diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_inits.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..840bad086dd74290c5538555966f1343b57ba5f9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_inits.py @@ -0,0 +1,374 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that checks the custom inits of Transformers are well-defined: Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. The goal of this +script is to check the objects defined in both halves are the same. + +This also checks the main init properly references all submodules, even if it doesn't import anything from them: every +submodule should be defined as a key of `_import_structure`, with an empty list as value potentially, or the submodule +won't be importable. + +Use from the root of the repo with: + +```bash +python utils/check_inits.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +There is no auto-fix possible here sadly :-( +""" + +import collections +import os +import re +from pathlib import Path +from typing import Dict, List, Optional, Tuple + + +# Path is set with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + + +# Matches is_xxx_available() +_re_backend = re.compile(r"is\_([a-z_]*)_available()") +# Catches a one-line _import_struct = {xxx} +_re_one_line_import_struct = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}") +# Catches a line with a key-values pattern: "bla": ["foo", "bar"] +_re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') +# Catches a line if not is_foo_available +_re_test_backend = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") +# Catches a line _import_struct["bla"].append("foo") +_re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') +# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] +_re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") +# Catches a line with an object between quotes and a comma: "MyModel", +_re_quote_object = re.compile(r'^\s+"([^"]+)",') +# Catches a line with objects between brackets only: ["foo", "bar"], +_re_between_brackets = re.compile(r"^\s+\[([^\]]+)\]") +# Catches a line with from foo import bar, bla, boo +_re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") +# Catches a line with try: +_re_try = re.compile(r"^\s*try:") +# Catches a line with else: +_re_else = re.compile(r"^\s*else:") + + +def find_backend(line: str) -> Optional[str]: + """ + Find one (or multiple) backend in a code line of the init. + + Args: + line (`str`): A code line of the main init. + + Returns: + Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line + contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so + `xxx_and_yyy` for instance). + """ + if _re_test_backend.search(line) is None: + return None + backends = [b[0] for b in _re_backend.findall(line)] + backends.sort() + return "_and_".join(backends) + + +def parse_init(init_file) -> Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]: + """ + Read an init_file and parse (per backend) the `_import_structure` objects defined and the `TYPE_CHECKING` objects + defined. + + Args: + init_file (`str`): Path to the init file to inspect. + + Returns: + `Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]`: A tuple of two dictionaries mapping backends to list of + imported objects, one for the `_import_structure` part of the init and one for the `TYPE_CHECKING` part of the + init. Returns `None` if the init is not a custom init. + """ + with open(init_file, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Get the to `_import_structure` definition. + line_index = 0 + while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"): + line_index += 1 + + # If this is a traditional init, just return. + if line_index >= len(lines): + return None + + # First grab the objects without a specific backend in _import_structure + objects = [] + while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None: + line = lines[line_index] + # If we have everything on a single line, let's deal with it. + if _re_one_line_import_struct.search(line): + content = _re_one_line_import_struct.search(line).groups()[0] + imports = re.findall(r"\[([^\]]+)\]", content) + for imp in imports: + objects.extend([obj[1:-1] for obj in imp.split(", ")]) + line_index += 1 + continue + single_line_import_search = _re_import_struct_key_value.search(line) + if single_line_import_search is not None: + imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0] + objects.extend(imports) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + line_index += 1 + + # Those are stored with the key "none". + import_dict_objects = {"none": objects} + + # Let's continue with backend-specific objects in _import_structure + while not lines[line_index].startswith("if TYPE_CHECKING"): + # If the line is an if not is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4): + line = lines[line_index] + if _re_import_struct_add_one.search(line) is not None: + objects.append(_re_import_struct_add_one.search(line).groups()[0]) + elif _re_import_struct_add_many.search(line) is not None: + imports = _re_import_struct_add_many.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_between_brackets.search(line) is not None: + imports = _re_between_brackets.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_quote_object.search(line) is not None: + objects.append(_re_quote_object.search(line).groups()[0]) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + elif line.startswith(" " * 12 + '"'): + objects.append(line[13:-3]) + line_index += 1 + + import_dict_objects[backend] = objects + else: + line_index += 1 + + # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend + objects = [] + while ( + line_index < len(lines) + and find_backend(lines[line_index]) is None + and not lines[line_index].startswith("else") + ): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 8): + objects.append(line[8:-2]) + line_index += 1 + + type_hint_objects = {"none": objects} + + # Let's continue with backend-specific objects + while line_index < len(lines): + # If the line is an if is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 12): + objects.append(line[12:-2]) + line_index += 1 + + type_hint_objects[backend] = objects + else: + line_index += 1 + + return import_dict_objects, type_hint_objects + + +def analyze_results(import_dict_objects: Dict[str, List[str]], type_hint_objects: Dict[str, List[str]]) -> List[str]: + """ + Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init. + + Args: + import_dict_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + type_hint_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + + Returns: + `List[str]`: The list of errors corresponding to mismatches. + """ + + def find_duplicates(seq): + return [k for k, v in collections.Counter(seq).items() if v > 1] + + # If one backend is missing from the other part of the init, error early. + if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): + return ["Both sides of the init do not have the same backends!"] + + errors = [] + # Find all errors. + for key in import_dict_objects.keys(): + # Duplicate imports in any half. + duplicate_imports = find_duplicates(import_dict_objects[key]) + if duplicate_imports: + errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}") + duplicate_type_hints = find_duplicates(type_hint_objects[key]) + if duplicate_type_hints: + errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}") + + # Missing imports in either part of the init. + if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): + name = "base imports" if key == "none" else f"{key} backend" + errors.append(f"Differences for {name}:") + for a in type_hint_objects[key]: + if a not in import_dict_objects[key]: + errors.append(f" {a} in TYPE_HINT but not in _import_structure.") + for a in import_dict_objects[key]: + if a not in type_hint_objects[key]: + errors.append(f" {a} in _import_structure but not in TYPE_HINT.") + return errors + + +def check_all_inits(): + """ + Check all inits in the transformers repo and raise an error if at least one does not define the same objects in + both halves. + """ + failures = [] + for root, _, files in os.walk(PATH_TO_TRANSFORMERS): + if "__init__.py" in files: + fname = os.path.join(root, "__init__.py") + objects = parse_init(fname) + if objects is not None: + errors = analyze_results(*objects) + if len(errors) > 0: + errors[0] = f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" + failures.append("\n".join(errors)) + if len(failures) > 0: + raise ValueError("\n\n".join(failures)) + + +def get_transformers_submodules() -> List[str]: + """ + Returns the list of Transformers submodules. + """ + submodules = [] + for path, directories, files in os.walk(PATH_TO_TRANSFORMERS): + for folder in directories: + # Ignore private modules + if folder.startswith("_"): + directories.remove(folder) + continue + # Ignore leftovers from branches (empty folders apart from pycache) + if len(list((Path(path) / folder).glob("*.py"))) == 0: + continue + short_path = str((Path(path) / folder).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(os.path.sep, ".") + submodules.append(submodule) + for fname in files: + if fname == "__init__.py": + continue + short_path = str((Path(path) / fname).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(".py", "").replace(os.path.sep, ".") + if len(submodule.split(".")) == 1: + submodules.append(submodule) + return submodules + + +IGNORE_SUBMODULES = [ + "convert_pytorch_checkpoint_to_tf2", + "modeling_flax_pytorch_utils", + "models.esm.openfold_utils", + "modeling_attn_mask_utils", + "safetensors_conversion", + "modeling_gguf_pytorch_utils", + "kernels.falcon_mamba", + "kernels", +] + + +def check_submodules(): + """ + Check all submodules of Transformers are properly registered in the main init. Error otherwise. + """ + # This is to make sure the transformers module imported is the one in the repo. + from transformers.utils import direct_transformers_import + + transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + import_structure_keys = set(transformers._import_structure.keys()) + # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing + # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and + # (potentiall re-) add them. + with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r") as f: + init_content = f.read() + import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]", init_content))) + + module_not_registered = [ + module + for module in get_transformers_submodules() + if module not in IGNORE_SUBMODULES and module not in import_structure_keys + ] + + if len(module_not_registered) > 0: + list_of_modules = "\n".join(f"- {module}" for module in module_not_registered) + raise ValueError( + "The following submodules are not properly registed in the main init of Transformers:\n" + f"{list_of_modules}\n" + "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." + ) + + +if __name__ == "__main__": + check_all_inits() + check_submodules() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_model_tester.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_model_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..8ace411b1a4e7db68fcc1a0ed874dfc3005721a1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_model_tester.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import glob +import os + +from get_test_info import get_tester_classes + + +if __name__ == "__main__": + failures = [] + + pattern = os.path.join("tests", "models", "**", "test_modeling_*.py") + test_files = glob.glob(pattern) + # TODO: deal with TF/Flax too + test_files = [ + x for x in test_files if not (x.startswith("test_modeling_tf_") or x.startswith("test_modeling_flax_")) + ] + + for test_file in test_files: + tester_classes = get_tester_classes(test_file) + for tester_class in tester_classes: + # A few tester classes don't have `parent` parameter in `__init__`. + # TODO: deal this better + try: + tester = tester_class(parent=None) + except Exception: + continue + if hasattr(tester, "get_config"): + config = tester.get_config() + for k, v in config.to_dict().items(): + if isinstance(v, int): + target = None + if k in ["vocab_size"]: + target = 100 + elif k in ["max_position_embeddings"]: + target = 128 + elif k in ["hidden_size", "d_model"]: + target = 40 + elif k == ["num_layers", "num_hidden_layers", "num_encoder_layers", "num_decoder_layers"]: + target = 5 + if target is not None and v > target: + failures.append( + f"{tester_class.__name__} will produce a `config` of type `{config.__class__.__name__}`" + f' with config["{k}"] = {v} which is too large for testing! Set its value to be smaller' + f" than {target}." + ) + + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_modular_conversion.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_modular_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..5406809cddc1cabde4dbe876c6d390c2f3b5289b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_modular_conversion.py @@ -0,0 +1,177 @@ +import argparse +import difflib +import glob +import logging +import subprocess +from io import StringIO + +from create_dependency_mapping import find_priority_list + +# Console for rich printing +from modular_model_converter import convert_modular_file +from rich.console import Console +from rich.syntax import Syntax + + +logging.basicConfig() +logging.getLogger().setLevel(logging.ERROR) +console = Console() + + +def process_file(modular_file_path, generated_modeling_content, file_type="modeling_", fix_and_overwrite=False): + file_name_prefix = file_type.split("*")[0] + file_name_suffix = file_type.split("*")[-1] if "*" in file_type else "" + file_path = modular_file_path.replace("modular_", f"{file_name_prefix}_").replace(".py", f"{file_name_suffix}.py") + # Read the actual modeling file + with open(file_path, "r", encoding="utf-8") as modeling_file: + content = modeling_file.read() + output_buffer = StringIO(generated_modeling_content[file_type][0]) + output_buffer.seek(0) + output_content = output_buffer.read() + diff = difflib.unified_diff( + output_content.splitlines(), + content.splitlines(), + fromfile=f"{file_path}_generated", + tofile=f"{file_path}", + lineterm="", + ) + diff_list = list(diff) + # Check for differences + if diff_list: + if fix_and_overwrite: + with open(file_path, "w", encoding="utf-8", newline="\n") as modeling_file: + modeling_file.write(generated_modeling_content[file_type][0]) + console.print(f"[bold blue]Overwritten {file_path} with the generated content.[/bold blue]") + else: + console.print(f"\n[bold red]Differences found between the generated code and {file_path}:[/bold red]\n") + diff_text = "\n".join(diff_list) + syntax = Syntax(diff_text, "diff", theme="ansi_dark", line_numbers=True) + console.print(syntax) + return 1 + else: + console.print(f"[bold green]No differences found for {file_path}.[/bold green]") + return 0 + + +def compare_files(modular_file_path, fix_and_overwrite=False): + # Generate the expected modeling content + generated_modeling_content = convert_modular_file(modular_file_path) + diff = 0 + for file_type in generated_modeling_content.keys(): + diff += process_file(modular_file_path, generated_modeling_content, file_type, fix_and_overwrite) + return diff + + +def get_models_in_diff(): + """ + Finds all models that have been modified in the diff. + + Returns: + A set containing the names of the models that have been modified (e.g. {'llama', 'whisper'}). + """ + fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") + modified_files = ( + subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()) + .decode("utf-8") + .split() + ) + + # Matches both modelling files and tests + relevant_modified_files = [x for x in modified_files if "/models/" in x and x.endswith(".py")] + model_names = set() + for file_path in relevant_modified_files: + model_name = file_path.split("/")[-2] + model_names.add(model_name) + return model_names + + +def guaranteed_no_diff(modular_file_path, dependencies, models_in_diff): + """ + Returns whether it is guaranteed to have no differences between the modular file and the modeling file. + + Model is in the diff -> not guaranteed to have no differences + Dependency is in the diff -> not guaranteed to have no differences + Otherwise -> guaranteed to have no differences + + Args: + modular_file_path: The path to the modular file. + dependencies: A dictionary containing the dependencies of each modular file. + models_in_diff: A set containing the names of the models that have been modified. + + Returns: + A boolean indicating whether the model (code and tests) is guaranteed to have no differences. + """ + model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "") + if model_name in models_in_diff: + return False + for dep in dependencies[modular_file_path]: + # two possible patterns: `transformers.models.model_name.(...)` or `model_name.(...)` + dependency_model_name = dep.split(".")[-2] + if dependency_model_name in models_in_diff: + return False + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Compare modular_xxx.py files with modeling_xxx.py files.") + parser.add_argument( + "--files", default=["all"], type=list, nargs="+", help="List of modular_xxx.py files to compare." + ) + parser.add_argument( + "--fix_and_overwrite", action="store_true", help="Overwrite the modeling_xxx.py file if differences are found." + ) + parser.add_argument( + "--num_workers", + default=1, + type=int, + help="The number of workers to run. No effect if `fix_and_overwrite` is specified.", + ) + args = parser.parse_args() + if args.files == ["all"]: + args.files = glob.glob("src/transformers/models/**/modular_*.py", recursive=True) + + # Assuming there is a topological sort on the dependency mapping: if the file being checked and its dependencies + # are not in the diff, then there it is guaranteed to have no differences. If no models are in the diff, then this + # script will do nothing. + models_in_diff = get_models_in_diff() + if not models_in_diff: + console.print("[bold green]No models files or model tests in the diff, skipping modular checks[/bold green]") + exit(0) + + skipped_models = set() + non_matching_files = 0 + ordered_files, dependencies = find_priority_list(args.files) + if args.fix_and_overwrite or args.num_workers == 1: + for modular_file_path in ordered_files: + is_guaranteed_no_diff = guaranteed_no_diff(modular_file_path, dependencies, models_in_diff) + if is_guaranteed_no_diff: + model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "") + skipped_models.add(model_name) + continue + non_matching_files += compare_files(modular_file_path, args.fix_and_overwrite) + models_in_diff = get_models_in_diff() # When overwriting, the diff changes + else: + new_ordered_files = [] + for modular_file_path in ordered_files: + is_guaranteed_no_diff = guaranteed_no_diff(modular_file_path, dependencies, models_in_diff) + if is_guaranteed_no_diff: + model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "") + skipped_models.add(model_name) + else: + new_ordered_files.append(modular_file_path) + + import multiprocessing + + with multiprocessing.Pool(args.num_workers) as p: + outputs = p.map(compare_files, new_ordered_files) + for output in outputs: + non_matching_files += output + + if non_matching_files and not args.fix_and_overwrite: + raise ValueError("Some diff and their modeling code did not match.") + + if skipped_models: + console.print( + f"[bold green]Skipped {len(skipped_models)} models and their dependencies that are not in the diff: " + f"{', '.join(skipped_models)}[/bold green]" + ) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_repo.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_repo.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3dddf9cf63d15dd85eb30747a1939181fa44c1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_repo.py @@ -0,0 +1,1222 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that performs several consistency checks on the repo. This includes: +- checking all models are properly defined in the __init__ of models/ +- checking all models are in the main __init__ +- checking all models are properly tested +- checking all object in the main __init__ are documented +- checking all models are in at least one auto class +- checking all the auto mapping are properly defined (no typos, importable) +- checking the list of deprecated models is up to date + +Use from the root of the repo with (as used in `make repo-consistency`): + +```bash +python utils/check_repo.py +``` + +It has no auto-fix mode. +""" + +import os +import re +import sys +import types +import warnings +from collections import OrderedDict +from difflib import get_close_matches +from pathlib import Path +from typing import List, Tuple + +from transformers import is_flax_available, is_tf_available, is_torch_available +from transformers.models.auto import get_values +from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES +from transformers.models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES +from transformers.models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES +from transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES +from transformers.models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES +from transformers.utils import ENV_VARS_TRUE_VALUES, direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_repo.py +PATH_TO_TRANSFORMERS = "src/transformers" +PATH_TO_TESTS = "tests" +PATH_TO_DOC = "docs/source/en" + +# Update this list with models that are supposed to be private. +PRIVATE_MODELS = [ + "AltRobertaModel", + "DPRSpanPredictor", + "UdopStack", + "LongT5Stack", + "RealmBertModel", + "T5Stack", + "MT5Stack", + "UMT5Stack", + "Pop2PianoStack", + "Qwen2AudioEncoder", + "Qwen2VisionTransformerPretrainedModel", + "Qwen2_5_VisionTransformerPretrainedModel", + "SwitchTransformersStack", + "TFDPRSpanPredictor", + "MaskFormerSwinModel", + "MaskFormerSwinPreTrainedModel", + "BridgeTowerTextModel", + "BridgeTowerVisionModel", + "Kosmos2TextModel", + "Kosmos2TextForCausalLM", + "Kosmos2VisionModel", + "SeamlessM4Tv2TextToUnitModel", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2TextToUnitForConditionalGeneration", + "Idefics2PerceiverResampler", + "Idefics2VisionTransformer", + "Idefics3VisionTransformer", + "SmolVLMVisionTransformer", + "AriaTextForCausalLM", + "AriaTextModel", +] + +# Update this list for models that are not tested with a comment explaining the reason it should not be. +# Being in this list is an exception and should **not** be the rule. +IGNORE_NON_TESTED = ( + PRIVATE_MODELS.copy() + + [ + # models to ignore for not tested + "RecurrentGemmaModel", # Building part of bigger (tested) model. + "FuyuForCausalLM", # Not tested fort now + "InstructBlipQFormerModel", # Building part of bigger (tested) model. + "InstructBlipVideoQFormerModel", # Building part of bigger (tested) model. + "UMT5EncoderModel", # Building part of bigger (tested) model. + "Blip2QFormerModel", # Building part of bigger (tested) model. + "ErnieMForInformationExtraction", + "FastSpeech2ConformerHifiGan", # Already tested by SpeechT5HifiGan (# Copied from) + "FastSpeech2ConformerWithHifiGan", # Built with two smaller (tested) models. + "GraphormerDecoderHead", # Building part of bigger (tested) model. + "JukeboxVQVAE", # Building part of bigger (tested) model. + "JukeboxPrior", # Building part of bigger (tested) model. + "DecisionTransformerGPT2Model", # Building part of bigger (tested) model. + "SegformerDecodeHead", # Building part of bigger (tested) model. + "MgpstrModel", # Building part of bigger (tested) model. + "BertLMHeadModel", # Needs to be setup as decoder. + "MegatronBertLMHeadModel", # Building part of bigger (tested) model. + "RealmBertModel", # Building part of bigger (tested) model. + "RealmReader", # Not regular model. + "RealmScorer", # Not regular model. + "RealmForOpenQA", # Not regular model. + "ReformerForMaskedLM", # Needs to be setup as decoder. + "TFElectraMainLayer", # Building part of bigger (tested) model (should it be a TFPreTrainedModel ?) + "TFRobertaForMultipleChoice", # TODO: fix + "TFRobertaPreLayerNormForMultipleChoice", # TODO: fix + "SeparableConv1D", # Building part of bigger (tested) model. + "FlaxBartForCausalLM", # Building part of bigger (tested) model. + "FlaxBertForCausalLM", # Building part of bigger (tested) model. Tested implicitly through FlaxRobertaForCausalLM. + "OPTDecoderWrapper", + "TFSegformerDecodeHead", # Not a regular model. + "AltRobertaModel", # Building part of bigger (tested) model. + "BlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "TFBlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "BridgeTowerTextModel", # No need to test it as it is tested by BridgeTowerModel model. + "BridgeTowerVisionModel", # No need to test it as it is tested by BridgeTowerModel model. + "BarkCausalModel", # Building part of bigger (tested) model. + "BarkModel", # Does not have a forward signature - generation tested with integration tests. + "SeamlessM4TTextToUnitModel", # Building part of bigger (tested) model. + "SeamlessM4TCodeHifiGan", # Building part of bigger (tested) model. + "SeamlessM4TTextToUnitForConditionalGeneration", # Building part of bigger (tested) model. + "ChameleonVQVAE", # VQVAE here is used only for encoding (discretizing) and is tested as part of bigger model + "Qwen2VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2VLForConditionalGeneration. + "Qwen2_5_VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5_VLForConditionalGeneration. + "MllamaTextModel", # Building part of bigger (tested) model. # TODO: add tests + "MllamaVisionModel", # Building part of bigger (tested) model. # TODO: add tests + "Emu3VQVAE", # Building part of bigger (tested) model + "Emu3TextModel", # Building part of bigger (tested) model + ] +) + +# Update this list with test files that don't have a tester with a `all_model_classes` variable and which don't +# trigger the common tests. +TEST_FILES_WITH_NO_COMMON_TESTS = [ + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/camembert/test_modeling_camembert.py", + "models/mt5/test_modeling_flax_mt5.py", + "models/mbart/test_modeling_mbart.py", + "models/mt5/test_modeling_mt5.py", + "models/pegasus/test_modeling_pegasus.py", + "models/camembert/test_modeling_tf_camembert.py", + "models/mt5/test_modeling_tf_mt5.py", + "models/xlm_roberta/test_modeling_tf_xlm_roberta.py", + "models/xlm_roberta/test_modeling_flax_xlm_roberta.py", + "models/xlm_prophetnet/test_modeling_xlm_prophetnet.py", + "models/xlm_roberta/test_modeling_xlm_roberta.py", + "models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py", + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/bark/test_modeling_bark.py", +] + +# Update this list for models that are not in any of the auto MODEL_XXX_MAPPING. Being in this list is an exception and +# should **not** be the rule. +IGNORE_NON_AUTO_CONFIGURED = PRIVATE_MODELS.copy() + [ + # models to ignore for model xxx mapping + "AlignTextModel", + "AlignVisionModel", + "ClapTextModel", + "ClapTextModelWithProjection", + "ClapAudioModel", + "ClapAudioModelWithProjection", + "Blip2TextModelWithProjection", + "Blip2VisionModelWithProjection", + "Blip2QFormerModel", + "Blip2VisionModel", + "ErnieMForInformationExtraction", + "FastSpeech2ConformerHifiGan", + "FastSpeech2ConformerWithHifiGan", + "GitVisionModel", + "GraphormerModel", + "GraphormerForGraphClassification", + "BlipForImageTextRetrieval", + "BlipForQuestionAnswering", + "BlipVisionModel", + "BlipTextLMHeadModel", + "BlipTextModel", + "BrosSpadeEEForTokenClassification", + "BrosSpadeELForTokenClassification", + "TFBlipForConditionalGeneration", + "TFBlipForImageTextRetrieval", + "TFBlipForQuestionAnswering", + "TFBlipVisionModel", + "TFBlipTextLMHeadModel", + "TFBlipTextModel", + "Swin2SRForImageSuperResolution", + "BridgeTowerForImageAndTextRetrieval", + "BridgeTowerForMaskedLM", + "BridgeTowerForContrastiveLearning", + "CLIPSegForImageSegmentation", + "CLIPSegVisionModel", + "CLIPSegTextModel", + "EsmForProteinFolding", + "GPTSanJapaneseModel", + "TimeSeriesTransformerForPrediction", + "InformerForPrediction", + "AutoformerForPrediction", + "PatchTSTForPretraining", + "PatchTSTForPrediction", + "JukeboxVQVAE", + "JukeboxPrior", + "SamModel", + "DPTForDepthEstimation", + "DecisionTransformerGPT2Model", + "GLPNForDepthEstimation", + "ViltForImagesAndTextClassification", + "ViltForImageAndTextRetrieval", + "ViltForTokenClassification", + "ViltForMaskedLM", + "PerceiverForMultimodalAutoencoding", + "PerceiverForOpticalFlow", + "SegformerDecodeHead", + "TFSegformerDecodeHead", + "FlaxBeitForMaskedImageModeling", + "BeitForMaskedImageModeling", + "ChineseCLIPTextModel", + "ChineseCLIPVisionModel", + "CLIPTextModelWithProjection", + "CLIPVisionModelWithProjection", + "ClvpForCausalLM", + "ClvpModel", + "GroupViTTextModel", + "GroupViTVisionModel", + "TFCLIPTextModel", + "TFCLIPVisionModel", + "TFGroupViTTextModel", + "TFGroupViTVisionModel", + "FlaxCLIPTextModel", + "FlaxCLIPTextModelWithProjection", + "FlaxCLIPVisionModel", + "FlaxWav2Vec2ForCTC", + "DetrForSegmentation", + "Pix2StructVisionModel", + "Pix2StructTextModel", + "ConditionalDetrForSegmentation", + "DPRReader", + "FlaubertForQuestionAnswering", + "FlavaImageCodebook", + "FlavaTextModel", + "FlavaImageModel", + "FlavaMultimodalModel", + "GPT2DoubleHeadsModel", + "GPTSw3DoubleHeadsModel", + "InstructBlipVisionModel", + "InstructBlipQFormerModel", + "InstructBlipVideoVisionModel", + "InstructBlipVideoQFormerModel", + "LayoutLMForQuestionAnswering", + "LukeForMaskedLM", + "LukeForEntityClassification", + "LukeForEntityPairClassification", + "LukeForEntitySpanClassification", + "MgpstrModel", + "OpenAIGPTDoubleHeadsModel", + "OwlViTTextModel", + "OwlViTVisionModel", + "Owlv2TextModel", + "Owlv2VisionModel", + "OwlViTForObjectDetection", + "PatchTSMixerForPrediction", + "PatchTSMixerForPretraining", + "RagModel", + "RagSequenceForGeneration", + "RagTokenForGeneration", + "RealmEmbedder", + "RealmForOpenQA", + "RealmScorer", + "RealmReader", + "TFDPRReader", + "TFGPT2DoubleHeadsModel", + "TFLayoutLMForQuestionAnswering", + "TFOpenAIGPTDoubleHeadsModel", + "TFRagModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + "Wav2Vec2ForCTC", + "HubertForCTC", + "SEWForCTC", + "SEWDForCTC", + "XLMForQuestionAnswering", + "XLNetForQuestionAnswering", + "SeparableConv1D", + "VisualBertForRegionToPhraseAlignment", + "VisualBertForVisualReasoning", + "VisualBertForQuestionAnswering", + "VisualBertForMultipleChoice", + "TFWav2Vec2ForCTC", + "TFHubertForCTC", + "XCLIPVisionModel", + "XCLIPTextModel", + "AltCLIPTextModel", + "AltCLIPVisionModel", + "AltRobertaModel", + "TvltForAudioVisualClassification", + "BarkCausalModel", + "BarkCoarseModel", + "BarkFineModel", + "BarkSemanticModel", + "MusicgenMelodyModel", + "MusicgenModel", + "MusicgenForConditionalGeneration", + "SpeechT5ForSpeechToSpeech", + "SpeechT5ForTextToSpeech", + "SpeechT5HifiGan", + "VitMatteForImageMatting", + "SeamlessM4TTextToUnitModel", + "SeamlessM4TTextToUnitForConditionalGeneration", + "SeamlessM4TCodeHifiGan", + "SeamlessM4TForSpeechToSpeech", # no auto class for speech-to-speech + "TvpForVideoGrounding", + "SeamlessM4Tv2NARTextToUnitModel", + "SeamlessM4Tv2NARTextToUnitForConditionalGeneration", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2ForSpeechToSpeech", # no auto class for speech-to-speech + "SegGptForImageSegmentation", + "SiglipVisionModel", + "SiglipTextModel", + "Siglip2VisionModel", + "Siglip2TextModel", + "ChameleonVQVAE", # no autoclass for VQ-VAE models + "VitPoseForPoseEstimation", + "CLIPTextModel", + "MoshiForConditionalGeneration", # no auto class for speech-to-speech + "Emu3VQVAE", # no autoclass for VQ-VAE models + "Emu3TextModel", # Building part of bigger (tested) model +] + +# DO NOT edit this list! +# (The corresponding pytorch objects should never have been in the main `__init__`, but it's too late to remove) +OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK = [ + "FlaxBertLayer", + "FlaxBigBirdLayer", + "FlaxRoFormerLayer", + "TFBertLayer", + "TFLxmertEncoder", + "TFLxmertXLayer", + "TFMPNetLayer", + "TFMobileBertLayer", + "TFSegformerLayer", + "TFViTMAELayer", +] + +# Update this list for models that have multiple model types for the same model doc. +MODEL_TYPE_TO_DOC_MAPPING = OrderedDict( + [ + ("data2vec-text", "data2vec"), + ("data2vec-audio", "data2vec"), + ("data2vec-vision", "data2vec"), + ("donut-swin", "donut"), + ] +) + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + +def check_missing_backends(): + """ + Checks if all backends are installed (otherwise the check of this script is incomplete). Will error in the CI if + that's not the case but only throw a warning for users running this. + """ + missing_backends = [] + if not is_torch_available(): + missing_backends.append("PyTorch") + if not is_tf_available(): + missing_backends.append("TensorFlow") + if not is_flax_available(): + missing_backends.append("Flax") + if len(missing_backends) > 0: + missing = ", ".join(missing_backends) + if os.getenv("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES: + raise Exception( + "Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the " + f"Transformers repo, the following are missing: {missing}." + ) + else: + warnings.warn( + "Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the " + f"Transformers repo, the following are missing: {missing}. While it's probably fine as long as you " + "didn't make any change in one of those backends modeling files, you should probably execute the " + "command above to be on the safe side." + ) + + +def check_model_list(): + """ + Checks the model listed as subfolders of `models` match the models available in `transformers.models`. + """ + # Get the models from the directory structure of `src/transformers/models/` + models_dir = os.path.join(PATH_TO_TRANSFORMERS, "models") + _models = [] + for model in os.listdir(models_dir): + if model == "deprecated": + continue + model_dir = os.path.join(models_dir, model) + if os.path.isdir(model_dir) and "__init__.py" in os.listdir(model_dir): + _models.append(model) + + # Get the models in the submodule `transformers.models` + models = [model for model in dir(transformers.models) if not model.startswith("__")] + + missing_models = sorted(set(_models).difference(models)) + if missing_models: + raise Exception( + f"The following models should be included in {models_dir}/__init__.py: {','.join(missing_models)}." + ) + + +# If some modeling modules should be ignored for all checks, they should be added in the nested list +# _ignore_modules of this function. +def get_model_modules() -> List[str]: + """Get all the model modules inside the transformers library (except deprecated models).""" + _ignore_modules = [ + "modeling_auto", + "modeling_encoder_decoder", + "modeling_marian", + "modeling_retribert", + "modeling_flax_auto", + "modeling_flax_encoder_decoder", + "modeling_speech_encoder_decoder", + "modeling_flax_speech_encoder_decoder", + "modeling_flax_vision_encoder_decoder", + "modeling_timm_backbone", + "modeling_tf_auto", + "modeling_tf_encoder_decoder", + "modeling_tf_vision_encoder_decoder", + "modeling_vision_encoder_decoder", + ] + modules = [] + for model in dir(transformers.models): + # There are some magic dunder attributes in the dir, we ignore them + if model == "deprecated" or model.startswith("__"): + continue + + model_module = getattr(transformers.models, model) + for submodule in dir(model_module): + if submodule.startswith("modeling") and submodule not in _ignore_modules: + modeling_module = getattr(model_module, submodule) + modules.append(modeling_module) + return modules + + +def get_models(module: types.ModuleType, include_pretrained: bool = False) -> List[Tuple[str, type]]: + """ + Get the objects in a module that are models. + + Args: + module (`types.ModuleType`): + The module from which we are extracting models. + include_pretrained (`bool`, *optional*, defaults to `False`): + Whether or not to include the `PreTrainedModel` subclass (like `BertPreTrainedModel`) or not. + + Returns: + List[Tuple[str, type]]: List of models as tuples (class name, actual class). + """ + models = [] + model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel) + for attr_name in dir(module): + if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name): + continue + attr = getattr(module, attr_name) + if isinstance(attr, type) and issubclass(attr, model_classes) and attr.__module__ == module.__name__: + models.append((attr_name, attr)) + return models + + +def is_building_block(model: str) -> bool: + """ + Returns `True` if a model is a building block part of a bigger model. + """ + if model.endswith("Wrapper"): + return True + if model.endswith("Encoder"): + return True + if model.endswith("Decoder"): + return True + if model.endswith("Prenet"): + return True + + +def is_a_private_model(model: str) -> bool: + """Returns `True` if the model should not be in the main init.""" + if model in PRIVATE_MODELS: + return True + return is_building_block(model) + + +def check_models_are_in_init(): + """Checks all models defined in the library are in the main init.""" + models_not_in_init = [] + dir_transformers = dir(transformers) + for module in get_model_modules(): + models_not_in_init += [ + model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers + ] + + # Remove private models + models_not_in_init = [model for model in models_not_in_init if not is_a_private_model(model)] + if len(models_not_in_init) > 0: + raise Exception(f"The following models should be in the main init: {','.join(models_not_in_init)}.") + + +# If some test_modeling files should be ignored when checking models are all tested, they should be added in the +# nested list _ignore_files of this function. +def get_model_test_files() -> List[str]: + """ + Get the model test files. + + Returns: + `List[str]`: The list of test files. The returned files will NOT contain the `tests` (i.e. `PATH_TO_TESTS` + defined in this script). They will be considered as paths relative to `tests`. A caller has to use + `os.path.join(PATH_TO_TESTS, ...)` to access the files. + """ + + _ignore_files = [ + "test_modeling_common", + "test_modeling_encoder_decoder", + "test_modeling_flax_encoder_decoder", + "test_modeling_flax_speech_encoder_decoder", + "test_modeling_marian", + "test_modeling_tf_common", + "test_modeling_tf_encoder_decoder", + ] + test_files = [] + model_test_root = os.path.join(PATH_TO_TESTS, "models") + model_test_dirs = [] + for x in os.listdir(model_test_root): + x = os.path.join(model_test_root, x) + if os.path.isdir(x): + model_test_dirs.append(x) + + for target_dir in [PATH_TO_TESTS] + model_test_dirs: + for file_or_dir in os.listdir(target_dir): + path = os.path.join(target_dir, file_or_dir) + if os.path.isfile(path): + filename = os.path.split(path)[-1] + if "test_modeling" in filename and os.path.splitext(filename)[0] not in _ignore_files: + file = os.path.join(*path.split(os.sep)[1:]) + test_files.append(file) + + return test_files + + +# 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 +# for the all_model_classes variable. +def find_tested_models(test_file: str) -> List[str]: + """ + Parse the content of test_file to detect what's in `all_model_classes`. This detects the models that inherit from + the common test class. + + Args: + test_file (`str`): The path to the test file to check + + Returns: + `List[str]`: The list of models tested in that file. + """ + with open(os.path.join(PATH_TO_TESTS, test_file), "r", encoding="utf-8", newline="\n") as f: + content = f.read() + all_models = re.findall(r"all_model_classes\s+=\s+\(\s*\(([^\)]*)\)", content) + # Check with one less parenthesis as well + all_models += re.findall(r"all_model_classes\s+=\s+\(([^\)]*)\)", content) + if len(all_models) > 0: + model_tested = [] + for entry in all_models: + for line in entry.split(","): + name = line.strip() + if len(name) > 0: + model_tested.append(name) + return model_tested + + +def should_be_tested(model_name: str) -> bool: + """ + Whether or not a model should be tested. + """ + if model_name in IGNORE_NON_TESTED: + return False + return not is_building_block(model_name) + + +def check_models_are_tested(module: types.ModuleType, test_file: str) -> List[str]: + """Check models defined in a module are all tested in a given file. + + Args: + module (`types.ModuleType`): The module in which we get the models. + test_file (`str`): The path to the file where the module is tested. + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + # XxxPreTrainedModel are not tested + defined_models = get_models(module) + tested_models = find_tested_models(test_file) + if tested_models is None: + if test_file.replace(os.path.sep, "/") in TEST_FILES_WITH_NO_COMMON_TESTS: + return + return [ + f"{test_file} should define `all_model_classes` to apply common tests to the models it tests. " + + "If this intentional, add the test filename to `TEST_FILES_WITH_NO_COMMON_TESTS` in the file " + + "`utils/check_repo.py`." + ] + failures = [] + for model_name, _ in defined_models: + if model_name not in tested_models and should_be_tested(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not tested in " + + f"{os.path.join(PATH_TO_TESTS, test_file)}. Add it to the all_model_classes in that file." + + "If common tests should not applied to that model, add its name to `IGNORE_NON_TESTED`" + + "in the file `utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_tested(): + """Check all models are properly tested.""" + modules = get_model_modules() + test_files = get_model_test_files() + failures = [] + for module in modules: + # Matches a module to its test file. + test_file = [file for file in test_files if f"test_{module.__name__.split('.')[-1]}.py" in file] + if len(test_file) == 0: + failures.append(f"{module.__name__} does not have its corresponding test file {test_file}.") + elif len(test_file) > 1: + failures.append(f"{module.__name__} has several test files: {test_file}.") + else: + test_file = test_file[0] + new_failures = check_models_are_tested(module, test_file) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def get_all_auto_configured_models() -> List[str]: + """Return the list of all models in at least one auto class.""" + result = set() # To avoid duplicates we concatenate all model classes in a set. + if is_torch_available(): + for attr_name in dir(transformers.models.auto.modeling_auto): + if attr_name.startswith("MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_auto, attr_name))) + if is_tf_available(): + for attr_name in dir(transformers.models.auto.modeling_tf_auto): + if attr_name.startswith("TF_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_tf_auto, attr_name))) + if is_flax_available(): + for attr_name in dir(transformers.models.auto.modeling_flax_auto): + if attr_name.startswith("FLAX_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_flax_auto, attr_name))) + return list(result) + + +def ignore_unautoclassed(model_name: str) -> bool: + """Rules to determine if a model should be in an auto class.""" + # Special white list + if model_name in IGNORE_NON_AUTO_CONFIGURED: + return True + # Encoder and Decoder should be ignored + if "Encoder" in model_name or "Decoder" in model_name: + return True + return False + + +def check_models_are_auto_configured(module: types.ModuleType, all_auto_models: List[str]) -> List[str]: + """ + Check models defined in module are each in an auto class. + + Args: + module (`types.ModuleType`): + The module in which we get the models. + all_auto_models (`List[str]`): + The list of all models in an auto class (as obtained with `get_all_auto_configured_models()`). + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + defined_models = get_models(module) + failures = [] + for model_name, _ in defined_models: + if model_name not in all_auto_models and not ignore_unautoclassed(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. " + "If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file " + "`utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_auto_configured(): + """Check all models are each in an auto class.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + modules = get_model_modules() + all_auto_models = get_all_auto_configured_models() + failures = [] + for module in modules: + new_failures = check_models_are_auto_configured(module, all_auto_models) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_object_names_being_defined(): + """Check all names defined in auto (name) mappings exist in the library.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = { + "TOKENIZER_MAPPING_NAMES": TOKENIZER_MAPPING_NAMES, + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for _, class_names in mapping.items(): + if not isinstance(class_names, tuple): + class_names = (class_names,) + for class_name in class_names: + if class_name is None: + continue + # dummy object is accepted + if not hasattr(transformers, class_name): + # If the class name is in a model name mapping, let's not check if there is a definition in any modeling + # module, if it's a private model defined in this file. + if name.endswith("MODEL_MAPPING_NAMES") and is_a_private_model(class_name): + continue + if name.endswith("MODEL_FOR_IMAGE_MAPPING_NAMES") and is_a_private_model(class_name): + continue + failures.append( + f"`{class_name}` appears in the mapping `{name}` but it is not defined in the library." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mapping_names_in_config_mapping_names(): + """Check all keys defined in auto mappings (mappings of names) appear in `CONFIG_MAPPING_NAMES`.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + # `TOKENIZER_PROCESSOR_MAPPING_NAMES` and `AutoTokenizer` is special, and don't need to follow the rule. + mappings_to_check = { + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for model_type in mapping: + if model_type not in CONFIG_MAPPING_NAMES: + failures.append( + f"`{model_type}` appears in the mapping `{name}` but it is not defined in the keys of " + "`CONFIG_MAPPING_NAMES`." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mappings_importable(): + """Check all auto mappings can be imported.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = {} + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name in mappings_to_check: + name = name.replace("_MAPPING_NAMES", "_MAPPING") + if not hasattr(transformers, name): + failures.append(f"`{name}`") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_objects_being_equally_in_main_init(): + """ + Check if a (TensorFlow or Flax) object is in the main __init__ iif its counterpart in PyTorch is. + """ + attrs = dir(transformers) + + failures = [] + for attr in attrs: + obj = getattr(transformers, attr) + if not hasattr(obj, "__module__") or "models.deprecated" in obj.__module__: + continue + + module_path = obj.__module__ + module_name = module_path.split(".")[-1] + module_dir = ".".join(module_path.split(".")[:-1]) + if ( + module_name.startswith("modeling_") + and not module_name.startswith("modeling_tf_") + and not module_name.startswith("modeling_flax_") + ): + parent_module = sys.modules[module_dir] + + frameworks = [] + if is_tf_available(): + frameworks.append("TF") + if is_flax_available(): + frameworks.append("Flax") + + for framework in frameworks: + other_module_path = module_path.replace("modeling_", f"modeling_{framework.lower()}_") + if os.path.isfile("src/" + other_module_path.replace(".", "/") + ".py"): + other_module_name = module_name.replace("modeling_", f"modeling_{framework.lower()}_") + other_module = getattr(parent_module, other_module_name) + if hasattr(other_module, f"{framework}{attr}"): + if not hasattr(transformers, f"{framework}{attr}"): + if f"{framework}{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}{attr}") + if hasattr(other_module, f"{framework}_{attr}"): + if not hasattr(transformers, f"{framework}_{attr}"): + if f"{framework}_{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}_{attr}") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +_re_decorator = re.compile(r"^\s*@(\S+)\s+$") + + +def check_decorator_order(filename: str) -> List[int]: + """ + Check that in a given test file, the slow decorator is always last. + + Args: + filename (`str`): The path to a test file to check. + + Returns: + `List[int]`: The list of failures as a list of indices where there are problems. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + decorator_before = None + errors = [] + for i, line in enumerate(lines): + search = _re_decorator.search(line) + if search is not None: + decorator_name = search.groups()[0] + if decorator_before is not None and decorator_name.startswith("parameterized"): + errors.append(i) + decorator_before = decorator_name + elif decorator_before is not None: + decorator_before = None + return errors + + +def check_all_decorator_order(): + """Check that in all test files, the slow decorator is always last.""" + errors = [] + for fname in os.listdir(PATH_TO_TESTS): + if fname.endswith(".py"): + filename = os.path.join(PATH_TO_TESTS, fname) + new_errors = check_decorator_order(filename) + errors += [f"- {filename}, line {i}" for i in new_errors] + if len(errors) > 0: + msg = "\n".join(errors) + raise ValueError( + "The parameterized decorator (and its variants) should always be first, but this is not the case in the" + f" following files:\n{msg}" + ) + + +def find_all_documented_objects() -> List[str]: + """ + Parse the content of all doc files to detect which classes and functions it documents. + + Returns: + `List[str]`: The list of all object names being documented. + `Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g. + `integrations.PeftAdapterMixin`) to its documented methods + """ + documented_obj = [] + documented_methods_map = {} + for doc_file in Path(PATH_TO_DOC).glob("**/*.md"): + with open(doc_file, "r", encoding="utf-8", newline="\n") as f: + content = f.read() + raw_doc_objs = re.findall(r"\[\[autodoc\]\]\s+(\S+)\s+", content) + documented_obj += [obj.split(".")[-1] for obj in raw_doc_objs] + + for obj in raw_doc_objs: + obj_public_methods = re.findall(rf"\[\[autodoc\]\] {obj}((\n\s+-.*)+)", content) + # Some objects have no methods documented + if len(obj_public_methods) == 0: + continue + else: + documented_methods_map[obj] = re.findall(r"(?<=-\s).*", obj_public_methods[0][0]) + + return documented_obj, documented_methods_map + + +# One good reason for not being documented is to be deprecated. Put in this list deprecated objects. +DEPRECATED_OBJECTS = [ + "AutoModelWithLMHead", + "BartPretrainedModel", + "DataCollator", + "DataCollatorForSOP", + "GlueDataset", + "GlueDataTrainingArguments", + "LineByLineTextDataset", + "LineByLineWithRefDataset", + "LineByLineWithSOPTextDataset", + "NerPipeline", + "PretrainedBartModel", + "PretrainedFSMTModel", + "SingleSentenceClassificationProcessor", + "SquadDataTrainingArguments", + "SquadDataset", + "SquadExample", + "SquadFeatures", + "SquadV1Processor", + "SquadV2Processor", + "TFAutoModelWithLMHead", + "TFBartPretrainedModel", + "TextDataset", + "TextDatasetForNextSentencePrediction", + "Wav2Vec2ForMaskedLM", + "Wav2Vec2Tokenizer", + "glue_compute_metrics", + "glue_convert_examples_to_features", + "glue_output_modes", + "glue_processors", + "glue_tasks_num_labels", + "squad_convert_examples_to_features", + "xnli_compute_metrics", + "xnli_output_modes", + "xnli_processors", + "xnli_tasks_num_labels", + "TFTrainingArguments", + "OwlViTFeatureExtractor", +] + +# Exceptionally, some objects should not be documented after all rules passed. +# ONLY PUT SOMETHING IN THIS LIST AS A LAST RESORT! +UNDOCUMENTED_OBJECTS = [ + "AddedToken", # This is a tokenizers class. + "BasicTokenizer", # Internal, should never have been in the main init. + "CharacterTokenizer", # Internal, should never have been in the main init. + "DPRPretrainedReader", # Like an Encoder. + "DummyObject", # Just picked by mistake sometimes. + "MecabTokenizer", # Internal, should never have been in the main init. + "ModelCard", # Internal type. + "SqueezeBertModule", # Internal building block (should have been called SqueezeBertLayer) + "TFDPRPretrainedReader", # Like an Encoder. + "TransfoXLCorpus", # Internal type. + "WordpieceTokenizer", # Internal, should never have been in the main init. + "absl", # External module + "add_end_docstrings", # Internal, should never have been in the main init. + "add_start_docstrings", # Internal, should never have been in the main init. + "convert_tf_weight_name_to_pt_weight_name", # Internal used to convert model weights + "logger", # Internal logger + "logging", # External module + "requires_backends", # Internal function + "AltRobertaModel", # Internal module + "VitPoseBackbone", # Internal module + "VitPoseBackboneConfig", # Internal module +] + +# This list should be empty. Objects in it should get their own doc page. +SHOULD_HAVE_THEIR_OWN_PAGE = [ + "AutoBackbone", + "BeitBackbone", + "BitBackbone", + "ConvNextBackbone", + "ConvNextV2Backbone", + "DinatBackbone", + "Dinov2Backbone", + "Dinov2WithRegistersBackbone", + "FocalNetBackbone", + "HieraBackbone", + "MaskFormerSwinBackbone", + "MaskFormerSwinConfig", + "MaskFormerSwinModel", + "NatBackbone", + "PvtV2Backbone", + "ResNetBackbone", + "SwinBackbone", + "Swinv2Backbone", + "TextNetBackbone", + "TimmBackbone", + "TimmBackboneConfig", + "VitDetBackbone", +] + + +def ignore_undocumented(name: str) -> bool: + """Rules to determine if `name` should be undocumented (returns `True` if it should not be documented).""" + # NOT DOCUMENTED ON PURPOSE. + # Constants uppercase are not documented. + if name.isupper(): + return True + # PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not documented. + if ( + name.endswith("PreTrainedModel") + or name.endswith("Decoder") + or name.endswith("Encoder") + or name.endswith("Layer") + or name.endswith("Embeddings") + or name.endswith("Attention") + ): + return True + # Submodules are not documented. + if os.path.isdir(os.path.join(PATH_TO_TRANSFORMERS, name)) or os.path.isfile( + os.path.join(PATH_TO_TRANSFORMERS, f"{name}.py") + ): + return True + # All load functions are not documented. + if name.startswith("load_tf") or name.startswith("load_pytorch"): + return True + # is_xxx_available functions are not documented. + if name.startswith("is_") and name.endswith("_available"): + return True + # Deprecated objects are not documented. + if name in DEPRECATED_OBJECTS or name in UNDOCUMENTED_OBJECTS: + return True + # MMBT model does not really work. + if name.startswith("MMBT"): + return True + if name in SHOULD_HAVE_THEIR_OWN_PAGE: + return True + return False + + +def check_all_objects_are_documented(): + """Check all models are properly documented.""" + documented_objs, documented_methods_map = find_all_documented_objects() + modules = transformers._modules + objects = [c for c in dir(transformers) if c not in modules and not c.startswith("_")] + undocumented_objs = [c for c in objects if c not in documented_objs and not ignore_undocumented(c)] + if len(undocumented_objs) > 0: + raise Exception( + "The following objects are in the public init so should be documented:\n - " + + "\n - ".join(undocumented_objs) + ) + check_model_type_doc_match() + check_public_method_exists(documented_methods_map) + + +def check_public_method_exists(documented_methods_map): + """Check that all explicitly documented public methods are defined in the corresponding class.""" + failures = [] + for obj, methods in documented_methods_map.items(): + # Let's ensure there is no repetition + if len(set(methods)) != len(methods): + failures.append(f"Error in the documentation of {obj}: there are repeated documented methods.") + + # Navigates into the object, given the full import path + nested_path = obj.split(".") + submodule = transformers + if len(nested_path) > 1: + nested_submodules = nested_path[:-1] + for submodule_name in nested_submodules: + if submodule_name == "transformers": + continue + + try: + submodule = getattr(submodule, submodule_name) + except AttributeError: + failures.append(f"Could not parse {submodule_name}. Are the required dependencies installed?") + continue + + class_name = nested_path[-1] + + try: + obj_class = getattr(submodule, class_name) + except AttributeError: + failures.append(f"Could not parse {class_name}. Are the required dependencies installed?") + continue + + # Checks that all explicitly documented methods are defined in the class + for method in methods: + if method == "all": # Special keyword to document all public methods + continue + try: + if not hasattr(obj_class, method): + failures.append( + "The following public method is explicitly documented but not defined in the corresponding " + f"class. class: {obj}, method: {method}. If the method is defined, this error can be due to " + f"lacking dependencies." + ) + except ImportError: + pass + + if len(failures) > 0: + raise Exception("\n".join(failures)) + + +def check_model_type_doc_match(): + """Check all doc pages have a corresponding model type.""" + model_doc_folder = Path(PATH_TO_DOC) / "model_doc" + model_docs = [m.stem for m in model_doc_folder.glob("*.md")] + + model_types = list(transformers.models.auto.configuration_auto.MODEL_NAMES_MAPPING.keys()) + model_types = [MODEL_TYPE_TO_DOC_MAPPING[m] if m in MODEL_TYPE_TO_DOC_MAPPING else m for m in model_types] + + errors = [] + for m in model_docs: + if m not in model_types and m != "auto": + close_matches = get_close_matches(m, model_types) + error_message = f"{m} is not a proper model identifier." + if len(close_matches) > 0: + close_matches = "/".join(close_matches) + error_message += f" Did you mean {close_matches}?" + errors.append(error_message) + + if len(errors) > 0: + raise ValueError( + "Some model doc pages do not match any existing model type:\n" + + "\n".join(errors) + + "\nYou can add any missing model type to the `MODEL_NAMES_MAPPING` constant in " + "models/auto/configuration_auto.py." + ) + + +def check_deprecated_constant_is_up_to_date(): + """ + Check if the constant `DEPRECATED_MODELS` in `models/auto/configuration_auto.py` is up to date. + """ + deprecated_folder = os.path.join(PATH_TO_TRANSFORMERS, "models", "deprecated") + deprecated_models = [m for m in os.listdir(deprecated_folder) if not m.startswith("_")] + + constant_to_check = transformers.models.auto.configuration_auto.DEPRECATED_MODELS + message = [] + missing_models = sorted(set(deprecated_models) - set(constant_to_check)) + if len(missing_models) != 0: + missing_models = ", ".join(missing_models) + message.append( + "The following models are in the deprecated folder, make sure to add them to `DEPRECATED_MODELS` in " + f"`models/auto/configuration_auto.py`: {missing_models}." + ) + + extra_models = sorted(set(constant_to_check) - set(deprecated_models)) + if len(extra_models) != 0: + extra_models = ", ".join(extra_models) + message.append( + "The following models are in the `DEPRECATED_MODELS` constant but not in the deprecated folder. Either " + f"remove them from the constant or move to the deprecated folder: {extra_models}." + ) + + if len(message) > 0: + raise Exception("\n".join(message)) + + +def check_repo_quality(): + """Check all models are tested and documented.""" + print("Repository-wide checks:") + print(" - checking all models are included.") + check_model_list() + print(" - checking all models are public.") + check_models_are_in_init() + print(" - checking all models have tests.") + check_all_decorator_order() + check_all_models_are_tested() + print(" - checking all objects have documentation.") + check_all_objects_are_documented() + print(" - checking all models are in at least one auto class.") + check_all_models_are_auto_configured() + print(" - checking all names in auto name mappings are defined.") + check_all_auto_object_names_being_defined() + print(" - checking all keys in auto name mappings are defined in `CONFIG_MAPPING_NAMES`.") + check_all_auto_mapping_names_in_config_mapping_names() + print(" - checking all auto mappings could be imported.") + check_all_auto_mappings_importable() + print(" - checking all objects are equally (across frameworks) in the main __init__.") + check_objects_being_equally_in_main_init() + print(" - checking the DEPRECATED_MODELS constant is up to date.") + check_deprecated_constant_is_up_to_date() + + +if __name__ == "__main__": + check_repo_quality() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_self_hosted_runner.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_self_hosted_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..7439bd270effcc206d79e9a7bcf97fe8ad939b63 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_self_hosted_runner.py @@ -0,0 +1,52 @@ +import argparse +import json +import subprocess + + +def get_runner_status(target_runners, token): + offline_runners = [] + + cmd = ( + f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' + " https://api.github.com/repos/huggingface/transformers/actions/runners" + ) + output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE) + o = output.stdout.decode("utf-8") + status = json.loads(o) + + runners = status["runners"] + for runner in runners: + if runner["name"] in target_runners: + if runner["status"] == "offline": + offline_runners.append(runner) + + # save the result so we can report them on Slack + with open("offline_runners.txt", "w") as fp: + fp.write(json.dumps(offline_runners)) + + if len(offline_runners) > 0: + failed = "\n".join([x["name"] for x in offline_runners]) + raise ValueError(f"The following runners are offline:\n{failed}") + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument( + "--target_runners", + default=None, + type=list_str, + required=True, + help="Comma-separated list of runners to check status.", + ) + + parser.add_argument( + "--token", default=None, type=str, required=True, help="A token that has actions:read permission." + ) + args = parser.parse_args() + + get_runner_status(args.target_runners, args.token) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/check_tf_ops.py b/tasks/tasksmith-441eeab80047/environment/source/utils/check_tf_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c2b8bae4e26b74e38728fc1440a58cf4837c1b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/check_tf_ops.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import os + +from tensorflow.core.protobuf.saved_model_pb2 import SavedModel + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_copies.py +REPO_PATH = "." + +# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) +INTERNAL_OPS = [ + "Assert", + "AssignVariableOp", + "EmptyTensorList", + "MergeV2Checkpoints", + "ReadVariableOp", + "ResourceGather", + "RestoreV2", + "SaveV2", + "ShardedFilename", + "StatefulPartitionedCall", + "StaticRegexFullMatch", + "VarHandleOp", +] + + +def onnx_compliancy(saved_model_path, strict, opset): + saved_model = SavedModel() + onnx_ops = [] + + with open(os.path.join(REPO_PATH, "utils", "tf_ops", "onnx.json")) as f: + onnx_opsets = json.load(f)["opsets"] + + for i in range(1, opset + 1): + onnx_ops.extend(onnx_opsets[str(i)]) + + with open(saved_model_path, "rb") as f: + saved_model.ParseFromString(f.read()) + + model_op_names = set() + + # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) + for meta_graph in saved_model.meta_graphs: + # Add operations in the graph definition + model_op_names.update(node.op for node in meta_graph.graph_def.node) + + # Go through the functions in the graph definition + for func in meta_graph.graph_def.library.function: + # Add operations in each function + model_op_names.update(node.op for node in func.node_def) + + # Convert to list, sorted if you want + model_op_names = sorted(model_op_names) + incompatible_ops = [] + + for op in model_op_names: + if op not in onnx_ops and op not in INTERNAL_OPS: + incompatible_ops.append(op) + + if strict and len(incompatible_ops) > 0: + raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops) + elif len(incompatible_ops) > 0: + print(f"Found the following incompatible ops for the opset {opset}:") + print(*incompatible_ops, sep="\n") + else: + print(f"The saved model {saved_model_path} can properly be converted with ONNX.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") + parser.add_argument( + "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." + ) + parser.add_argument( + "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." + ) + parser.add_argument( + "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" + ) + args = parser.parse_args() + + if args.framework == "onnx": + onnx_compliancy(args.saved_model_path, args.strict, args.opset) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/create_dependency_mapping.py b/tasks/tasksmith-441eeab80047/environment/source/utils/create_dependency_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..782617e27c28066958075a076071a9e5b32efeb3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/create_dependency_mapping.py @@ -0,0 +1,70 @@ +import ast +from collections import defaultdict + + +# Function to perform topological sorting +def topological_sort(dependencies: dict): + # Nodes are the name of the models to convert (we only add those to the graph) + nodes = {node.rsplit("modular_", 1)[1].replace(".py", "") for node in dependencies.keys()} + # This will be a graph from models to convert, to models to convert that should be converted before (as they are a dependency) + graph = {} + name_mapping = {} + for node, deps in dependencies.items(): + node_name = node.rsplit("modular_", 1)[1].replace(".py", "") + dep_names = {dep.split(".")[-2] for dep in deps} + dependencies = {dep for dep in dep_names if dep in nodes and dep != node_name} + graph[node_name] = dependencies + name_mapping[node_name] = node + + sorting_list = [] + while len(graph) > 0: + # Find the nodes with 0 out-degree + leaf_nodes = {node for node in graph if len(graph[node]) == 0} + # Add them to the list + sorting_list += list(leaf_nodes) + # Remove the leafs from the graph (and from the deps of other nodes) + graph = {node: deps - leaf_nodes for node, deps in graph.items() if node not in leaf_nodes} + + return [name_mapping[x] for x in sorting_list] + + +# Function to extract class and import info from a file +def extract_classes_and_imports(file_path): + with open(file_path, "r", encoding="utf-8") as file: + tree = ast.parse(file.read(), filename=file_path) + imports = set() + + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + module = node.module if isinstance(node, ast.ImportFrom) else None + if module and (".modeling_" in module or "transformers.models" in module): + imports.add(module) + return imports + + +# Function to map dependencies between classes +def map_dependencies(py_files): + dependencies = defaultdict(set) + # First pass: Extract all classes and map to files + for file_path in py_files: + # dependencies[file_path].add(None) + class_to_file = extract_classes_and_imports(file_path) + for module in class_to_file: + dependencies[file_path].add(module) + return dependencies + + +def find_priority_list(py_files): + """ + Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular + models will be higher in the topological order. + + Args: + py_files: List of paths to the modular files + + Returns: + A tuple with the ordered files (list) and their dependencies (dict) + """ + dependencies = map_dependencies(py_files) + ordered_files = topological_sort(dependencies) + return ordered_files, dependencies diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/create_dummy_models.py b/tasks/tasksmith-441eeab80047/environment/source/utils/create_dummy_models.py new file mode 100644 index 0000000000000000000000000000000000000000..e151b37d52ba065e470b14b9697ee5a2d63a05c2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/create_dummy_models.py @@ -0,0 +1,1577 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import collections.abc +import copy +import inspect +import json +import multiprocessing +import os +import shutil +import tempfile +import traceback +from pathlib import Path + +from check_config_docstrings import get_checkpoint_from_config_class +from datasets import load_dataset +from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model +from huggingface_hub import Repository, create_repo, hf_api, upload_folder + +from transformers import ( + CONFIG_MAPPING, + FEATURE_EXTRACTOR_MAPPING, + IMAGE_PROCESSOR_MAPPING, + PROCESSOR_MAPPING, + TOKENIZER_MAPPING, + AutoTokenizer, + LayoutLMv3TokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerFast, + logging, +) +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.file_utils import is_tf_available, is_torch_available +from transformers.image_processing_utils import BaseImageProcessor +from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name +from transformers.models.fsmt import configuration_fsmt +from transformers.processing_utils import ProcessorMixin, transformers_module +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + +# make sure tokenizer plays nice with multiprocessing +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +logging.set_verbosity_error() +logging.disable_progress_bar() +logger = logging.get_logger(__name__) + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +if not is_torch_available(): + raise ValueError("Please install PyTorch.") + +if not is_tf_available(): + raise ValueError("Please install TensorFlow.") + + +FRAMEWORKS = ["pytorch", "tensorflow"] +INVALID_ARCH = [] +TARGET_VOCAB_SIZE = 1024 + +data = {"training_ds": None, "testing_ds": None} + +COMPOSITE_MODELS = { + "EncoderDecoderModel": "EncoderDecoderModel-bert-bert", + "SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert", + "VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2", + "VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert", +} + +# This list contains the model architectures for which a tiny version could not be created. +# Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them. +# One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is +# identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques. +UNCONVERTIBLE_MODEL_ARCHITECTURES = { + "BertGenerationEncoder", + "BertGenerationDecoder", + "CamembertForSequenceClassification", + "CamembertForMultipleChoice", + "CamembertForMaskedLM", + "CamembertForCausalLM", + "CamembertForTokenClassification", + "CamembertForQuestionAnswering", + "CamembertModel", + "TFCamembertForMultipleChoice", + "TFCamembertForTokenClassification", + "TFCamembertForQuestionAnswering", + "TFCamembertForSequenceClassification", + "TFCamembertForMaskedLM", + "TFCamembertModel", + "TFCamembertForCausalLM", + "DecisionTransformerModel", + "GraphormerModel", + "InformerModel", + "JukeboxModel", + "MarianForCausalLM", + "MaskFormerSwinModel", + "MaskFormerSwinBackbone", + "MT5Model", + "MT5ForConditionalGeneration", + "UMT5ForConditionalGeneration", + "TFMT5ForConditionalGeneration", + "TFMT5Model", + "QDQBertForSequenceClassification", + "QDQBertForMaskedLM", + "QDQBertModel", + "QDQBertForTokenClassification", + "QDQBertLMHeadModel", + "QDQBertForMultipleChoice", + "QDQBertForQuestionAnswering", + "QDQBertForNextSentencePrediction", + "ReformerModelWithLMHead", + "RetriBertModel", + "Speech2Text2ForCausalLM", + "TimeSeriesTransformerModel", + "TrajectoryTransformerModel", + "TrOCRForCausalLM", + "XLMProphetNetForConditionalGeneration", + "XLMProphetNetForCausalLM", + "XLMProphetNetModel", + "XLMRobertaModel", + "XLMRobertaForTokenClassification", + "XLMRobertaForMultipleChoice", + "XLMRobertaForMaskedLM", + "XLMRobertaForCausalLM", + "XLMRobertaForSequenceClassification", + "XLMRobertaForQuestionAnswering", + "TFXLMRobertaForSequenceClassification", + "TFXLMRobertaForMaskedLM", + "TFXLMRobertaForCausalLM", + "TFXLMRobertaForQuestionAnswering", + "TFXLMRobertaModel", + "TFXLMRobertaForMultipleChoice", + "TFXLMRobertaForTokenClassification", +} + + +def get_processor_types_from_config_class(config_class, allowed_mappings=None): + """Return a tuple of processors for `config_class`. + + We use `tuple` here to include (potentially) both slow & fast tokenizers. + """ + + # To make a uniform return type + def _to_tuple(x): + if not isinstance(x, collections.abc.Sequence): + x = (x,) + else: + x = tuple(x) + return x + + if allowed_mappings is None: + allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"] + + processor_types = () + + # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or + # a feature extractor + if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings: + processor_types = _to_tuple(PROCESSOR_MAPPING[config_class]) + else: + if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings: + processor_types = TOKENIZER_MAPPING[config_class] + + if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings: + processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class]) + elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings: + processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class]) + + # Remark: some configurations have no processor at all. For example, generic composite models like + # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't + # require any processor. + + # We might get `None` for some tokenizers - remove them here. + processor_types = tuple(p for p in processor_types if p is not None) + + return processor_types + + +def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None): + """Return a tuple of all possible architectures attributed to a configuration class `config_class`. + + For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering]. + """ + # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in + # - MODEL_FOR_PRETRAINING_MAPPING_NAMES + # - MODEL_WITH_LM_HEAD_MAPPING_NAMES + # - MODEL_FOR_MASKED_LM_MAPPING_NAMES + # - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + # We avoid the duplication. + architectures = set() + + if models_to_skip is None: + models_to_skip = [] + models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip) + + for mapping in arch_mappings: + if config_class in mapping: + models = mapping[config_class] + models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,) + for model in models: + if model.__name__ not in models_to_skip: + architectures.add(model) + + architectures = tuple(architectures) + + return architectures + + +def get_config_class_from_processor_class(processor_class): + """Get the config class from a processor class. + + Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses + `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to + create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it + to find a checkpoint in order to create the processor. + """ + + processor_prefix = processor_class.__name__ + for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]: + processor_prefix = processor_prefix.replace(postfix, "") + + # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config` + if processor_prefix == "Wav2Vec2CTC": + processor_prefix = "Wav2Vec2" + + # Find the new configuration class + new_config_name = f"{processor_prefix}Config" + new_config_class = getattr(transformers_module, new_config_name) + + return new_config_class + + +def build_processor(config_class, processor_class, allow_no_checkpoint=False): + """Create a processor for `processor_class`. + + If a processor is not able to be built with the original arguments, this method tries to change the arguments and + call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to + find a checkpoint containing the necessary files to build a processor. + + The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in + `convert_processors`. For each model architecture`, a copy will be created and saved along the built model. + """ + # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint. + checkpoint = get_checkpoint_from_config_class(config_class) + + if checkpoint is None: + # try to get the checkpoint from the config class for `processor_class`. + # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class) + + processor = None + try: + processor = processor_class.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load + # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in + # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint + # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get + # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from + # `checkpoint`, but it helps this recursive method to find a way to build a processor). + if ( + processor is None + and checkpoint is not None + and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer)) + ): + try: + config = AutoConfig.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + config = None + if config is not None: + if not isinstance(config, config_class): + raise ValueError( + f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`" + f" ({config_class.__name__})!" + ) + tokenizer_class = config.tokenizer_class + new_processor_class = None + if tokenizer_class is not None: + new_processor_class = getattr(transformers_module, tokenizer_class) + if new_processor_class != processor_class: + processor = build_processor(config_class, new_processor_class) + # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto + # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build + if processor is None: + new_processor_classes = get_processor_types_from_config_class( + config.__class__, allowed_mappings=["tokenizer"] + ) + # Used to avoid infinite recursion between a pair of fast/slow tokenizer types + names = [ + x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None + ] + new_processor_classes = [ + x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names + ] + if len(new_processor_classes) > 0: + new_processor_class = new_processor_classes[0] + # Let's use fast tokenizer if there is any + for x in new_processor_classes: + if x.__name__.endswith("Fast"): + new_processor_class = x + break + processor = build_processor(config_class, new_processor_class) + + if processor is None: + # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`. + if issubclass(processor_class, ProcessorMixin): + attrs = {} + for attr_name in processor_class.attributes: + attrs[attr_name] = [] + # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has + # - feature_extractor_class = "CLIPFeatureExtractor" + # - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") + attr_class_names = getattr(processor_class, f"{attr_name}_class") + if not isinstance(attr_class_names, tuple): + attr_class_names = (attr_class_names,) + + for name in attr_class_names: + attr_class = getattr(transformers_module, name) + attr = build_processor(config_class, attr_class) + if attr is not None: + attrs[attr_name].append(attr) + + # try to build a `ProcessorMixin`, so we can return a single value + if all(len(v) > 0 for v in attrs.values()): + try: + processor = processor_class(**{k: v[0] for k, v in attrs.items()}) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + else: + # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960` + # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor + # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + if config_class_from_processor_class != config_class: + processor = build_processor(config_class_from_processor_class, processor_class) + + # Try to create an image processor or a feature extractor without any checkpoint + if ( + processor is None + and allow_no_checkpoint + and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin)) + ): + try: + processor = processor_class() + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # validation + if processor is not None: + if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")): + raise ValueError( + f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of" + f" {processor_class.__name__} or an Auto class!" + ) + + return processor + + +def get_tiny_config(config_class, model_class=None, **model_tester_kwargs): + """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`. + + Args: + config_class: Subclass of `PreTrainedConfig`. + + Returns: + An instance of `config_class` with tiny hyperparameters + """ + model_type = config_class.model_type + + # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via + # `model_type` as it would be sth. like `configuration_data2vec_vision.py`. + # A simple way is to use `inspect.getsourcefile(config_class)`. + config_source_file = inspect.getsourcefile(config_class) + # The modeling file name without prefix (`modeling_`) and postfix (`.py`) + modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "") + + try: + print("Importing", model_type_to_module_name(model_type)) + module_name = model_type_to_module_name(model_type) + if not modeling_name.startswith(module_name): + raise ValueError(f"{modeling_name} doesn't start with {module_name}!") + test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py") + models_to_model_testers = get_model_to_tester_mapping(test_file) + # Find the model tester class + model_tester_class = None + tester_classes = [] + if model_class is not None: + tester_classes = get_tester_classes_for_model(test_file, model_class) + else: + for _tester_classes in models_to_model_testers.values(): + tester_classes.extend(_tester_classes) + if len(tester_classes) > 0: + # sort with the length of the class names first, then the alphabetical order + # This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has + # `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI). + # TODO: More fine grained control of the desired tester class. + model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0] + except ModuleNotFoundError: + error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name." + raise ValueError(error) + + if model_tester_class is None: + error = f"Tiny config not created for {model_type} - no model tester is found in the testing module." + raise ValueError(error) + + # CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to + # `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`. + + if "vocab_size" in model_tester_kwargs: + if "text_kwargs" in inspect.signature(model_tester_class.__init__).parameters.keys(): + vocab_size = model_tester_kwargs.pop("vocab_size") + model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size} + + # `parent` is an instance of `unittest.TestCase`, but we don't need it here. + model_tester = model_tester_class(parent=None, **model_tester_kwargs) + + if hasattr(model_tester, "get_pipeline_config"): + config = model_tester.get_pipeline_config() + elif hasattr(model_tester, "prepare_config_and_inputs"): + # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if + # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`. + config = model_tester.prepare_config_and_inputs()[0] + elif hasattr(model_tester, "get_config"): + config = model_tester.get_config() + else: + error = ( + f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks" + " necessary method to create config." + ) + raise ValueError(error) + + # make sure this is long enough (some model tester has `20` for this attr.) to pass `text-generation` + # pipeline tests. + max_positions = [] + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + max_positions.append(getattr(config, key)) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + max_positions.append(getattr(config.text_config, key)) + if len(max_positions) > 0: + max_position = max(200, min(max_positions)) + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + setattr(config, key, max_position) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + setattr(config.text_config, key, max_position) + + return config + + +def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast): + new_tokenizer = tokenizer_fast.train_new_from_iterator( + data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False + ) + + # Make sure it at least runs + if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast): + new_tokenizer(data["testing_ds"]["text"]) + + return new_tokenizer + + +def convert_feature_extractor(feature_extractor, tiny_config): + to_convert = False + kwargs = {} + if hasattr(tiny_config, "image_size"): + kwargs["size"] = tiny_config.image_size + kwargs["crop_size"] = tiny_config.image_size + to_convert = True + elif ( + hasattr(tiny_config, "vision_config") + and tiny_config.vision_config is not None + and hasattr(tiny_config.vision_config, "image_size") + ): + kwargs["size"] = tiny_config.vision_config.image_size + kwargs["crop_size"] = tiny_config.vision_config.image_size + to_convert = True + + # Speech2TextModel specific. + if hasattr(tiny_config, "input_feat_per_channel"): + kwargs["feature_size"] = tiny_config.input_feat_per_channel + kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel + to_convert = True + + if to_convert: + feature_extractor = feature_extractor.__class__(**kwargs) + + # Sanity check: on tiny image feature extractors, a large image size results in slow CI -- up to the point where it + # can result in timeout issues. + if ( + isinstance(feature_extractor, BaseImageProcessor) + and hasattr(feature_extractor, "size") + and isinstance(feature_extractor.size, dict) + ): + largest_image_size = max(feature_extractor.size.values()) + if largest_image_size > 64: + # hardcoded exceptions + models_with_large_image_size = ("deformable_detr", "flava", "grounding_dino", "mgp_str", "swiftformer") + if any(model_name in tiny_config.model_type for model_name in models_with_large_image_size): + pass + else: + raise ValueError( + f"Image size of {tiny_config.model_type} is too large ({feature_extractor.size}). " + "Please reduce it to 64 or less on each dimension. The following steps are usually the " + "easiest solution: 1) confirm that you're setting `image_size` in your ModelTester class; " + "2) ensure that it gets passed to the tester config init, `get_config()`." + ) + + return feature_extractor + + +def convert_processors(processors, tiny_config, output_folder, result): + """Change a processor to work with smaller inputs. + + For tokenizers, we try to reduce their vocabulary size. + + For feature extractor, we use smaller image size or change + other attributes using the values from `tiny_config`. See `convert_feature_extractor`. + + This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages. + """ + + def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False): + """Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`. + + If `keep_fast_tokenizer=True`, the fast tokenizer will be kept. + """ + # sanity check 1: fast and slow tokenizers should be compatible (vocab_size) + if fast_tokenizer is not None and slow_tokenizer is not None: + if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size: + warning_message = ( + "The fast/slow tokenizers " + f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different " + "vocabulary size: " + f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and " + f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}." + ) + result["warnings"].append(warning_message) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + # sanity check 2: fast and slow tokenizers should be compatible (length) + if fast_tokenizer is not None and slow_tokenizer is not None: + if len(fast_tokenizer) != len(slow_tokenizer): + warning_message = ( + f"The fast/slow tokenizers () have different length: " + f"len(fast_tokenizer) = {len(fast_tokenizer)} and " + f"len(slow_tokenizer) = {len(slow_tokenizer)}." + ) + result["warnings"].append(warning_message) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + return fast_tokenizer, slow_tokenizer + + tokenizers = [] + feature_extractors = [] + for processor in processors: + if isinstance(processor, PreTrainedTokenizerBase): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor) + elif isinstance(processor, BaseImageProcessor): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, FeatureExtractionMixin): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, ProcessorMixin): + if hasattr(processor, "tokenizer"): + if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor.tokenizer) + # Currently, we only have these 2 possibilities + if hasattr(processor, "image_processor"): + if processor.image_processor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.image_processor) + elif hasattr(processor, "feature_extractor"): + if processor.feature_extractor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.feature_extractor) + + # check the built processors have the unique type + num_types = len({x.__class__.__name__ for x in feature_extractors}) + if num_types >= 2: + raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!") + num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers}) + if num_types >= 2: + raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!") + + fast_tokenizer = None + slow_tokenizer = None + + for tokenizer in tokenizers: + if isinstance(tokenizer, PreTrainedTokenizerFast): + fast_tokenizer = tokenizer + else: + slow_tokenizer = tokenizer + + # If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer. + # This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues. + # It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible. + # For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to + # load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`, + # which has different vocabulary. + # TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True) + original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer + + if fast_tokenizer: + try: + # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can + # be retrained + if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE: + fast_tokenizer = convert_tokenizer(fast_tokenizer) + except Exception: + result["warnings"].append( + ( + f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + + # If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it. + if fast_tokenizer: + # Make sure the fast tokenizer can be saved + try: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + fast_tokenizer.save_pretrained(tmpdir) + try: + slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False) + except Exception: + result["warnings"].append( + ( + f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + # Let's just keep the fast version + slow_tokenizer = None + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + + # If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original + # tokenizers. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False) + + # If there is any conversion failed, we keep the original tokenizers. + if (original_fast_tokenizer is not None and fast_tokenizer is None) or ( + original_slow_tokenizer is not None and slow_tokenizer is None + ): + warning_messagae = ( + "There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub " + " will be used instead." + ) + result["warnings"].append(warning_messagae) + # Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`) + fast_tokenizer = original_fast_tokenizer + slow_tokenizer = original_slow_tokenizer + + # Make sure the fast tokenizer can be saved + if fast_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + fast_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + # Make sure the slow tokenizer can be saved + if slow_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + slow_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + slow_tokenizer = None + + # update feature extractors using the tiny config + try: + feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors] + except Exception: + result["warnings"].append( + ( + "Failed to convert feature extractors.", + traceback.format_exc(), + ) + ) + feature_extractors = [] + + if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0: + if fast_tokenizer is not None: + if fast_tokenizer.__class__.__name__ in [ + "RobertaTokenizerFast", + "XLMRobertaTokenizerFast", + "LongformerTokenizerFast", + "MPNetTokenizerFast", + ]: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings + if slow_tokenizer is not None: + if slow_tokenizer.__class__.__name__ in [ + "RobertaTokenizer", + "XLMRobertaTokenizer", + "LongformerTokenizer", + "MPNetTokenizer", + ]: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings + + processors = [fast_tokenizer, slow_tokenizer] + feature_extractors + processors = [p for p in processors if p is not None] + for p in processors: + p.save_pretrained(output_folder) + + return processors + + +def get_checkpoint_dir(output_dir, model_arch): + """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory.""" + + arch_name = model_arch.__name__ + if arch_name.startswith("TF"): + arch_name = arch_name[2:] + elif arch_name.startswith("Flax"): + arch_name = arch_name[4:] + + return os.path.join(output_dir, arch_name) + + +def build_model(model_arch, tiny_config, output_dir): + """Create and save a model for `model_arch`. + + Also copy the set of processors to each model (under the same model type) output folder. + """ + + checkpoint_dir = get_checkpoint_dir(output_dir, model_arch) + + processor_output_dir = os.path.join(output_dir, "processors") + # copy the (same set of) processors (for a model type) to the model arch. specific folder + if os.path.isdir(processor_output_dir): + shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True) + + tiny_config = copy.deepcopy(tiny_config) + + if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]): + tiny_config.is_encoder_decoder = False + tiny_config.is_decoder = True + + model = model_arch(config=tiny_config) + model.save_pretrained(checkpoint_dir) + model.from_pretrained(checkpoint_dir) + + return model + + +def fill_result_with_error(result, error, trace, models_to_create): + """Fill `result` with errors for all target model arch if we can't build processor""" + error = (error, trace) + result["error"] = error + for framework in FRAMEWORKS: + if framework in models_to_create: + result[framework] = {} + for model_arch in models_to_create[framework]: + result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error} + + result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()} + + +def upload_model(model_dir, organization, token): + """Upload the tiny models""" + + arch_name = model_dir.split(os.path.sep)[-1] + repo_name = f"tiny-random-{arch_name}" + repo_id = f"{organization}/{repo_name}" + + repo_exist = False + error = None + try: + create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token) + except Exception as e: + error = e + if "You already created" in str(e): + error = None + logger.warning("Remote repository exists and will be cloned.") + repo_exist = True + try: + create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token) + except Exception as e: + error = e + if error is not None: + raise error + + with tempfile.TemporaryDirectory() as tmpdir: + repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token) + repo.git_pull() + shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True) + + if repo_exist: + # Open a PR on the existing Hub repo. + hub_pr_url = upload_folder( + folder_path=model_dir, + repo_id=repo_id, + repo_type="model", + commit_message=f"Update tiny models for {arch_name}", + commit_description=f"Upload tiny models for {arch_name}", + create_pr=True, + token=token, + ) + logger.warning(f"PR open in {hub_pr_url}.") + # TODO: We need this information? + else: + # Push to Hub repo directly + repo.git_add(auto_lfs_track=True) + repo.git_commit(f"Upload tiny models for {arch_name}") + repo.git_push(blocking=True) # this prints a progress bar with the upload + logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.") + + +def build_composite_models(config_class, output_dir): + import tempfile + + from transformers import ( + BertConfig, + BertLMHeadModel, + BertModel, + BertTokenizer, + BertTokenizerFast, + EncoderDecoderModel, + GPT2Config, + GPT2LMHeadModel, + GPT2Tokenizer, + GPT2TokenizerFast, + SpeechEncoderDecoderModel, + TFEncoderDecoderModel, + TFVisionEncoderDecoderModel, + TFVisionTextDualEncoderModel, + VisionEncoderDecoderModel, + VisionTextDualEncoderModel, + ViTConfig, + ViTFeatureExtractor, + ViTModel, + Wav2Vec2Config, + Wav2Vec2Model, + Wav2Vec2Processor, + ) + + # These will be removed at the end if they are empty + result = {"error": None, "warnings": []} + + if config_class.model_type == "encoder-decoder": + encoder_config_class = BertConfig + decoder_config_class = BertConfig + encoder_processor = (BertTokenizerFast, BertTokenizer) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = BertModel + decoder_class = BertLMHeadModel + model_class = EncoderDecoderModel + tf_model_class = TFEncoderDecoderModel + elif config_class.model_type == "vision-encoder-decoder": + encoder_config_class = ViTConfig + decoder_config_class = GPT2Config + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer) + encoder_class = ViTModel + decoder_class = GPT2LMHeadModel + model_class = VisionEncoderDecoderModel + tf_model_class = TFVisionEncoderDecoderModel + elif config_class.model_type == "speech-encoder-decoder": + encoder_config_class = Wav2Vec2Config + decoder_config_class = BertConfig + encoder_processor = (Wav2Vec2Processor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = Wav2Vec2Model + decoder_class = BertLMHeadModel + model_class = SpeechEncoderDecoderModel + tf_model_class = None + elif config_class.model_type == "vision-text-dual-encoder": + # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier + encoder_config_class = ViTConfig + decoder_config_class = BertConfig + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = ViTModel + decoder_class = BertModel + model_class = VisionTextDualEncoderModel + tf_model_class = TFVisionTextDualEncoderModel + + with tempfile.TemporaryDirectory() as tmpdir: + try: + # build encoder + models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []} + encoder_output_dir = os.path.join(tmpdir, "encoder") + build(encoder_config_class, models_to_create, encoder_output_dir) + + # build decoder + models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []} + decoder_output_dir = os.path.join(tmpdir, "decoder") + build(decoder_config_class, models_to_create, decoder_output_dir) + + # build encoder-decoder + encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__) + decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__) + + if config_class.model_type != "vision-text-dual-encoder": + # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it + # has no decoder. + decoder_config = decoder_config_class.from_pretrained(decoder_path) + decoder_config.is_decoder = True + decoder_config.add_cross_attention = True + model = model_class.from_encoder_decoder_pretrained( + encoder_path, + decoder_path, + decoder_config=decoder_config, + ) + elif config_class.model_type == "vision-text-dual-encoder": + model = model_class.from_vision_text_pretrained(encoder_path, decoder_path) + + model_path = os.path.join( + output_dir, + f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}", + ) + model.save_pretrained(model_path) + + if tf_model_class is not None: + model = tf_model_class.from_pretrained(model_path) + model.save_pretrained(model_path) + + # copy the processors + encoder_processor_path = os.path.join(encoder_output_dir, "processors") + decoder_processor_path = os.path.join(decoder_output_dir, "processors") + if os.path.isdir(encoder_processor_path): + shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True) + if os.path.isdir(decoder_processor_path): + shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True) + + # fill `result` + result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor} + + result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}} + + result["tensorflow"] = {} + if tf_model_class is not None: + result["tensorflow"] = { + tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path} + } + except Exception: + result["error"] = ( + f"Failed to build models for {config_class.__name__}.", + traceback.format_exc(), + ) + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id): + """Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc. + + The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an + integer that will be return if `tokenizer` has no token corresponding to `token_id_name`. + """ + + token_id = original_token_id + + if not token_id_name.endswith("_token_id"): + raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!") + + token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None) + if token is not None: + if isinstance(tokenizer, PreTrainedTokenizerFast): + token_id = tokenizer._convert_token_to_id_with_added_voc(token) + else: + token_id = tokenizer._convert_token_to_id(token) + + return token_id + + +def get_config_overrides(config_class, processors): + # `Bark` configuration is too special. Let's just not handle this for now. + if config_class.__name__ == "BarkConfig": + return {} + + config_overrides = {} + + # Check if there is any tokenizer (prefer fast version if any) + tokenizer = None + for processor in processors: + if isinstance(processor, PreTrainedTokenizerFast): + tokenizer = processor + break + elif isinstance(processor, PreTrainedTokenizer): + tokenizer = processor + + if tokenizer is None: + return config_overrides + + # Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.) + # We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty + # `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token. + vocab_size = len(tokenizer) + + # The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and + # `35999`. + if config_class.__name__ == "GPTSanJapaneseConfig": + vocab_size += 2 + + config_overrides["vocab_size"] = vocab_size + + # Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids. + model_tester_kwargs = {"vocab_size": vocab_size} + # `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`. + if config_class.__name__ == "FSMTConfig": + del model_tester_kwargs["vocab_size"] + model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size + model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size + + _tiny_config = get_tiny_config(config_class, **model_tester_kwargs) + + # handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.) + if hasattr(_tiny_config, "text_config"): + _tiny_config = _tiny_config.text_config + + # Collect values of some special token ids + for attr in dir(_tiny_config): + if attr.endswith("_token_id"): + token_id = getattr(_tiny_config, attr) + if token_id is not None: + # Using the token id values from `tokenizer` instead of from `_tiny_config`. + token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id) + config_overrides[attr] = token_id + + if config_class.__name__ == "FSMTConfig": + config_overrides["src_vocab_size"] = tokenizer.src_vocab_size + config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size + # `FSMTConfig` has `DecoderConfig` as `decoder` attribute. + config_overrides["decoder"] = configuration_fsmt.DecoderConfig( + vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"] + ) + + return config_overrides + + +def build(config_class, models_to_create, output_dir): + """Create all models for a certain model type. + + Args: + config_class (`PretrainedConfig`): + A subclass of `PretrainedConfig` that is used to determine `models_to_create`. + models_to_create (`dict`): + A dictionary containing the processor/model classes that we want to create the instances. These models are + of the same model type which is associated to `config_class`. + output_dir (`str`): + The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under + it. Models in different frameworks with the same architecture will be saved in the same subdirectory. + """ + if data["training_ds"] is None or data["testing_ds"] is None: + ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1") + data["training_ds"] = ds["train"] + data["testing_ds"] = ds["test"] + + if config_class.model_type in [ + "encoder-decoder", + "vision-encoder-decoder", + "speech-encoder-decoder", + "vision-text-dual-encoder", + ]: + return build_composite_models(config_class, output_dir) + + result = {k: {} for k in models_to_create} + + # These will be removed at the end if they are empty + result["error"] = None + result["warnings"] = [] + + # Build processors + processor_classes = models_to_create["processor"] + + if len(processor_classes) == 0: + error = f"No processor class could be found in {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + for processor_class in processor_classes: + try: + processor = build_processor(config_class, processor_class, allow_no_checkpoint=True) + if processor is not None: + result["processor"][processor_class] = processor + except Exception: + error = f"Failed to build processor for {processor_class.__name__}." + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + if len(result["processor"]) == 0: + error = f"No processor could be built for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + tiny_config = get_tiny_config(config_class) + except Exception as e: + error = f"Failed to get tiny config for {config_class.__name__}: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Convert the processors (reduce vocabulary size, smaller image size, etc.) + processors = list(result["processor"].values()) + processor_output_folder = os.path.join(output_dir, "processors") + try: + processors = convert_processors(processors, tiny_config, processor_output_folder, result) + except Exception: + error = "Failed to convert the processors." + trace = traceback.format_exc() + result["warnings"].append((error, trace)) + + if len(processors) == 0: + error = f"No processor is returned by `convert_processors` for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + config_overrides = get_config_overrides(config_class, processors) + except Exception as e: + error = f"Failure occurs while calling `get_config_overrides`: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Just for us to see this easily in the report + if "vocab_size" in config_overrides: + result["vocab_size"] = config_overrides["vocab_size"] + + # Update attributes that `vocab_size` involves + for k, v in config_overrides.items(): + if hasattr(tiny_config, k): + setattr(tiny_config, k, v) + # So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only. + # `FuyuConfig` saves data under both FuyuConfig and its `text_config`. This is not good, but let's just update + # every involved fields to avoid potential failure. + if ( + hasattr(tiny_config, "text_config") + and tiny_config.text_config is not None + and hasattr(tiny_config.text_config, k) + ): + setattr(tiny_config.text_config, k, v) + # If `text_config_dict` exists, we need to update its value here too in order to # make + # `save_pretrained -> from_pretrained` work. + if hasattr(tiny_config, "text_config_dict"): + tiny_config.text_config_dict[k] = v + + if result["warnings"]: + logger.warning(result["warnings"][0][0]) + + # update `result["processor"]` + result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors} + + for pytorch_arch in models_to_create["pytorch"]: + result["pytorch"][pytorch_arch.__name__] = {} + error = None + try: + model = build_model(pytorch_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the pytorch model for {pytorch_arch}: {e}" + trace = traceback.format_exc() + + result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None + result["pytorch"][pytorch_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None + ) + if error is not None: + result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace) + logger.error(f"{pytorch_arch.__name__}: {error}") + + for tensorflow_arch in models_to_create["tensorflow"]: + # Make PT/TF weights compatible + pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF` + pt_arch = getattr(transformers_module, pt_arch_name) + + result["tensorflow"][tensorflow_arch.__name__] = {} + error = None + if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None: + ckpt = get_checkpoint_dir(output_dir, pt_arch) + # Use the same weights from PyTorch. + try: + model = tensorflow_arch.from_pretrained(ckpt) + model.save_pretrained(ckpt) + except Exception as e: + # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now). + model = None + error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}" + trace = traceback.format_exc() + else: + try: + model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}" + trace = traceback.format_exc() + + result["tensorflow"][tensorflow_arch.__name__]["model"] = ( + model.__class__.__name__ if model is not None else None + ) + result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None + ) + if error is not None: + result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace) + logger.error(f"{tensorflow_arch.__name__}: {error}") + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def build_tiny_model_summary(results, organization=None, token=None): + """Build a summary: a dictionary of the form + { + model architecture name: + { + "tokenizer_classes": [...], + "processor_classes": [...], + "model_classes": [...], + } + .. + } + """ + tiny_model_summary = {} + for config_name in results: + processors = [key for key, value in results[config_name]["processor"].items()] + tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")]) + processor_classes = sorted([x for x in processors if x not in tokenizer_classes]) + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + model_classes = [arch_name] + base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name + # tiny model is not created for `arch_name` + if results[config_name][framework][arch_name]["model"] is None: + model_classes = [] + if base_arch_name not in tiny_model_summary: + tiny_model_summary[base_arch_name] = {} + tiny_model_summary[base_arch_name].update( + { + "tokenizer_classes": tokenizer_classes, + "processor_classes": processor_classes, + } + ) + tiny_model_summary[base_arch_name]["model_classes"] = sorted( + tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes + ) + if organization is not None: + repo_name = f"tiny-random-{base_arch_name}" + # composite models' checkpoints have more precise repo. names on the Hub. + if base_arch_name in COMPOSITE_MODELS: + repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}" + repo_id = f"{organization}/{repo_name}" + try: + commit_hash = hf_api.repo_info(repo_id, token=token).sha + except Exception: + # The directory is not created, but processor(s) is/are included in `results`. + logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}") + del tiny_model_summary[base_arch_name] + continue + tiny_model_summary[base_arch_name]["sha"] = commit_hash + + return tiny_model_summary + + +def build_failed_report(results, include_warning=True): + failed_results = {} + for config_name in results: + if "error" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name] = {"error": results[config_name]["error"]} + + if include_warning and "warnings" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name]["warnings"] = results[config_name]["warnings"] + + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + if framework not in failed_results[config_name]: + failed_results[config_name][framework] = {} + if arch_name not in failed_results[config_name][framework]: + failed_results[config_name][framework][arch_name] = {} + error = results[config_name][framework][arch_name]["error"] + failed_results[config_name][framework][arch_name]["error"] = error + + return failed_results + + +def build_simple_report(results): + text = "" + failed_text = "" + for config_name in results: + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + result = results[config_name][framework][arch_name]["error"] + failed_text += f"{arch_name}: {result[0]}\n" + else: + result = ("OK",) + text += f"{arch_name}: {result[0]}\n" + + return text, failed_text + + +def update_tiny_model_summary_file(report_path): + with open(os.path.join(report_path, "tiny_model_summary.json")) as fp: + new_data = json.load(fp) + with open("tests/utils/tiny_model_summary.json") as fp: + data = json.load(fp) + for key, value in new_data.items(): + if key not in data: + data[key] = value + else: + for attr in ["tokenizer_classes", "processor_classes", "model_classes"]: + # we might get duplication here. We will remove them below when creating `updated_data`. + data[key][attr].extend(value[attr]) + new_sha = value.get("sha", None) + if new_sha is not None: + data[key]["sha"] = new_sha + + updated_data = {} + for key in sorted(data.keys()): + updated_data[key] = {} + for attr, value in data[key].items(): + # deduplication and sort + updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value + + with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp: + json.dump(updated_data, fp, indent=4, ensure_ascii=False) + + +def create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token, + num_workers=1, +): + clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + if os.getcwd() != clone_path: + raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}") + + report_path = os.path.join(output_path, "reports") + os.makedirs(report_path, exist_ok=True) + + _pytorch_arch_mappings = [ + x + for x in dir(transformers_module) + if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING" + ] + _tensorflow_arch_mappings = [ + x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING") + ] + + pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings] + tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings] + + config_classes = CONFIG_MAPPING.values() + if not all: + config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types] + + # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes + processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes} + + to_create = {} + for c in config_classes: + processors = processor_type_map[c] + models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip) + tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip) + if len(models) + len(tf_models) > 0: + to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models} + + results = {} + if num_workers <= 1: + for c, models_to_create in list(to_create.items()): + print(f"Create models for {c.__name__} ...") + result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type)) + results[c.__name__] = result + print("=" * 40) + else: + all_build_args = [] + for c, models_to_create in list(to_create.items()): + all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type))) + with multiprocessing.Pool() as pool: + results = pool.starmap(build, all_build_args) + results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)} + + if upload: + if organization is None: + raise ValueError("The argument `organization` could not be `None`. No model is uploaded") + + to_upload = [] + for model_type in os.listdir(output_path): + # This is the directory containing the reports + if model_type == "reports": + continue + for arch in os.listdir(os.path.join(output_path, model_type)): + if arch == "processors": + continue + to_upload.append(os.path.join(output_path, model_type, arch)) + to_upload = sorted(to_upload) + + upload_results = {} + if len(to_upload) > 0: + for model_dir in to_upload: + try: + upload_model(model_dir, organization, token) + except Exception as e: + error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}" + logger.error(error) + upload_results[model_dir] = error + + with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp: + json.dump(upload_results, fp, indent=4) + + # Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists. + # When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model + # architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to + # `tests/utils/tiny_model_summary.json`. + tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token) + with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp: + json.dump(tiny_model_summary, fp, indent=4) + + with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp: + json.dump(results, fp, indent=4) + + # Build the warning/failure report (json format): same format as the complete `results` except this contains only + # warnings or errors. + failed_results = build_failed_report(results) + with open(os.path.join(report_path, "failed_report.json"), "w") as fp: + json.dump(failed_results, fp, indent=4) + + simple_report, failed_report = build_simple_report(results) + # The simplified report: a .txt file with each line of format: + # {model architecture name}: {OK or error message} + with open(os.path.join(report_path, "simple_report.txt"), "w") as fp: + fp.write(simple_report) + + # The simplified failure report: same above except this only contains line with errors + with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp: + fp.write(failed_report) + + update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports")) + + +if __name__ == "__main__": + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + parser.add_argument("--all", action="store_true", help="Will create all tiny models.") + parser.add_argument( + "--no_check", + action="store_true", + help="If set, will not check the validity of architectures. Use with caution.", + ) + parser.add_argument( + "-m", + "--model_types", + type=list_str, + help="Comma-separated list of model type(s) from which the tiny models will be created.", + ) + parser.add_argument( + "--models_to_skip", + type=list_str, + help=( + "Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually " + "the list of model classes that have their tiny versions already uploaded to the Hub." + ), + ) + parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.") + parser.add_argument( + "--organization", + default=None, + type=str, + help="The organization on the Hub to which the tiny models will be uploaded.", + ) + parser.add_argument( + "--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access." + ) + parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.") + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + + args = parser.parse_args() + + if not args.all and not args.model_types: + raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.") + + create_tiny_models( + args.output_path, + args.all, + args.model_types, + args.models_to_skip, + args.no_check, + args.upload, + args.organization, + args.token, + args.num_workers, + ) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/custom_init_isort.py b/tasks/tasksmith-441eeab80047/environment/source/utils/custom_init_isort.py new file mode 100644 index 0000000000000000000000000000000000000000..82bf07ce43a9c526131fa4fb3ac884cada8394b6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/custom_init_isort.py @@ -0,0 +1,330 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that sorts the imports in the custom inits of Transformers. Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. `isort` or `ruff` +properly sort the second half which looks like traditionl imports, the goal of this script is to sort the first half. + +Use from the root of the repo with: + +```bash +python utils/custom_init_isort.py +``` + +which will auto-sort the imports (used in `make style`). + +For a check only (as used in `make quality`) run: + +```bash +python utils/custom_init_isort.py --check_only +``` +""" + +import argparse +import os +import re +from typing import Any, Callable, List, Optional + + +# Path is defined with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + +# Pattern that looks at the indentation in a line. +_re_indent = re.compile(r"^(\s*)\S") +# Pattern that matches `"key":" and puts `key` in group 0. +_re_direct_key = re.compile(r'^\s*"([^"]+)":') +# Pattern that matches `_import_structure["key"]` and puts `key` in group 0. +_re_indirect_key = re.compile(r'^\s*_import_structure\["([^"]+)"\]') +# Pattern that matches `"key",` and puts `key` in group 0. +_re_strip_line = re.compile(r'^\s*"([^"]+)",\s*$') +# Pattern that matches any `[stuff]` and puts `stuff` in group 0. +_re_bracket_content = re.compile(r"\[([^\]]+)\]") + + +def get_indent(line: str) -> str: + """Returns the indent in given line (as string).""" + search = _re_indent.search(line) + return "" if search is None else search.groups()[0] + + +def split_code_in_indented_blocks( + code: str, indent_level: str = "", start_prompt: Optional[str] = None, end_prompt: Optional[str] = None +) -> List[str]: + """ + Split some code into its indented blocks, starting at a given level. + + Args: + code (`str`): The code to split. + indent_level (`str`): The indent level (as string) to use for identifying the blocks to split. + start_prompt (`str`, *optional*): If provided, only starts splitting at the line where this text is. + end_prompt (`str`, *optional*): If provided, stops splitting at a line where this text is. + + Warning: + The text before `start_prompt` or after `end_prompt` (if provided) is not ignored, just not split. The input `code` + can thus be retrieved by joining the result. + + Returns: + `List[str]`: The list of blocks. + """ + # Let's split the code into lines and move to start_index. + index = 0 + lines = code.split("\n") + if start_prompt is not None: + while not lines[index].startswith(start_prompt): + index += 1 + blocks = ["\n".join(lines[:index])] + else: + blocks = [] + + # This variable contains the block treated at a given time. + current_block = [lines[index]] + index += 1 + # We split into blocks until we get to the `end_prompt` (or the end of the file). + while index < len(lines) and (end_prompt is None or not lines[index].startswith(end_prompt)): + # We have a non-empty line with the proper indent -> start of a new block + if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level: + # Store the current block in the result and rest. There are two cases: the line is part of the block (like + # a closing parenthesis) or not. + if len(current_block) > 0 and get_indent(current_block[-1]).startswith(indent_level + " "): + # Line is part of the current block + current_block.append(lines[index]) + blocks.append("\n".join(current_block)) + if index < len(lines) - 1: + current_block = [lines[index + 1]] + index += 1 + else: + current_block = [] + else: + # Line is not part of the current block + blocks.append("\n".join(current_block)) + current_block = [lines[index]] + else: + # Just add the line to the current block + current_block.append(lines[index]) + index += 1 + + # Adds current block if it's nonempty. + if len(current_block) > 0: + blocks.append("\n".join(current_block)) + + # Add final block after end_prompt if provided. + if end_prompt is not None and index < len(lines): + blocks.append("\n".join(lines[index:])) + + return blocks + + +def ignore_underscore_and_lowercase(key: Callable[[Any], str]) -> Callable[[Any], str]: + """ + Wraps a key function (as used in a sort) to lowercase and ignore underscores. + """ + + def _inner(x): + return key(x).lower().replace("_", "") + + return _inner + + +def sort_objects(objects: List[Any], key: Optional[Callable[[Any], str]] = None) -> List[Any]: + """ + Sort a list of objects following the rules of isort (all uppercased first, camel-cased second and lower-cased + last). + + Args: + objects (`List[Any]`): + The list of objects to sort. + key (`Callable[[Any], str]`, *optional*): + A function taking an object as input and returning a string, used to sort them by alphabetical order. + If not provided, will default to noop (so a `key` must be provided if the `objects` are not of type string). + + Returns: + `List[Any]`: The sorted list with the same elements as in the inputs + """ + + # If no key is provided, we use a noop. + def noop(x): + return x + + if key is None: + key = noop + # Constants are all uppercase, they go first. + constants = [obj for obj in objects if key(obj).isupper()] + # Classes are not all uppercase but start with a capital, they go second. + classes = [obj for obj in objects if key(obj)[0].isupper() and not key(obj).isupper()] + # Functions begin with a lowercase, they go last. + functions = [obj for obj in objects if not key(obj)[0].isupper()] + + # Then we sort each group. + key1 = ignore_underscore_and_lowercase(key) + return sorted(constants, key=key1) + sorted(classes, key=key1) + sorted(functions, key=key1) + + +def sort_objects_in_import(import_statement: str) -> str: + """ + Sorts the imports in a single import statement. + + Args: + import_statement (`str`): The import statement in which to sort the imports. + + Returns: + `str`: The same as the input, but with objects properly sorted. + """ + + # This inner function sort imports between [ ]. + def _replace(match): + imports = match.groups()[0] + # If there is one import only, nothing to do. + if "," not in imports: + return f"[{imports}]" + keys = [part.strip().replace('"', "") for part in imports.split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]" + + lines = import_statement.split("\n") + if len(lines) > 3: + # Here we have to sort internal imports that are on several lines (one per name): + # key: [ + # "object1", + # "object2", + # ... + # ] + + # We may have to ignore one or two lines on each side. + idx = 2 if lines[1].strip() == "[" else 1 + keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])] + sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1]) + sorted_lines = [lines[x[0] + idx] for x in sorted_indices] + return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) + elif len(lines) == 3: + # Here we have to sort internal imports that are on one separate line: + # key: [ + # "object1", "object2", ... + # ] + if _re_bracket_content.search(lines[1]) is not None: + lines[1] = _re_bracket_content.sub(_replace, lines[1]) + else: + keys = [part.strip().replace('"', "") for part in lines[1].split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + return "\n".join(lines) + else: + # Finally we have to deal with imports fitting on one line + import_statement = _re_bracket_content.sub(_replace, import_statement) + return import_statement + + +def sort_imports(file: str, check_only: bool = True): + """ + Sort the imports defined in the `_import_structure` of a given init. + + Args: + file (`str`): The path to the init to check/fix. + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + with open(file, encoding="utf-8") as f: + code = f.read() + + # If the file is not a custom init, there is nothing to do. + if "_import_structure" not in code or "define_import_structure" in code: + return + + # Blocks of indent level 0 + main_blocks = split_code_in_indented_blocks( + code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:" + ) + + # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). + for block_idx in range(1, len(main_blocks) - 1): + # Check if the block contains some `_import_structure`s thingy to sort. + block = main_blocks[block_idx] + block_lines = block.split("\n") + + # Get to the start of the imports. + line_idx = 0 + while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]: + # Skip dummy import blocks + if "import dummy" in block_lines[line_idx]: + line_idx = len(block_lines) + else: + line_idx += 1 + if line_idx >= len(block_lines): + continue + + # Ignore beginning and last line: they don't contain anything. + internal_block_code = "\n".join(block_lines[line_idx:-1]) + indent = get_indent(block_lines[1]) + # Slit the internal block into blocks of indent level 1. + internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent) + # We have two categories of import key: list or _import_structure[key].append/extend + pattern = _re_direct_key if "_import_structure = {" in block_lines[0] else _re_indirect_key + # Grab the keys, but there is a trap: some lines are empty or just comments. + keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks] + # We only sort the lines with a key. + keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None] + sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])] + + # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. + count = 0 + reorderded_blocks = [] + for i in range(len(internal_blocks)): + if keys[i] is None: + reorderded_blocks.append(internal_blocks[i]) + else: + block = sort_objects_in_import(internal_blocks[sorted_indices[count]]) + reorderded_blocks.append(block) + count += 1 + + # And we put our main block back together with its first and last line. + main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]) + + if code != "\n".join(main_blocks): + if check_only: + return True + else: + print(f"Overwriting {file}.") + with open(file, "w", encoding="utf-8") as f: + f.write("\n".join(main_blocks)) + + +def sort_imports_in_all_inits(check_only=True): + """ + Sort the imports defined in the `_import_structure` of all inits in the repo. + + Args: + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + failures = [] + for root, _, files in os.walk(PATH_TO_TRANSFORMERS): + if "__init__.py" in files: + result = sort_imports(os.path.join(root, "__init__.py"), check_only=check_only) + if result: + failures = [os.path.join(root, "__init__.py")] + if len(failures) > 0: + raise ValueError(f"Would overwrite {len(failures)} files, run `make style`.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_imports_in_all_inits(check_only=args.check_only) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/deprecate_models.py b/tasks/tasksmith-441eeab80047/environment/source/utils/deprecate_models.py new file mode 100644 index 0000000000000000000000000000000000000000..add8da74d9308b061f79c5a25402aa10d85ddcd6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/deprecate_models.py @@ -0,0 +1,378 @@ +""" +Script which deprecates a list of given models + +Example usage: +python utils/deprecate_models.py --models bert distilbert +""" + +import argparse +import os +from collections import defaultdict +from pathlib import Path +from typing import Optional, Tuple + +import requests +from custom_init_isort import sort_imports_in_all_inits +from git import Repo +from packaging import version + +from transformers import CONFIG_MAPPING, logging +from transformers import __version__ as current_version + + +REPO_PATH = Path(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) +repo = Repo(REPO_PATH) + +logger = logging.get_logger(__name__) + + +def get_last_stable_minor_release(): + # Get the last stable release of transformers + url = "https://pypi.org/pypi/transformers/json" + release_data = requests.get(url).json() + + # Find the last stable release of of transformers (version below current version) + major_version, minor_version, patch_version, _ = current_version.split(".") + last_major_minor = f"{major_version}.{int(minor_version) - 1}" + last_stable_minor_releases = [ + release for release in release_data["releases"] if release.startswith(last_major_minor) + ] + last_stable_release = sorted(last_stable_minor_releases, key=version.parse)[-1] + + return last_stable_release + + +def build_tip_message(last_stable_release): + return ( + """ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +""" + + f"""If you run into any issues running this model, please reinstall the last version that supported this model: v{last_stable_release}. +You can do so by running the following command: `pip install -U transformers=={last_stable_release}`. + +""" + ) + + +def insert_tip_to_model_doc(model_doc_path, tip_message): + tip_message_lines = tip_message.split("\n") + + with open(model_doc_path, "r") as f: + model_doc = f.read() + + # Add the tip message to the model doc page directly underneath the title + lines = model_doc.split("\n") + + new_model_lines = [] + for line in lines: + if line.startswith("# "): + new_model_lines.append(line) + new_model_lines.extend(tip_message_lines) + else: + new_model_lines.append(line) + + with open(model_doc_path, "w") as f: + f.write("\n".join(new_model_lines)) + + +def get_model_doc_path(model: str) -> Tuple[Optional[str], Optional[str]]: + # Possible variants of the model name in the model doc path + model_names = [model, model.replace("_", "-"), model.replace("_", "")] + + model_doc_paths = [REPO_PATH / f"docs/source/en/model_doc/{model_name}.md" for model_name in model_names] + + for model_doc_path, model_name in zip(model_doc_paths, model_names): + if os.path.exists(model_doc_path): + return model_doc_path, model_name + + return None, None + + +def extract_model_info(model): + model_info = {} + model_doc_path, model_doc_name = get_model_doc_path(model) + model_path = REPO_PATH / f"src/transformers/models/{model}" + + if model_doc_path is None: + print(f"Model doc path does not exist for {model}") + return None + model_info["model_doc_path"] = model_doc_path + model_info["model_doc_name"] = model_doc_name + + if not os.path.exists(model_path): + print(f"Model path does not exist for {model}") + return None + model_info["model_path"] = model_path + + return model_info + + +def update_relative_imports(filename, model): + with open(filename, "r") as f: + filelines = f.read() + + new_file_lines = [] + for line in filelines.split("\n"): + if line.startswith("from .."): + new_file_lines.append(line.replace("from ..", "from ...")) + else: + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def remove_copied_from_statements(model): + model_path = REPO_PATH / f"src/transformers/models/{model}" + for file in os.listdir(model_path): + if file == "__pycache__": + continue + file_path = model_path / file + with open(file_path, "r") as f: + file_lines = f.read() + + new_file_lines = [] + for line in file_lines.split("\n"): + if "# Copied from" in line: + continue + new_file_lines.append(line) + + with open(file_path, "w") as f: + f.write("\n".join(new_file_lines)) + + +def move_model_files_to_deprecated(model): + model_path = REPO_PATH / f"src/transformers/models/{model}" + deprecated_model_path = REPO_PATH / f"src/transformers/models/deprecated/{model}" + + if not os.path.exists(deprecated_model_path): + os.makedirs(deprecated_model_path) + + for file in os.listdir(model_path): + if file == "__pycache__": + continue + repo.git.mv(f"{model_path}/{file}", f"{deprecated_model_path}/{file}") + + # For deprecated files, we then need to update the relative imports + update_relative_imports(f"{deprecated_model_path}/{file}", model) + + +def delete_model_tests(model): + tests_path = REPO_PATH / f"tests/models/{model}" + + if os.path.exists(tests_path): + repo.git.rm("-r", tests_path) + + +def get_line_indent(s): + return len(s) - len(s.lstrip()) + + +def update_main_init_file(models): + """ + Replace all instances of model.model_name with model.deprecated.model_name in the __init__.py file + + Args: + models (List[str]): The models to mark as deprecated + """ + filename = REPO_PATH / "src/transformers/__init__.py" + with open(filename, "r") as f: + init_file = f.read() + + # 1. For each model, find all the instances of model.model_name and replace with model.deprecated.model_name + for model in models: + init_file = init_file.replace(f'models.{model}"', f'models.deprecated.{model}"') + init_file = init_file.replace(f"models.{model} import", f"models.deprecated.{model} import") + + with open(filename, "w") as f: + f.write(init_file) + + # 2. Resort the imports + sort_imports_in_all_inits(check_only=False) + + +def remove_model_references_from_file(filename, models, condition): + """ + Remove all references to the given models from the given file + + Args: + filename (str): The file to remove the references from + models (List[str]): The models to remove + condition (Callable): A function that takes the line and model and returns True if the line should be removed + """ + filename = REPO_PATH / filename + with open(filename, "r") as f: + init_file = f.read() + + new_file_lines = [] + for i, line in enumerate(init_file.split("\n")): + if any(condition(line, model) for model in models): + continue + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def remove_model_config_classes_from_config_check(model_config_classes): + """ + Remove the deprecated model config classes from the check_config_attributes.py file + + Args: + model_config_classes (List[str]): The model config classes to remove e.g. ["BertConfig", "DistilBertConfig"] + """ + filename = REPO_PATH / "utils/check_config_attributes.py" + with open(filename, "r") as f: + check_config_attributes = f.read() + + # Keep track as we have to delete comment above too + in_special_cases_to_allow = False + in_indent = False + new_file_lines = [] + + for line in check_config_attributes.split("\n"): + indent = get_line_indent(line) + if (line.strip() == "SPECIAL_CASES_TO_ALLOW = {") or (line.strip() == "SPECIAL_CASES_TO_ALLOW.update("): + in_special_cases_to_allow = True + + elif in_special_cases_to_allow and indent == 0 and line.strip() in ("}", ")"): + in_special_cases_to_allow = False + + if in_indent: + if line.strip().endswith(("]", "],")): + in_indent = False + continue + + if in_special_cases_to_allow and any( + model_config_class in line for model_config_class in model_config_classes + ): + # Remove comments above the model config class to remove + while new_file_lines[-1].strip().startswith("#"): + new_file_lines.pop() + + if line.strip().endswith("["): + in_indent = True + + continue + + elif any(model_config_class in line for model_config_class in model_config_classes): + continue + + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def add_models_to_deprecated_models_in_config_auto(models): + """ + Add the models to the DEPRECATED_MODELS list in configuration_auto.py and sorts the list + to be in alphabetical order. + """ + filepath = REPO_PATH / "src/transformers/models/auto/configuration_auto.py" + with open(filepath, "r") as f: + config_auto = f.read() + + new_file_lines = [] + deprecated_models_list = [] + in_deprecated_models = False + for line in config_auto.split("\n"): + if line.strip() == "DEPRECATED_MODELS = [": + in_deprecated_models = True + new_file_lines.append(line) + elif in_deprecated_models and line.strip() == "]": + in_deprecated_models = False + # Add the new models to deprecated models list + deprecated_models_list.extend([f' "{model}", ' for model in models]) + # Sort so they're in alphabetical order in the file + deprecated_models_list = sorted(deprecated_models_list) + new_file_lines.extend(deprecated_models_list) + # Make sure we still have the closing bracket + new_file_lines.append(line) + elif in_deprecated_models: + deprecated_models_list.append(line) + else: + new_file_lines.append(line) + + with open(filepath, "w") as f: + f.write("\n".join(new_file_lines)) + + +def deprecate_models(models): + # Get model info + skipped_models = [] + models_info = defaultdict(dict) + for model in models: + single_model_info = extract_model_info(model) + if single_model_info is None: + skipped_models.append(model) + else: + models_info[model] = single_model_info + + model_config_classes = [] + for model, model_info in models_info.items(): + if model in CONFIG_MAPPING: + model_config_classes.append(CONFIG_MAPPING[model].__name__) + elif model_info["model_doc_name"] in CONFIG_MAPPING: + model_config_classes.append(CONFIG_MAPPING[model_info["model_doc_name"]].__name__) + else: + skipped_models.append(model) + print(f"Model config class not found for model: {model}") + + # Filter out skipped models + models = [model for model in models if model not in skipped_models] + + if skipped_models: + print(f"Skipped models: {skipped_models} as the model doc or model path could not be found.") + print(f"Models to deprecate: {models}") + + # Remove model config classes from config check + print("Removing model config classes from config checks") + remove_model_config_classes_from_config_check(model_config_classes) + + tip_message = build_tip_message(get_last_stable_minor_release()) + + for model, model_info in models_info.items(): + print(f"Processing model: {model}") + # Add the tip message to the model doc page directly underneath the title + print("Adding tip message to model doc page") + insert_tip_to_model_doc(model_info["model_doc_path"], tip_message) + + # Remove #Copied from statements from model's files + print("Removing #Copied from statements from model's files") + remove_copied_from_statements(model) + + # Move the model file to deprecated: src/transfomers/models/model -> src/transformers/models/deprecated/model + print("Moving model files to deprecated for model") + move_model_files_to_deprecated(model) + + # Delete the model tests: tests/models/model + print("Deleting model tests") + delete_model_tests(model) + + # # We do the following with all models passed at once to avoid having to re-write the file multiple times + print("Updating __init__.py file to point to the deprecated models") + update_main_init_file(models) + + # Remove model references from other files + print("Removing model references from other files") + remove_model_references_from_file( + "src/transformers/models/__init__.py", models, lambda line, model: model == line.strip().strip(",") + ) + remove_model_references_from_file( + "utils/slow_documentation_tests.txt", models, lambda line, model: "/" + model + "/" in line + ) + remove_model_references_from_file("utils/not_doctested.txt", models, lambda line, model: "/" + model + "/" in line) + + # Add models to DEPRECATED_MODELS in the configuration_auto.py + print("Adding models to DEPRECATED_MODELS in configuration_auto.py") + add_models_to_deprecated_models_in_config_auto(models) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--models", nargs="+", help="List of models to deprecate") + args = parser.parse_args() + deprecate_models(args.models) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/download_glue_data.py b/tasks/tasksmith-441eeab80047/environment/source/utils/download_glue_data.py new file mode 100644 index 0000000000000000000000000000000000000000..22e9fcae471f3361039544e9b6fb1b4318dd3c50 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/download_glue_data.py @@ -0,0 +1,157 @@ +"""Script for downloading all GLUE data. +Original source: https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e + +Note: for legal reasons, we are unable to host MRPC. +You can either use the version hosted by the SentEval team, which is already tokenized, +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. +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). +You should then rename and place specific files in a folder (see below for an example). + +mkdir MRPC +cabextract MSRParaphraseCorpus.msi -d MRPC +cat MRPC/_2DEC3DBE877E4DB192D17C0256E90F1D | tr -d $'\r' > MRPC/msr_paraphrase_train.txt +cat MRPC/_D7B391F9EAFF4B1B8BCE8F21B20B1B61 | tr -d $'\r' > MRPC/msr_paraphrase_test.txt +rm MRPC/_* +rm MSRParaphraseCorpus.msi + +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. +2/11/19: It looks like SentEval actually *is* hosting the extracted data. Hooray! +""" + +import argparse +import os +import sys +import urllib.request +import zipfile + + +TASKS = ["CoLA", "SST", "MRPC", "QQP", "STS", "MNLI", "SNLI", "QNLI", "RTE", "WNLI", "diagnostic"] +TASK2PATH = { + "CoLA": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4", + "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", + "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", + "QQP": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5", + "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", + "MNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce", + "SNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df", + "QNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601", + "RTE": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb", + "WNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf", + "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", +} + +MRPC_TRAIN = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt" +MRPC_TEST = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt" + + +def download_and_extract(task, data_dir): + print(f"Downloading and extracting {task}...") + data_file = f"{task}.zip" + urllib.request.urlretrieve(TASK2PATH[task], data_file) + with zipfile.ZipFile(data_file) as zip_ref: + zip_ref.extractall(data_dir) + os.remove(data_file) + print("\tCompleted!") + + +def format_mrpc(data_dir, path_to_data): + print("Processing MRPC...") + mrpc_dir = os.path.join(data_dir, "MRPC") + if not os.path.isdir(mrpc_dir): + os.mkdir(mrpc_dir) + if path_to_data: + mrpc_train_file = os.path.join(path_to_data, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(path_to_data, "msr_paraphrase_test.txt") + else: + print("Local MRPC data not specified, downloading data from %s" % MRPC_TRAIN) + mrpc_train_file = os.path.join(mrpc_dir, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(mrpc_dir, "msr_paraphrase_test.txt") + urllib.request.urlretrieve(MRPC_TRAIN, mrpc_train_file) + urllib.request.urlretrieve(MRPC_TEST, mrpc_test_file) + if not os.path.isfile(mrpc_train_file): + raise ValueError(f"Train data not found at {mrpc_train_file}") + if not os.path.isfile(mrpc_test_file): + raise ValueError(f"Test data not found at {mrpc_test_file}") + urllib.request.urlretrieve(TASK2PATH["MRPC"], os.path.join(mrpc_dir, "dev_ids.tsv")) + + dev_ids = [] + with open(os.path.join(mrpc_dir, "dev_ids.tsv"), encoding="utf8") as ids_fh: + for row in ids_fh: + dev_ids.append(row.strip().split("\t")) + + with open(mrpc_train_file, encoding="utf8") as data_fh, open( + os.path.join(mrpc_dir, "train.tsv"), "w", encoding="utf8" + ) as train_fh, open(os.path.join(mrpc_dir, "dev.tsv"), "w", encoding="utf8") as dev_fh: + header = data_fh.readline() + train_fh.write(header) + dev_fh.write(header) + for row in data_fh: + label, id1, id2, s1, s2 = row.strip().split("\t") + if [id1, id2] in dev_ids: + dev_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + else: + train_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + + with open(mrpc_test_file, encoding="utf8") as data_fh, open( + os.path.join(mrpc_dir, "test.tsv"), "w", encoding="utf8" + ) as test_fh: + header = data_fh.readline() + test_fh.write("index\t#1 ID\t#2 ID\t#1 String\t#2 String\n") + for idx, row in enumerate(data_fh): + label, id1, id2, s1, s2 = row.strip().split("\t") + test_fh.write("%d\t%s\t%s\t%s\t%s\n" % (idx, id1, id2, s1, s2)) + print("\tCompleted!") + + +def download_diagnostic(data_dir): + print("Downloading and extracting diagnostic...") + if not os.path.isdir(os.path.join(data_dir, "diagnostic")): + os.mkdir(os.path.join(data_dir, "diagnostic")) + data_file = os.path.join(data_dir, "diagnostic", "diagnostic.tsv") + urllib.request.urlretrieve(TASK2PATH["diagnostic"], data_file) + print("\tCompleted!") + return + + +def get_tasks(task_names): + task_names = task_names.split(",") + if "all" in task_names: + tasks = TASKS + else: + tasks = [] + for task_name in task_names: + if task_name not in TASKS: + raise ValueError(f"Task {task_name} not found!") + tasks.append(task_name) + return tasks + + +def main(arguments): + parser = argparse.ArgumentParser() + parser.add_argument("--data_dir", help="directory to save data to", type=str, default="glue_data") + parser.add_argument( + "--tasks", help="tasks to download data for as a comma separated string", type=str, default="all" + ) + parser.add_argument( + "--path_to_mrpc", + help="path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt", + type=str, + default="", + ) + args = parser.parse_args(arguments) + + if not os.path.isdir(args.data_dir): + os.mkdir(args.data_dir) + tasks = get_tasks(args.tasks) + + for task in tasks: + if task == "MRPC": + format_mrpc(args.data_dir, args.path_to_mrpc) + elif task == "diagnostic": + download_diagnostic(args.data_dir) + else: + download_and_extract(task, args.data_dir) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/extract_warnings.py b/tasks/tasksmith-441eeab80047/environment/source/utils/extract_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..5f49b1b456de01e24ec4c0b6fde182a431444e7f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/extract_warnings.py @@ -0,0 +1,134 @@ +import argparse +import json +import os +import time +import zipfile + +from get_ci_error_statistics import download_artifact, get_artifacts_links + +from transformers import logging + + +logger = logging.get_logger(__name__) + + +def extract_warnings_from_single_artifact(artifact_path, targets): + """Extract warnings from a downloaded artifact (in .zip format)""" + selected_warnings = set() + buffer = [] + + def parse_line(fp): + for line in fp: + if isinstance(line, bytes): + line = line.decode("UTF-8") + if "warnings summary (final)" in line: + continue + # This means we are outside the body of a warning + elif not line.startswith(" "): + # process a single warning and move it to `selected_warnings`. + if len(buffer) > 0: + warning = "\n".join(buffer) + # Only keep the warnings specified in `targets` + if any(f": {x}: " in warning for x in targets): + selected_warnings.add(warning) + buffer.clear() + continue + else: + line = line.strip() + buffer.append(line) + + if from_gh: + for filename in os.listdir(artifact_path): + file_path = os.path.join(artifact_path, filename) + if not os.path.isdir(file_path): + # read the file + if filename != "warnings.txt": + continue + with open(file_path) as fp: + parse_line(fp) + else: + try: + with zipfile.ZipFile(artifact_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename != "warnings.txt": + continue + with z.open(filename) as fp: + parse_line(fp) + except Exception: + logger.warning( + f"{artifact_path} is either an invalid zip file or something else wrong. This file is skipped." + ) + + return selected_warnings + + +def extract_warnings(artifact_dir, targets): + """Extract warnings from all artifact files""" + + selected_warnings = set() + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if (p.endswith(".zip") or from_gh)] + for p in paths: + selected_warnings.update(extract_warnings_from_single_artifact(p, targets)) + + return selected_warnings + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + # optional parameters + parser.add_argument( + "--targets", + default="DeprecationWarning,UserWarning,FutureWarning", + type=list_str, + help="Comma-separated list of target warning(s) which we want to extract.", + ) + parser.add_argument( + "--from_gh", + action="store_true", + help="If running from a GitHub action workflow and collecting warnings from its artifacts.", + ) + + args = parser.parse_args() + + from_gh = args.from_gh + if from_gh: + # The artifacts have to be downloaded using `actions/download-artifact@v4` + pass + else: + os.makedirs(args.output_dir, exist_ok=True) + + # get download links + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + # download artifacts + for idx, (name, url) in enumerate(artifacts.items()): + print(name) + print(url) + print("=" * 80) + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + # extract warnings from artifacts + selected_warnings = extract_warnings(args.output_dir, args.targets) + selected_warnings = sorted(selected_warnings) + with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: + json.dump(selected_warnings, fp, ensure_ascii=False, indent=4) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/get_ci_error_statistics.py b/tasks/tasksmith-441eeab80047/environment/source/utils/get_ci_error_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8ffa37b803352fde707867ce070589bcf3fe5d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/get_ci_error_statistics.py @@ -0,0 +1,303 @@ +import argparse +import json +import math +import os +import time +import traceback +import zipfile +from collections import Counter + +import requests + + +def get_jobs(workflow_run_id, token=None): + """Extract jobs in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + jobs = [] + + try: + jobs.extend(result["jobs"]) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + jobs.extend(result["jobs"]) + + return jobs + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return [] + + +def get_job_links(workflow_run_id, token=None): + """Extract job names and their job links in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_links = {} + + try: + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + + return job_links + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def get_artifacts_links(worflow_run_id, token=None): + """Get all artifact links from a workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" + result = requests.get(url, headers=headers).json() + artifacts = {} + + try: + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + + return artifacts + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def download_artifact(artifact_name, artifact_url, output_dir, token): + """Download a GitHub Action artifact from a URL. + + The URL is of the form `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, + but it can't be used to download directly. We need to get a redirect URL first. + See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + result = requests.get(artifact_url, headers=headers, allow_redirects=False) + download_url = result.headers["Location"] + response = requests.get(download_url, allow_redirects=True) + file_path = os.path.join(output_dir, f"{artifact_name}.zip") + with open(file_path, "wb") as fp: + fp.write(response.content) + + +def get_errors_from_single_artifact(artifact_zip_path, job_links=None): + """Extract errors from a downloaded artifact (in .zip format)""" + errors = [] + failed_tests = [] + job_name = None + + with zipfile.ZipFile(artifact_zip_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: + with z.open(filename) as f: + for line in f: + line = line.decode("UTF-8").strip() + if filename == "failures_line.txt": + try: + # `error_line` is the place where `error` occurs + error_line = line[: line.index(": ")] + error = line[line.index(": ") + len(": ") :] + errors.append([error_line, error]) + except Exception: + # skip un-related lines + pass + elif filename == "summary_short.txt" and line.startswith("FAILED "): + # `test` is the test method that failed + test = line[len("FAILED ") :] + failed_tests.append(test) + elif filename == "job_name.txt": + job_name = line + + if len(errors) != len(failed_tests): + raise ValueError( + f"`errors` and `failed_tests` should have the same number of elements. Got {len(errors)} for `errors` " + f"and {len(failed_tests)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" + " problem." + ) + + job_link = None + if job_name and job_links: + job_link = job_links.get(job_name, None) + + # A list with elements of the form (line of error, error, failed test) + result = [x + [y] + [job_link] for x, y in zip(errors, failed_tests)] + + return result + + +def get_all_errors(artifact_dir, job_links=None): + """Extract errors from all artifact files""" + + errors = [] + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")] + for p in paths: + errors.extend(get_errors_from_single_artifact(p, job_links=job_links)) + + return errors + + +def reduce_by_error(logs, error_filter=None): + """count each error""" + + counter = Counter() + counter.update([x[1] for x in logs]) + counts = counter.most_common() + r = {} + for error, count in counts: + if error_filter is None or error not in error_filter: + r[error] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def get_model(test): + """Get the model name from a test method""" + test = test.split("::")[0] + if test.startswith("tests/models/"): + test = test.split("/")[2] + else: + test = None + + return test + + +def reduce_by_model(logs, error_filter=None): + """count each error per model""" + + logs = [(x[0], x[1], get_model(x[2])) for x in logs] + logs = [x for x in logs if x[2] is not None] + tests = {x[2] for x in logs} + + r = {} + for test in tests: + counter = Counter() + # count by errors in `test` + counter.update([x[1] for x in logs if x[2] == test]) + counts = counter.most_common() + error_counts = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} + n_errors = sum(error_counts.values()) + if n_errors > 0: + r[test] = {"count": n_errors, "errors": error_counts} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def make_github_table(reduced_by_error): + header = "| no. | error | status |" + sep = "|-:|:-|:-|" + lines = [header, sep] + for error in reduced_by_error: + count = reduced_by_error[error]["count"] + line = f"| {count} | {error[:100]} | |" + lines.append(line) + + return "\n".join(lines) + + +def make_github_table_per_model(reduced_by_model): + header = "| model | no. of errors | major error | count |" + sep = "|-:|-:|-:|-:|" + lines = [header, sep] + for model in reduced_by_model: + count = reduced_by_model[model]["count"] + error, _count = list(reduced_by_model[model]["errors"].items())[0] + line = f"| {model} | {count} | {error[:60]} | {_count} |" + lines.append(line) + + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + args = parser.parse_args() + + os.makedirs(args.output_dir, exist_ok=True) + + _job_links = get_job_links(args.workflow_run_id, token=args.token) + job_links = {} + # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. + # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. + if _job_links: + for k, v in _job_links.items(): + # This is how GitHub actions combine job names. + if " / " in k: + index = k.find(" / ") + k = k[index + len(" / ") :] + job_links[k] = v + with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: + json.dump(job_links, fp, ensure_ascii=False, indent=4) + + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + for idx, (name, url) in enumerate(artifacts.items()): + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + errors = get_all_errors(args.output_dir, job_links=job_links) + + # `e[1]` is the error + counter = Counter() + counter.update([e[1] for e in errors]) + + # print the top 30 most common test errors + most_common = counter.most_common(30) + for item in most_common: + print(item) + + with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: + json.dump(errors, fp, ensure_ascii=False, indent=4) + + reduced_by_error = reduce_by_error(errors) + reduced_by_model = reduce_by_model(errors) + + s1 = make_github_table(reduced_by_error) + s2 = make_github_table_per_model(reduced_by_model) + + with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: + fp.write(s1) + with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: + fp.write(s2) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/get_github_job_time.py b/tasks/tasksmith-441eeab80047/environment/source/utils/get_github_job_time.py new file mode 100644 index 0000000000000000000000000000000000000000..af59081ffd4645470437958410a0fff9df7c64da --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/get_github_job_time.py @@ -0,0 +1,71 @@ +import argparse +import math +import traceback + +import dateutil.parser as date_parser +import requests + + +def extract_time_from_single_job(job): + """Extract time info from a single job in a GitHub Actions workflow run""" + + job_info = {} + + start = job["started_at"] + end = job["completed_at"] + + start_datetime = date_parser.parse(start) + end_datetime = date_parser.parse(end) + + duration_in_min = round((end_datetime - start_datetime).total_seconds() / 60.0) + + job_info["started_at"] = start + job_info["completed_at"] = end + job_info["duration"] = duration_in_min + + return job_info + + +def get_job_time(workflow_run_id, token=None): + """Extract time info for all jobs in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_time = {} + + try: + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + + return job_time + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +if __name__ == "__main__": + r""" + Example: + + python get_github_job_time.py --workflow_run_id 2945609517 + """ + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + args = parser.parse_args() + + job_time = get_job_time(args.workflow_run_id) + job_time = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) + + for k, v in job_time.items(): + print(f'{k}: {v["duration"]}') diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/get_modified_files.py b/tasks/tasksmith-441eeab80047/environment/source/utils/get_modified_files.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8bdfcdf00c835b68ed9b0eddeaf4d9d517d9cd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/get_modified_files.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: +# python ./utils/get_modified_files.py utils src tests examples +# +# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered +# since the output of this script is fed into Makefile commands it doesn't print a newline after the results + +import re +import subprocess +import sys + + +fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") +modified_files = ( + subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split() +) + +joined_dirs = "|".join(sys.argv[1:]) +regex = re.compile(rf"^({joined_dirs}).*?\.py$") + +relevant_modified_files = [x for x in modified_files if regex.match(x)] +print(" ".join(relevant_modified_files), end="") diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/get_previous_daily_ci.py b/tasks/tasksmith-441eeab80047/environment/source/utils/get_previous_daily_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..efd7d24a752991f16a41f85654fdb86a04c8ba94 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/get_previous_daily_ci.py @@ -0,0 +1,85 @@ +import os +import zipfile + +import requests +from get_ci_error_statistics import download_artifact, get_artifacts_links + + +def get_daily_ci_runs(token, num_runs=7): + """Get the workflow runs of the scheduled (daily) CI. + + This only selects the runs triggered by the `schedule` event on the `main` branch. + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + # The id of a workflow (not of a workflow run). + # From a given workflow run (where we have workflow run id), we can get the workflow id by going to + # https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id} + # and check the `workflow_id` key. + workflow_id = "90575235" + + url = f"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" + # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results + url += f"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" + + result = requests.get(url, headers=headers).json() + + return result["workflow_runs"] + + +def get_last_daily_ci_runs(token): + """Get the last completed workflow run id of the scheduled (daily) CI.""" + workflow_runs = get_daily_ci_runs(token) + workflow_run_id = None + for workflow_run in workflow_runs: + if workflow_run["status"] == "completed": + workflow_run_id = workflow_run["id"] + break + + return workflow_run_id + + +def get_last_daily_ci_run_commit(token): + """Get the commit sha of the last completed scheduled daily CI workflow run.""" + workflow_runs = get_daily_ci_runs(token) + head_sha = None + for workflow_run in workflow_runs: + if workflow_run["status"] == "completed": + head_sha = workflow_run["head_sha"] + break + + return head_sha + + +def get_last_daily_ci_artifacts(artifact_names, output_dir, token): + """Get the artifacts of last completed workflow run id of the scheduled (daily) CI.""" + workflow_run_id = get_last_daily_ci_runs(token) + if workflow_run_id is not None: + artifacts_links = get_artifacts_links(worflow_run_id=workflow_run_id, token=token) + for artifact_name in artifact_names: + if artifact_name in artifacts_links: + artifact_url = artifacts_links[artifact_name] + download_artifact( + artifact_name=artifact_name, artifact_url=artifact_url, output_dir=output_dir, token=token + ) + + +def get_last_daily_ci_reports(artifact_names, output_dir, token): + """Get the artifacts' content of the last completed workflow run id of the scheduled (daily) CI.""" + get_last_daily_ci_artifacts(artifact_names, output_dir, token) + + results = {} + for artifact_name in artifact_names: + artifact_zip_path = os.path.join(output_dir, f"{artifact_name}.zip") + if os.path.isfile(artifact_zip_path): + results[artifact_name] = {} + with zipfile.ZipFile(artifact_zip_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + with z.open(filename) as f: + results[artifact_name][filename] = f.read().decode("UTF-8") + + return results diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/get_test_info.py b/tasks/tasksmith-441eeab80047/environment/source/utils/get_test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..3c376bdbdaaf45fe9d9623ac4cd292421fbcb0ef --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/get_test_info.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import os +import sys + + +# This is required to make the module import works (when the python process is running from the root of the repo) +sys.path.append(".") + + +r""" +The argument `test_file` in this file refers to a model test file. This should be a string of the from +`tests/models/*/test_modeling_*.py`. +""" + + +def get_module_path(test_file): + """Return the module path of a model test file.""" + components = test_file.split(os.path.sep) + if components[0:2] != ["tests", "models"]: + raise ValueError( + "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " + f"{test_file} instead." + ) + test_fn = components[-1] + if not test_fn.endswith("py"): + raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead.") + if not test_fn.startswith("test_modeling_"): + raise ValueError( + f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." + ) + + components = components[:-1] + [test_fn.replace(".py", "")] + test_module_path = ".".join(components) + + return test_module_path + + +def get_test_module(test_file): + """Get the module of a model test file.""" + test_module_path = get_module_path(test_file) + try: + test_module = importlib.import_module(test_module_path) + except AttributeError as exc: + # e.g. if you have a `tests` folder in `site-packages`, created by another package, when trying to import + # `tests.models...` + raise ValueError( + f"Could not import module {test_module_path}. Confirm that you don't have a package with the same root " + "name installed or in your environment's `site-packages`." + ) from exc + + return test_module + + +def get_tester_classes(test_file): + """Get all classes in a model test file whose names ends with `ModelTester`.""" + tester_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + if attr.endswith("ModelTester"): + tester_classes.append(getattr(test_module, attr)) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_classes(test_file): + """Get all [test] classes in a model test file with attribute `all_model_classes` that are non-empty. + + These are usually the (model) test classes containing the (non-slow) tests to run and are subclasses of one of the + classes `ModelTesterMixin`, `TFModelTesterMixin` or `FlaxModelTesterMixin`, as well as a subclass of + `unittest.TestCase`. Exceptions include `RagTestMixin` (and its subclasses). + """ + test_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + attr_value = getattr(test_module, attr) + # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking + # `all_model_classes` is not empty (which also excludes other special classes). + model_classes = getattr(attr_value, "all_model_classes", []) + if len(model_classes) > 0: + test_classes.append(attr_value) + + # sort with class names + return sorted(test_classes, key=lambda x: x.__name__) + + +def get_model_classes(test_file): + """Get all model classes that appear in `all_model_classes` attributes in a model test file.""" + test_classes = get_test_classes(test_file) + model_classes = set() + for test_class in test_classes: + model_classes.update(test_class.all_model_classes) + + # sort with class names + return sorted(model_classes, key=lambda x: x.__name__) + + +def get_model_tester_from_test_class(test_class): + """Get the model tester class of a model test class.""" + test = test_class() + if hasattr(test, "setUp"): + test.setUp() + + model_tester = None + if hasattr(test, "model_tester"): + # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. + if test.model_tester is not None: + model_tester = test.model_tester.__class__ + + return model_tester + + +def get_test_classes_for_model(test_file, model_class): + """Get all [test] classes in `test_file` that have `model_class` in their `all_model_classes`.""" + test_classes = get_test_classes(test_file) + + target_test_classes = [] + for test_class in test_classes: + if model_class in test_class.all_model_classes: + target_test_classes.append(test_class) + + # sort with class names + return sorted(target_test_classes, key=lambda x: x.__name__) + + +def get_tester_classes_for_model(test_file, model_class): + """Get all model tester classes in `test_file` that are associated to `model_class`.""" + test_classes = get_test_classes_for_model(test_file, model_class) + + tester_classes = [] + for test_class in test_classes: + tester_class = get_model_tester_from_test_class(test_class) + if tester_class is not None: + tester_classes.append(tester_class) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_to_tester_mapping(test_file): + """Get a mapping from [test] classes to model tester classes in `test_file`. + + This uses `get_test_classes` which may return classes that are NOT subclasses of `unittest.TestCase`. + """ + test_classes = get_test_classes(test_file) + test_tester_mapping = {test_class: get_model_tester_from_test_class(test_class) for test_class in test_classes} + return test_tester_mapping + + +def get_model_to_test_mapping(test_file): + """Get a mapping from model classes to test classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_test_mapping = { + model_class: get_test_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_test_mapping + + +def get_model_to_tester_mapping(test_file): + """Get a mapping from model classes to model tester classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_to_tester_mapping = { + model_class: get_tester_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_to_tester_mapping + + +def to_json(o): + """Make the information succinct and easy to read. + + Avoid the full class representation like `` when + displaying the results. Instead, we use class name (`BertForMaskedLM`) for the readability. + """ + if isinstance(o, str): + return o + elif isinstance(o, type): + return o.__name__ + elif isinstance(o, (list, tuple)): + return [to_json(x) for x in o] + elif isinstance(o, dict): + return {to_json(k): to_json(v) for k, v in o.items()} + else: + return o diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/important_models.txt b/tasks/tasksmith-441eeab80047/environment/source/utils/important_models.txt new file mode 100644 index 0000000000000000000000000000000000000000..6dcd5de8d66f70ae5d7d902bf21389c8babbd7fa --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/important_models.txt @@ -0,0 +1,4 @@ +models/llama +models/mistral +models/mixtral +models/gemma \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/models_to_deprecate.py b/tasks/tasksmith-441eeab80047/environment/source/utils/models_to_deprecate.py new file mode 100644 index 0000000000000000000000000000000000000000..17ea1fd28ec8c6ef6fc10ba6828c90539d9865f8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/models_to_deprecate.py @@ -0,0 +1,200 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Script to find a candidate list of models to deprecate based on the number of downloads and the date of the last commit. +""" + +import argparse +import glob +import json +import os +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path + +from git import Repo +from huggingface_hub import HfApi + + +api = HfApi() + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +repo = Repo(PATH_TO_REPO) + + +class HubModelLister: + """ + Utility for getting models from the hub based on tags. Handles errors without crashing the script. + """ + + def __init__(self, tags): + self.tags = tags + self.model_list = api.list_models(tags=tags) + + def __iter__(self): + try: + yield from self.model_list + except Exception as e: + print(f"Error: {e}") + return + + +def _extract_commit_hash(commits): + for commit in commits: + if commit.startswith("commit "): + return commit.split(" ")[1] + return "" + + +def get_list_of_repo_model_paths(models_dir): + # Get list of all models in the library + models = glob.glob(os.path.join(models_dir, "*/modeling_*.py")) + + # Remove flax and tf models + models = [model for model in models if "_flax_" not in model] + models = [model for model in models if "_tf_" not in model] + + # Get list of all deprecated models in the library + deprecated_models = glob.glob(os.path.join(models_dir, "deprecated", "*")) + # For each deprecated model, remove the deprecated models from the list of all models as well as the symlink path + for deprecated_model in deprecated_models: + deprecated_model_name = "/" + deprecated_model.split("/")[-1] + "/" + models = [model for model in models if deprecated_model_name not in model] + # Remove deprecated models + models = [model for model in models if "/deprecated" not in model] + # Remove auto + models = [model for model in models if "/auto/" not in model] + return models + + +def get_list_of_models_to_deprecate( + thresh_num_downloads=5_000, + thresh_date=None, + use_cache=False, + save_model_info=False, + max_num_models=-1, +): + if thresh_date is None: + thresh_date = datetime.now(timezone.utc).replace(year=datetime.now(timezone.utc).year - 1) + else: + thresh_date = datetime.strptime(thresh_date, "%Y-%m-%d").replace(tzinfo=timezone.utc) + + models_dir = PATH_TO_REPO / "src/transformers/models" + model_paths = get_list_of_repo_model_paths(models_dir=models_dir) + + if use_cache and os.path.exists("models_info.json"): + with open("models_info.json", "r") as f: + models_info = json.load(f) + # Convert datetimes back to datetime objects + for model, info in models_info.items(): + info["first_commit_datetime"] = datetime.fromisoformat(info["first_commit_datetime"]) + + else: + # Build a dictionary of model info: first commit datetime, commit hash, model path + models_info = defaultdict(dict) + for model_path in model_paths: + model = model_path.split("/")[-2] + if model in models_info: + continue + commits = repo.git.log("--diff-filter=A", "--", model_path).split("\n") + commit_hash = _extract_commit_hash(commits) + commit_obj = repo.commit(commit_hash) + committed_datetime = commit_obj.committed_datetime + models_info[model]["commit_hash"] = commit_hash + models_info[model]["first_commit_datetime"] = committed_datetime + models_info[model]["model_path"] = model_path + models_info[model]["downloads"] = 0 + + # Some tags on the hub are formatted differently than in the library + tags = [model] + if "_" in model: + tags.append(model.replace("_", "-")) + models_info[model]["tags"] = tags + + # Filter out models which were added less than a year ago + models_info = { + model: info for model, info in models_info.items() if info["first_commit_datetime"] < thresh_date + } + + # We make successive calls to the hub, filtering based on the model tags + n_seen = 0 + for model, model_info in models_info.items(): + for model_tag in model_info["tags"]: + model_list = HubModelLister(tags=model_tag) + for i, hub_model in enumerate(model_list): + n_seen += 1 + if i % 100 == 0: + print(f"Processing model {i} for tag {model_tag}") + if max_num_models != -1 and i > n_seen: + break + if hub_model.private: + continue + model_info["downloads"] += hub_model.downloads + + if save_model_info and not (use_cache and os.path.exists("models_info.json")): + # Make datetimes serializable + for model, info in models_info.items(): + info["first_commit_datetime"] = info["first_commit_datetime"].isoformat() + with open("models_info.json", "w") as f: + json.dump(models_info, f, indent=4) + + print("\nFinding models to deprecate:") + n_models_to_deprecate = 0 + models_to_deprecate = {} + for model, info in models_info.items(): + n_downloads = info["downloads"] + if n_downloads < thresh_num_downloads: + n_models_to_deprecate += 1 + models_to_deprecate[model] = info + print(f"\nModel: {model}") + print(f"Downloads: {n_downloads}") + print(f"Date: {info['first_commit_datetime']}") + print("\nModels to deprecate: ", "\n" + "\n".join(models_to_deprecate.keys())) + print(f"\nNumber of models to deprecate: {n_models_to_deprecate}") + print("Before deprecating make sure to verify the models, including if they're used as a module in other models.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--save_model_info", action="store_true", help="Save the retrieved model info to a json file.") + parser.add_argument( + "--use_cache", action="store_true", help="Use the cached model info instead of calling the hub." + ) + parser.add_argument( + "--thresh_num_downloads", + type=int, + default=5_000, + help="Threshold number of downloads below which a model should be deprecated. Default is 5,000.", + ) + parser.add_argument( + "--thresh_date", + type=str, + default=None, + help="Date to consider the first commit from. Format: YYYY-MM-DD. If unset, defaults to one year ago from today.", + ) + parser.add_argument( + "--max_num_models", + type=int, + default=-1, + help="Maximum number of models to consider from the hub. -1 means all models. Useful for testing.", + ) + args = parser.parse_args() + + models_to_deprecate = get_list_of_models_to_deprecate( + thresh_num_downloads=args.thresh_num_downloads, + thresh_date=args.thresh_date, + use_cache=args.use_cache, + save_model_info=args.save_model_info, + max_num_models=args.max_num_models, + ) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/modular_model_converter.py b/tasks/tasksmith-441eeab80047/environment/source/utils/modular_model_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..efb8ac00475ef904d77c6cc62b91f78a4986875d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/modular_model_converter.py @@ -0,0 +1,1746 @@ +# coding=utf-8 +# Copyright 2024 the HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import glob +import importlib +import os +import re +from abc import ABC, abstractmethod +from collections import Counter, defaultdict, deque +from typing import Dict, Optional, Set, Union + +import libcst as cst +from check_copies import run_ruff +from create_dependency_mapping import find_priority_list +from libcst import ClassDef, CSTVisitor +from libcst import matchers as m +from libcst.metadata import MetadataWrapper, ParentNodeProvider, PositionProvider, ScopeProvider + +from transformers import logging +from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES + + +logger = logging.get_logger(__name__) + + +AUTO_GENERATED_MESSAGE = """# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from {relative_path}. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# {short_name} file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +""" + + +def get_module_source_from_name(module_name: str) -> str: + # Extract the source code from the module name + spec = importlib.util.find_spec(module_name) + if spec is None or spec.origin is None: + raise ValueError(f"Cannot open file associated with {module_name} module.") + + with open(spec.origin, "r", encoding="utf-8") as file: + source_code = file.read() + return source_code + + +def preserve_case_replace(text, patterns: dict, default_name: str): + # Create a regex pattern to match all variations + regex_pattern = "|".join(re.escape(key) for key in patterns.keys()) + compiled_regex = re.compile(f"(? str: + """From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`.""" + if lowercase_name in CONFIG_MAPPING_NAMES: + return CONFIG_MAPPING_NAMES[lowercase_name].replace("Config", "") + else: + return "".join(x.title() for x in lowercase_name.split("_")) + + +def get_lowercase_name(cased_name: str) -> str: + """From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`.""" + inverse_mapping = {value: key for key, value in CONFIG_MAPPING_NAMES.items()} + if cased_name + "Config" in inverse_mapping: + return inverse_mapping[cased_name + "Config"] + else: + return "_".join([s.lower() for s in re.findall(r"[A-Z][^A-Z]*", cased_name)]) + + +class ReplaceNameTransformer(m.MatcherDecoratableTransformer): + """A transformer that replaces `old_name` with `new_name` in comments, string and any references. + It should take into account name like `MyNewModel`, or `my_new_model`. Without using the AUTO_MAPPING. + Supported renaming patterns: + - llama -> my_new_model and my_new_model -> llama + - Llama -> MyNewModel and MyNewModel -> Llama + - LLAMA -> MY_NEW_MODEL and MY_NEW_MODEL -> LLAMA + - LLaMa -> MyNewModel abd MyNewModel -> Llama + """ + + def __init__(self, old_name: str, new_name: str, original_new_model_name: str = "", only_doc: bool = False): + super().__init__() + self.old_name = old_name + self.new_name = new_name + self.cased_new_name = get_cased_name(self.new_name) + self.cased_old_name = get_cased_name(self.old_name) + self.patterns = { + old_name: new_name, + old_name.upper(): new_name.upper(), + # For some old models, `self.cased_old_name` == `old_name.upper()` in which case this overwrite previous entry + self.cased_old_name: self.cased_new_name, + } + # In case new_name is a prefix alias, and not the original new model name + self.original_new_model_name = original_new_model_name + self.only_doc = only_doc + + def _replace_name(self, original_node, updated_node): + if re.findall(r"# Copied from", updated_node.value): + return cst.RemoveFromParent() + update = preserve_case_replace(updated_node.value, self.patterns, self.cased_new_name) + return updated_node.with_changes(value=update) + + @m.leave(m.SimpleString() | m.Comment()) + def replace_name(self, original_node, updated_node): + return self._replace_name(original_node, updated_node) + + def leave_Name(self, original_node, updated_node): + if not self.only_doc: + return self._replace_name(original_node, updated_node) + return updated_node + + def leave_ImportFrom(self, original_node, updated_node): + """The imports from other file types (configuration, processing etc) should use original model name.""" + if self.original_new_model_name != self.new_name and m.matches(updated_node.module, m.Name()): + patterns = "|".join(ALL_FILE_TYPES) + regex = rf"({patterns})_{self.new_name}" + new_source = re.sub( + regex, lambda m: f"{m.group(1)}_{self.original_new_model_name}", updated_node.module.value + ) + updated_node = updated_node.with_changes(module=updated_node.module.with_changes(value=new_source)) + return updated_node + + +DOCSTRING_NODE = m.SimpleStatementLine( + body=[ + m.Expr( + value=m.SimpleString( + # match anything between """ """ + value=m.MatchIfTrue(lambda value: re.search(r"\"\"\"[\s\S]*\"\"\"", value) is not None) + ) + ) + ] +) + + +def SUPER_CALL_NODE(func_name): + return m.Call(func=m.Attribute(value=m.Call(func=m.Name("super")), attr=m.Name(func_name))) + + +def is_call_to_super(node, func_name): + return m.matches( + node, m.SimpleStatementLine(body=[m.Return(SUPER_CALL_NODE(func_name)) | m.Expr(SUPER_CALL_NODE(func_name))]) + ) + + +def get_full_attribute_name(node: Union[cst.Attribute, cst.Name]) -> Optional[str]: + """Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the + successive value of an Attribute are not Name nodes, return `None`.""" + if m.matches(node, m.Name()): + return node.value + elif m.matches(node, m.Attribute()): + if not m.matches(node.attr, m.Name()): + return None + name = node.attr.value + new_node = node.value + while m.matches(new_node, m.Attribute()): + if not m.matches(new_node.attr, m.Name()): + return None + name = new_node.attr.value + "." + name + new_node = new_node.value + if not m.matches(new_node, m.Name()): + return None + return new_node.value + "." + name + return None + + +# Transformer class to replace ClassB.call_to_method and ClassB().call_to_method with super().call_to_method +class ReplaceMethodCallTransformer(cst.CSTTransformer): + def __init__(self, all_bases: Set[str]): + self.all_bases = all_bases + + def leave_Attribute(self, original_node: cst.Attribute, updated_node: cst.Attribute) -> cst.CSTNode: + # Handle ClassB.call_to_method or module.classB.call_to_method + if ( + m.matches(original_node.value, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.value) in self.all_bases + and m.matches(original_node.attr, m.Name()) + ): + # Replace with super().call_to_method + return updated_node.with_changes( + value=cst.Call(cst.Name("super")), + ) + # Handle ClassB().call_to_method or module.ClassB().call_to_method + elif ( + m.matches(original_node.value, m.Call()) + and m.matches(original_node.value.func, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.value.func) in self.all_bases + and m.matches(original_node.attr, m.Name()) + ): + # Replace with super().call_to_method + return updated_node.with_changes(value=cst.Call(cst.Name("super"))) + return updated_node + + def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode: + # Check if the function being called is of the form ClassB().func_a or ClassB.func_a + if m.matches(original_node.func, m.Attribute()) and ( + # Match ClassB().func_a(...) or module + ( + m.matches(original_node.func.value, m.Call()) + and m.matches(original_node.func.value.func, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.func.value.func) in self.all_bases + ) + or + # Match ClassB.func_a(...) + ( + m.matches(original_node.func.value, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.func.value) in self.all_bases + ) + ): + # Check if the first argument is 'self', and remove it + if len(original_node.args) > 0 and m.matches(original_node.args[0].value, m.Name("self")): + # Create the new argument list without 'self' + new_args = updated_node.args[1:] + else: + new_args = updated_node.args + + return updated_node.with_changes(args=new_args) + return updated_node + + +def get_docstring_indent(docstring): + # Match the first line after the opening triple quotes + match = re.search(r'(?:"""|\'\'\'|```)\n(\s+)', docstring) + if match: + # Return the indentation spaces captured + return len(match.group(1)) + return 0 + + +def is_full_docstring(new_docstring: str) -> bool: + """Check if `new_docstring` is a full docstring, or if it is only part of a docstring that should then + be merged with the existing old one. + """ + # libcst returns the docstrinbgs with litteral `r"""` quotes in front + new_docstring = new_docstring.split('"""', 1)[1] + # The docstring contains Args definition, so it is self-contained + if re.search(r"\n\s*Args:\n", new_docstring): + return True + # If it contains Returns, but starts with text indented with an additional 4 spaces before, it is self-contained + # (this is the scenario when using `@add_start_docstrings_to_model_forward`, but adding more args to docstring) + match_object = re.search(r"\n([^\S\n]*)Returns:\n", new_docstring) + if match_object is not None: + full_indent = match_object.group(1) + striped_doc = new_docstring.strip("\n") + if striped_doc.startswith(full_indent + " " * 4) or striped_doc.startswith(full_indent + "\t"): + return True + return False + + +def merge_docstrings(original_docstring, updated_docstring): + original_level = get_docstring_indent(original_docstring) + if not is_full_docstring(updated_docstring): + # Split the docstring at the example section, assuming `"""` is used to define the docstring + parts = original_docstring.split("```") + if "```" in updated_docstring and len(parts) > 1: + updated_docstring = updated_docstring.lstrip('r"') + new_parts = updated_docstring.split("```") + if len(new_parts) != 3: + raise ValueError("There should only be one example, and it should have opening and closing '```'") + parts[1] = new_parts[1] + updated_docstring = "".join( + [ + parts[0].rstrip(" \n") + new_parts[0], + f"\n{original_level * ' '}```", + parts[1], + "```", + parts[2], + ] + ) + elif updated_docstring not in original_docstring: + # add tabulation if we are at the lowest level. + if re.search(r"\n\s*.*\(.*\)\:\n\s*\w", updated_docstring): + updated_docstring = updated_docstring.replace("\n ", "\n ") + updated_docstring = original_docstring.rstrip('"') + "\n" + updated_docstring.lstrip('r"\n') + return updated_docstring + + +class SuperTransformer(cst.CSTTransformer): + METADATA_DEPENDENCIES = (ParentNodeProvider,) + + def __init__(self, python_module: cst.Module, original_methods, updated_methods, all_bases=None): + self.python_module = python_module + self.original_methods = original_methods + self.updated_methods = updated_methods + self.all_assign_target = {} + self.deleted_targets = {} # child node can delete some arguments + self.all_bases = all_bases or [] + self.transformer = ReplaceMethodCallTransformer(set(self.all_bases)) + + def update_body(self, existing_body, new_statements): + """ + Helper method to update the body by removing duplicates before adding new statements. + `existing_body` is the body of the original method, the parent class + `new_statements` are the additional statements + """ + deduplicated_new_body = [] + existing_nodes = set() + for node in new_statements: + if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): + target = self.python_module.code_for_node(node.body[0].targets[0].target) + self.all_assign_target[target] = node + if m.matches(node, m.SimpleStatementLine(body=[m.Del()])): + target = self.python_module.code_for_node(node.body[0].target) + self.deleted_targets[target] = node + + for stmt in existing_body: + if m.matches(stmt, m.SimpleStatementLine(body=[m.Assign()])): + target = self.python_module.code_for_node(stmt.body[0].targets[0].target) + if target in self.deleted_targets: + continue + if target in self.all_assign_target: + stmt = self.all_assign_target[target] + # Skip the docstring (will be added later on, at the beginning) + elif m.matches(stmt, DOCSTRING_NODE): + continue + comment_less_code = re.sub(r"#.*", "", self.python_module.code_for_node(stmt)).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + deduplicated_new_body.append(stmt) + existing_nodes.add(comment_less_code) + + for node in new_statements: + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if node not in deduplicated_new_body and comment_less_code not in existing_nodes: + if not m.matches(node, m.SimpleStatementLine(body=[m.Del()])): + deduplicated_new_body.append(node) + existing_nodes.add(comment_less_code) + + deduplicated_new_body = self._fix_post_init_location(deduplicated_new_body) + + return deduplicated_new_body + + def _fix_post_init_location(self, new_body: list[cst.CSTNode]): + """Fix the location of the `post_init()` in the new body, if we added statements after the call to + `super()` (it needs to be the very last statement called)""" + # Fix the post_init() that has to be last + for i, node in enumerate(new_body): + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if "self.post_init(" in comment_less_code and i < len(new_body) - 1: + # Remove it and add it again at the end + new_body.pop(i) + new_body.append(node) + break + return new_body + + def _fix_init_location(self, new_body): + """Fix the location of the `super().__init__()` in the new body, if we had new statements before it.""" + start_index = 0 + for i, node in enumerate(new_body): + if m.matches(node, DOCSTRING_NODE) and i == start_index: + start_index += 1 + continue + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if "super().__init__" in comment_less_code and i > start_index: + # Remove it and add it again at the top after the docstrings + node = new_body.pop(i) + new_body = new_body[:start_index] + [node] + new_body[start_index:] + break + return new_body + + def replace_super_calls(self, node: cst.IndentedBlock, func_name: str) -> cst.CSTNode: + """Updates the body of the input `node`'s `func_name` function by replacing calls + to super().func_name() with the source code of the parent class' `func_name`. + It keeps everything that is defined before `super().func_name()`. + """ + self.has_docstring = False + parent_has_docstring = False + if func_name in self.original_methods: + parent_has_docstring = m.matches(self.original_methods[func_name].body.body[0], DOCSTRING_NODE) + new_body = [] + has_super_call = False + + for i, expr in enumerate(node.body): + if is_call_to_super(expr, func_name): + has_super_call = True + new_body.extend(self.update_body(self.original_methods[func_name].body.body, node.body[i + 1 :])) + new_body = self._fix_init_location(new_body) + else: + expr = expr.visit(self.transformer) + if m.matches(expr, DOCSTRING_NODE): + self.has_docstring = True + if parent_has_docstring: # actually here we ought to de-duplicate? + original_docstring = self.original_methods[func_name].body.body[0].body[0].value.value + updated_docstring = expr.body[0].value.value + merged_doc = merge_docstrings(original_docstring, updated_docstring) + new_node = [expr.with_changes(body=[cst.Expr(value=cst.SimpleString(value=merged_doc))])] + else: + new_node = [expr] + new_body.extend(new_node) + elif not m.matches(expr, m.SimpleStatementLine(body=[m.Del()])) and not has_super_call: + new_body.append(expr) + if not self.has_docstring and parent_has_docstring: + new_body = [self.original_methods[func_name].body.body[0]] + new_body + return node.with_changes(body=new_body) + + def leave_FunctionDef(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode: + if updated_node.name.value in self.updated_methods: + name = updated_node.name.value + new_body = self.replace_super_calls(updated_node.body, name) + return updated_node.with_changes(body=new_body, params=updated_node.params) + return updated_node + + def leave_Return(self, original_node: cst.Return, updated_node: cst.Return) -> cst.CSTNode: + """ "When a return statement is reached, it is replaced with the unrolled super code""" + if m.matches(updated_node.value, m.Call(func=m.Attribute(attr=m.Name("super")))): + func_def = self.get_metadata(ParentNodeProvider, original_node) + if m.matched(func_def, m.FunctionDef()) and func_def.name.value in self.original_methods: + updated_return_value = updated_node.value.with_changes( + args=[ + cst.Arg( + value=cst.Call(func=cst.Name("super"), args=[cst.Arg(value=cst.Name(func_def.name.value))]) + ) + ] + ) + return updated_node.with_changes(value=updated_return_value) + return updated_node + + +def find_all_dependencies( + dependency_mapping: Dict[str, set], + start_entity: Optional[str] = None, + initial_dependencies: Optional[set] = None, + initial_checked_dependencies: Optional[set] = None, + return_parent: bool = False, +) -> Union[list, set]: + """Return all the dependencies of the given `start_entity` or `initial_dependencies`. This is basically some kind of + BFS traversal algorithm. It can either start from `start_entity`, or `initial_dependencies`. + + Args: + dependency_mapping (`Dict[str, set]`): + A mapping from entities (usually function/assignment names), to immediate dependencies. That is, for function names, + a mapping {"foo": {"bar", "test"}} would indicate that functions `bar` and `test` are immediately called + in `foo`'s definition. + start_entity (str | None, *optional*): + A key of `dependency_mapping`, indicating from which entity to start the search. + initial_dependencies (set | None, *optional*): + If `start_entity` is not provided, this can be used as an alternative. In this case, the search will continue + from all the entities in `initial_dependencies`, if they are in `dependency_mapping`. + initial_checked_dependencies (set | None, *optional*): + If provided, entities already present in `initial_checked_dependencies` will not be part of the returned dependencies. + return_parent (bool, *optional*): + If `True`, will return a list consisting of tuples (dependency, parent) instead of a simple set of dependencies. Note + that the order of the items in the list reflects the traversal order. Thus, no parent can ever appear before childs. + Returns: + A set of all the dependencies, or a list of tuples `(dependency, parent)` if `return_parent=True`. + + Example: + Given the following structure in the `modular_xxx.py` file: + ``` + def foo1(): + pass + + def foo2(): + pass + + def bar(): + foo1() + + def foobar(): + bar() + foo2() + + class MyLayer(SomeOtherModelLayer): + def forward(...): + foobar() + ``` + and the `dependency_mapping` created when visiting the `modular_xxx.py` file, we get: + ``` + dependency_mapping = {'bar': {'foo1'}, 'foobar': {'bar', 'foo2'}} + find_all_dependencies(dependency_mapping, start_entity='foobar', return_parent=True) + >>> [('bar', 'foobar'), ('foo2', 'foobar'), ('foo1', 'bar')] + ``` + That is, all the functions needed (and potentially their immediate parent) so that the function to be added + in MyLayer (`foobar`) can work correctly. + """ + if initial_dependencies is None and start_entity is not None: + initial_dependencies = dependency_mapping[start_entity] + if initial_checked_dependencies is None: + initial_checked_dependencies = set() + + dependency_queue = deque(initial_dependencies) + all_dependencies = set() + all_dependencies_with_parent = [] + checked_dependencies = set(initial_checked_dependencies) + parents = {initial_dep: start_entity for initial_dep in initial_dependencies} + while len(dependency_queue) > 0: + # Pick element to visit + current = dependency_queue.popleft() + if current not in checked_dependencies: + # Add the dependencies + all_dependencies.add(current) + all_dependencies_with_parent += [(current, parents[current])] + if current in dependency_mapping.keys(): + # Update dependency queue + dependency_queue.extend(dependency_mapping[current]) + parents.update({dep: current for dep in dependency_mapping[current]}) + # add visited node to the list + checked_dependencies.add(current) + + if not return_parent: + return all_dependencies + # no child can ever appear before its parent thanks to the queue (needed to add them at the correct location in the body later) + return all_dependencies_with_parent + + +# Top-level variables that match the following patterns will always use the value in the `modular_xxx.py` file +ASSIGNMENTS_REGEX_TO_KEEP = [r"_CHECKPOINT", r"_EXPECTED", r"_FOR_DOC"] + + +class ClassDependencyMapper(CSTVisitor): + """A visitor which is designed to analyze a single class node to get all its dependencies that are shared with the set of + `global_names`. + """ + + def __init__( + self, class_name: str, global_names: set[str], objects_imported_from_modeling: Optional[set[str]] = None + ): + super().__init__() + self.class_name = class_name + self.dependencies = set() + self.global_names = global_names + self.objects_imported_from_modeling = ( + set() if objects_imported_from_modeling is None else objects_imported_from_modeling + ) + + def visit_Name(self, node): + if ( + node.value != self.class_name + and node.value in self.global_names + and node.value not in self.objects_imported_from_modeling + ): + self.dependencies.add(node.value) + + +def dependencies_for_class_node(node: cst.ClassDef, global_names: set[str]) -> set: + """Create immediate dependencies for a class node based on the `global_names`.""" + temp_module = cst.Module(body=[node]) + visitor = ClassDependencyMapper(node.name.value, global_names) + temp_module.visit(visitor) + return visitor.dependencies + + +def augmented_dependencies_for_class_node( + node: cst.ClassDef, mapper: "ModuleMapper", objects_imported_from_modeling: Optional[set[str]] = None +) -> set: + """Create augmented dependencies for a class node based on a `mapper`. + Augmented dependencies means immediate dependencies + recursive function and assignments dependencies. + """ + temp_module = cst.Module(body=[node]) + visitor = ClassDependencyMapper(node.name.value, set(mapper.global_nodes.keys()), objects_imported_from_modeling) + temp_module.visit(visitor) + return mapper.augment_dependencies(visitor.dependencies) + + +# All the potential file types to create +ALL_FILE_TYPES = ( + "modeling", + "configuration", + "tokenization", + "processing", + "image_processing", + "feature_extractor", +) + + +class ModuleMapper(CSTVisitor, ABC): + """An abstract visitor class which analyses a module, creating a mapping of dependencies for classes, functions and assignments. + Class dependencies are computed with `compute_class_dependencies()`, while function and assignment dependencies are stored in + `self.object_recursive_dependency_mapping` (can be computed by `_compute_recursive_object_dependencies()`). + It defines common visiting patterns (i.e. common visit_xxx/leave_xxx functions) between the modular file and the + modeling files that will be visited. + """ + + METADATA_DEPENDENCIES = (ParentNodeProvider, PositionProvider) + + def __init__(self, python_module: cst.Module): + # fmt: off + self.python_module: cst.Module = python_module # original cst.Module being visited + self.classes: Dict[str, cst.ClassDef] = {} # mapping from class names to Nodes (it will be ordered by default!!) + self.imports = [] # stores all import statements + self.functions: Dict[str, cst.FunctionDef] = {} # mapping of global scope function names to Nodes + self.object_dependency_mapping = defaultdict(set) # immediate function/assignment dependency mapping (i.e. dependencies immediately in the function/assignment definition) + self.assignments: Dict[str, cst.SimpleStatementLine] = {} # mapping of global assignments names to Nodes + self.current_function = None # this keeps track of the current module-scope function + self.current_assignment = None # this keeps track of the current module-scope assignment + # this keeps track of objects imported from modeling files (`from .configuration import Config`) -> `Config` should not be a dependency + self.objects_imported_from_modeling = set() + # regex pattern joining every possible file type + self.match_patterns = "|".join(ALL_FILE_TYPES) + # fmt: on + + def visit_ImportFrom(self, node): + """This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have + `from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs + to be added (because it will be part of the imports)""" + import_module = self.python_module.code_for_node(node.module) + import_statement = "." * len(node.relative) + import_module + if re.search(rf"^\.({self.match_patterns})_.*", import_statement): + for imported_object in node.names: + # If an alias is present, we record it and not the original name + if imported_object.evaluated_alias is not None: + self.objects_imported_from_modeling.add(imported_object.evaluated_alias) + else: + self.objects_imported_from_modeling.add(imported_object.evaluated_name) + + def visit_SimpleStatementLine(self, node): + """ + Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements + are extracted and saved in their corresponding dict. They are then used when updating dependency mappings. + """ + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + if m.matches(parent_node, m.Module()): + if m.matches(node, simple_top_level_assign_structure): + left_hand_side = node.body[0].targets[0].target.value + self.current_assignment = left_hand_side + self.assignments[left_hand_side] = node + elif m.matches(node, m.SimpleStatementLine(body=[m.Import() | m.ImportFrom()])): + self.imports.append(node) + + def leave_SimpleStatementLine(self, node): + # No need to check for the parent here -> everytime we exit one, it should be None anyway independently of where the + # SimpleStatement is located + self.current_assignment = None + + def visit_FunctionDef(self, node): + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + if m.matches(parent_node, m.Module()): + self.current_function = node.name.value + self.functions[node.name.value] = node + + def leave_FunctionDef(self, node): + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + if m.matches(parent_node, m.Module()): + self.current_function = None + + def visit_If(self, node): + # If we are inside a function, do not add the import to the list of imports + if self.current_function is None: + for stmt in node.body.body: + if m.matches(stmt, m.SimpleStatementLine(body=[m.ImportFrom() | m.Import()])): + self.imports.append(node) + + def visit_ClassDef(self, node: ClassDef) -> None: + """Record class nodes to create their dependencies at the end.""" + self.classes[node.name.value] = node + + def visit_Name(self, node: cst.Call): + """This is used to create a mapping from module-scope functions and assignments to objects used inside them.""" + if self.current_function is not None: + self.object_dependency_mapping[self.current_function].add(node.value) + if self.current_assignment is not None: + self.object_dependency_mapping[self.current_assignment].add(node.value) + + def leave_Module(self, node): + """When leaving the module, we store the position of each global scoped node to allow sorting the dependencies + based on their position in the code later. We use the PositionProvider metadata wrapper for this. + We also make sure to update `self.object_dependency_mapping` so that it contains only names recorded in + `self.global_nodes`. + """ + # assign all nodes + self.global_nodes = {**self.assignments, **self.classes, **self.functions} + # now sort the class dependency_mapping based on the position of the nodes + self.start_lines = {} + for id, node in self.global_nodes.items(): + self.start_lines[id] = self.get_metadata(cst.metadata.PositionProvider, node).start.line + + def _restrict_dependencies_to_known_entities(self): + """Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that + are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc). + This should be called only after all merging operations have been finalized!!""" + global_objects = set(self.global_nodes.keys()) + for object_name, dependencies in self.object_dependency_mapping.items(): + self.object_dependency_mapping[object_name] = {dep for dep in dependencies if dep in global_objects} + + def _compute_recursive_object_dependencies(self) -> dict[str, set]: + """Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the + following file: + ``` + def foo(): + pass + + def bar(): + foo() + + def test(): + bar() + ``` + this visitor can only record immediate dependencies, i.e. it will record the following + `self.object_dependency_mapping = {"test": {"bar"}, "bar": {"foo}}`. This function is used to create + the recursive mapping, i.e. `recursive_dependencies = {"test": {"bar", "foo"}, "bar": {"foo}}`. + """ + recursive_dependencies = {} + for object_name in self.object_dependency_mapping.keys(): + all_dependencies = find_all_dependencies(self.object_dependency_mapping, start_entity=object_name) + recursive_dependencies[object_name] = all_dependencies + return recursive_dependencies + + def augment_dependencies(self, dependencies: set[str]) -> set[str]: + """For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and + **assignments** present in the `dependencies`. + """ + new_dependencies = dependencies.copy() + # Go through the set of dependencies + for dep in tuple(dependencies): + if dep in self.object_recursive_dependency_mapping.keys(): + new_dependencies.update(self.object_recursive_dependency_mapping[dep]) + return new_dependencies + + def compute_class_dependencies(self): + """For each visited class, find its dependencies based on visiting the current file + potential merged dependencies.""" + self.class_dependency_mapping = {} + for class_name, class_node in self.classes.items(): + dependencies = dependencies_for_class_node(class_node, set(self.global_nodes.keys())) + # Correctly augment class dependencies with all needed objects + self.class_dependency_mapping[class_name] = self.augment_dependencies(dependencies) + + @abstractmethod + def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: + raise NotImplementedError + + +class ModelFileMapper(ModuleMapper): + """A mapper designed to parse modeling files (like `modeling_llama.py`). When encountering such a file + in the `modular_xxx.py` file, we need to correctly visit it and merge the dependencies of the modular and current file. + For this reason, this class should only be instantiated from the class method `visit_and_merge_dependencies`, which takes + care of correctly merging dependencies, then finalizes all dependency graph computations. + Note that we only merge functions and assignments here, as classes will be treated later on as they may be modified. + For example, if you redefine `apply_rotary_pos_emb()` in the modular, the new node should be used in the dependencies + of the modeling files as well. + """ + + def __init__(self, python_module: cst.Module): + super().__init__(python_module) + + def compute_relative_order(self, missing_dependencies: set[str]) -> dict[str, int]: + """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that + will be created based on the modular. + """ + relative_order = {} + idx = 0 + classes = sorted( + [dep for dep in tuple(missing_dependencies) if dep in self.classes], key=lambda x: self.start_lines[x] + ) + # This is because for merged dependencies, we only have relative order in the other visited file, so we need + # to track dependency order relative to a given class + if len(classes) > 0 and not hasattr(self, "class_dependency_mapping"): + raise ValueError("Cannot correctly find the relative order of the dependencies.") + + remaining_dependencies = missing_dependencies.copy() + + # Start by tracking relative order class by class + for class_name in classes: + class_dependencies = tuple(self.class_dependency_mapping[class_name] & remaining_dependencies) + original_dependencies = [] + merged_dependencies = [] + # We need to differentiate between nodes that were already present (we can get relative order globally) and + # nodes that were merged (we can get relative order only relative to the class the dependencies relate to) + for class_dep in class_dependencies: + if class_dep in self.start_lines: + original_dependencies.append(class_dep) + else: + merged_dependencies.append(class_dep) + # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) + # will always get the same order independently of the system (they come from a set, which has no deterministic order) + original_dependencies = sorted(original_dependencies, reverse=True) + # Sort both list according to the order in their respective file + original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) + merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) + + # Add all original node first, then merged ones + for dep in original_dependencies + merged_dependencies: + remaining_dependencies.remove(dep) + relative_order[dep] = idx + idx += 1 + # Add the class itself (it can sometimes already be present if the order of classes in the source file + # does not make sense, i.e. a class is used somewhere before being defined like in `rt_detr`...) + if class_name in remaining_dependencies: + remaining_dependencies.remove(class_name) + relative_order[class_name] = idx + idx += 1 + + # Now add what still remains + remaining_dependencies = tuple(remaining_dependencies) + original_dependencies = [] + merged_dependencies = [] + for dep in remaining_dependencies: + if dep in self.modular_file_start_lines: + merged_dependencies.append(dep) + else: + original_dependencies.append(dep) + # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) + # will always get the same order independently of the system (they come from a set, which has no deterministic order) + original_dependencies = sorted(original_dependencies, reverse=True) + # Sort both list according to the order in their respective file + original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) + merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) + + # Add all original node first, then merged ones + for dep in original_dependencies + merged_dependencies: + relative_order[dep] = idx + idx += 1 + + return relative_order + + def _merge_functions(self, functions: dict[str, cst.CSTNode], object_mapping: dict[str, set]): + """Update the global nodes and function dependency mapping with those from the modular file. + + Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies + instead of the original ones (this may mean to add new functions as well, if any redefined function uses a new one). + """ + # Add/overwrite all needed function nodes and dependencies + self.functions.update(functions) + self.object_dependency_mapping.update( + {obj: dep for obj, dep in object_mapping.items() if obj in functions.keys()} + ) + # Add them to global nodes + self.global_nodes.update(self.functions) + + def _merge_assignments(self, assignments: dict[str, cst.CSTNode], object_mapping: dict[str, set]): + """Update the global nodes with the assignment from the modular file. + + Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches + 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 + big docstrings. + """ + for assignment, node in assignments.items(): + should_keep = any(re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP) + + if should_keep or assignment not in self.assignments: + self.assignments[assignment] = node + if assignment in object_mapping: + self.object_dependency_mapping[assignment] = object_mapping[assignment] + # Add them to global nodes + self.global_nodes.update(self.assignments) + + def _merge_classes(self, classes: dict[str, cst.CSTNode]): + """Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and + are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined + classes in the modular to be discoverable when computing dependencies for new nodes later on. For this reason, we + do not add the new classes to `self.classes`, but only to `global_nodes`. + """ + # Add/overwrite all needed function nodes and dependencies + self.global_nodes.update( + { + name: node + for name, node in classes.items() + if name not in self.classes and name not in self.objects_imported_from_modeling + } + ) + + def merge_modular_dependencies(self, classes, functions, assignments, object_mapping, start_lines): + """Merge classes, functions and assignments from the modular definitions into the current module file, + then record the relative order of all nodes. + Note: This function takes care of updating `global_nodes` and `object_recursive_dependency_mapping` as well after the + merge with other files dependencies. + """ + self._merge_functions(functions, object_mapping) + self._merge_assignments(assignments, object_mapping) + self._merge_classes(classes) + self.modular_file_start_lines = start_lines + + # Restrict the dependency mappings to the known entities to avoid Python's built-ins and imports + self._restrict_dependencies_to_known_entities() + # Create the global mapping of recursive dependencies for functions and assignments + self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() + + @classmethod + def visit_and_merge_dependencies( + cls, module: cst.Module, classes, functions, assignments, object_mapping, start_lines + ) -> "ModelFileMapper": + wrapper = MetadataWrapper(module) + mapper = cls(module) + wrapper.visit(mapper) + # Merge dependencies + mapper.merge_modular_dependencies(classes, functions, assignments, object_mapping, start_lines) + # Create the class dependencies graph + mapper.compute_class_dependencies() + return mapper + + +def common_partial_suffix(str1: str, str2: str) -> str: + """Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string, + we do not consider it a common suffix and return `""`""" + common_suffix = "" + for i in range(1, min(len(str1), len(str2)) + 1): + if str1[-i] == str2[-i]: + common_suffix = str1[-i] + common_suffix + else: + break + # We do not allow full string suffix + if common_suffix == str1 or common_suffix == str2: + common_suffix = "" + return common_suffix + + +def replace_class_node( + mapper: ModelFileMapper, class_node: cst.ClassDef, renamed_super_class: str, original_super_class: str +): + """ + Replace a class node which inherits from another modeling class. This function works in the following way: + - start from the base class node of the inherited class (a cst.Node) + - replace all methods of the base node with the methods defined in the child class + - append all new methods defined in the child class + - replace all calls to super() with the unravelled code + + | ```python | | ```python + | class GemmaModel(LlamaModel): | | class GemmaModel(nn.Module): + | def __init__(self): | | def __init__(self): + Going from: | super().__init__() | to: | super().__init__(config) + | self.dropout = 0.2 | | self.dropout = 0.2 + | ``` | | self.padding_idx = config.pad_token_id + | self.vocab_size = config.vocab_size + | self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + | self.layers = nn.ModuleList( + | [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + | ) + | self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + | self.gradient_checkpointing = False + | # Initialize weights and apply final processing + | self.post_init() + | ``` + """ + all_bases = [get_full_attribute_name(k.value) for k in class_node.bases] + if any(base is None for base in all_bases): + raise ValueError(f"Could not parse the name of the bases for {class_node.name.value}") + + original_node = mapper.classes[renamed_super_class] + # Always use the new name of the class (in case we use e.g. `ColPaliForRetrieval` inheriting from `PaliGemmaForConditionalGeneration`) + new_name = class_node.name + + # If the new class name is different from the renamed super class name, we need to update the docstrings/comments accordingly + if new_name.value != renamed_super_class: + common_suffix = common_partial_suffix(new_name.value, renamed_super_class) + # Note that this works even without common prefix, in which case it does not replace anything + old, new = renamed_super_class.replace(common_suffix, ""), new_name.value.replace(common_suffix, "") + temp_module = cst.Module(body=[original_node]) + original_node = temp_module.visit( + ReplaceNameTransformer(get_lowercase_name(old), get_lowercase_name(new), only_doc=True) + ).body[0] + + # If we explicitly passed a new base with common suffix to an old base, it is for switching the prefix + # e.g. if the "natural" parent class is `PreTrainedModel` but we wanted to rename it to `PreTrainedVisionModel` + additional_bases = [base for base in all_bases if base != original_super_class] + new_bases = [] + for original_base in original_node.bases: + new_base = original_base + # we only potentially switch base for Name-based bases, not Attribute + if m.matches(original_base.value, m.Name()): + original_base_name = original_base.value.value + for additional_base_name in additional_bases: + suffix = common_partial_suffix(original_base_name, additional_base_name) + if len(suffix) > 0 and suffix[0].isupper(): + new_name_node = original_base.value.with_changes(value=additional_base_name) + new_base = original_base.with_changes(value=new_name_node) + break + new_bases.append(new_base) + + original_methods = { + f.name.value if hasattr(f, "name") else mapper.python_module.code_for_node(f): f + for f in original_node.body.body + } + updated_methods = { + f.name.value if hasattr(f, "name") else mapper.python_module.code_for_node(f): f for f in class_node.body.body + } + end_meth = [] + + assign_targets = {} + docstring_node = [] + # Iterate directly from node.body as there can be property/setters with same names which are overwritten when we use a dict + for func in original_node.body.body: + name = func.name.value if hasattr(func, "name") else mapper.python_module.code_for_node(func) + if m.matches(func, m.FunctionDef()) and name in updated_methods and updated_methods[name] is not None: + new_params = updated_methods[name].params + # Replace the method in the replacement class, preserving decorators + kwarg_name = getattr(updated_methods[name].params, "star_kwarg", None) + if kwarg_name and kwarg_name.name.value == "super_kwargs": + parent_params = {k.name.value: k for k in func.params.params} + parent_params.update({k.name.value: k for k in new_params.params[1:]}) + new_params = new_params.with_changes( + params=list(parent_params.values()), star_kwarg=func.params.star_kwarg + ) + # Keep decorators in `modular_xxx.py` if any, else original decorators + new_decorators = ( + updated_methods[name].decorators if len(updated_methods[name].decorators) > 0 else func.decorators + ) + if not re.match( + r"\ndef .*\(.*\):\n raise.*Error\(.*", + mapper.python_module.code_for_node(updated_methods[name]), + ): + func = func.with_changes(body=updated_methods[name].body, params=new_params, decorators=new_decorators) + else: + continue + + if m.matches(func, m.SimpleStatementLine(body=[m.Assign()])): + target = mapper.python_module.code_for_node(func.body[0].targets[0]) + assign_targets[target] = func + elif m.matches(func, m.SimpleStatementLine(body=[m.AnnAssign()])): + target = mapper.python_module.code_for_node(func.body[0].target) + assign_targets[target] = func + elif m.matches(func, DOCSTRING_NODE): + docstring_node = [func] + else: + end_meth.append(func) + + # Port new methods that are defined only in modular-file and append at the end + for func in class_node.body.body: + name = func.name.value if hasattr(func, "name") else mapper.python_module.code_for_node(func) + if m.matches(func, DOCSTRING_NODE): # This processes the docstring of the class! + # Extract the original docstring + updated_docstring = func.body[0].value.value + if len(docstring_node) == 0: # If the original docstring is empty, just create one from the updated. + docstring_node = [ + cst.SimpleStatementLine(body=[cst.Expr(value=cst.SimpleString(value=updated_docstring))]) + ] + else: + original_docstring = docstring_node[0].body[0].value.value + merged_doc = merge_docstrings(original_docstring, updated_docstring) + # Update the docstring in the original function + docstring_node = [ + docstring_node[0].with_changes(body=[cst.Expr(value=cst.SimpleString(value=merged_doc))]) + ] + if name not in original_methods and func is not None and isinstance(func, cst.FunctionDef): + end_meth.append(func) + if m.matches(func, m.SimpleStatementLine(body=[m.Assign()])): + # TODO we only use single assign might cause issues + target = mapper.python_module.code_for_node(func.body[0].targets[0]) + assign_targets[target] = func + if m.matches(func, m.SimpleStatementLine(body=[m.AnnAssign()])): + target = mapper.python_module.code_for_node(func.body[0].target) + assign_targets[target] = func + end_meth = docstring_node + list(assign_targets.values()) + end_meth + + # Replace the calls to `super()` with the unrolled code + result_node = original_node.with_changes(body=cst.IndentedBlock(body=end_meth)) + temp_module = cst.Module(body=[result_node]) + new_module = MetadataWrapper(temp_module) + new_replacement_class = new_module.visit( + SuperTransformer(temp_module, original_methods, updated_methods, all_bases) + ) + new_replacement_body = new_replacement_class.body[0].body # get the indented block + + # Use decorators redefined in `modular_xxx.py` if any + new_decorators = class_node.decorators if len(class_node.decorators) > 0 else original_node.decorators + + return original_node.with_changes( + body=new_replacement_body, decorators=new_decorators, bases=new_bases, name=new_name + ) + + +TYPE_TO_FILE_TYPE = { + "Config": "configuration", + "Tokenizer": "tokenization", + "Processor": "processing", + "ImageProcessor": "image_processing", + "ImageProcessorFast": "image_processing*_fast", # "*" indicates where to insert the model name before the "_fast" suffix + "FastImageProcessorKwargs": "image_processing*_fast", + "FeatureExtractor": "feature_extractor", + "ProcessorKwargs": "processing", + "ImagesKwargs": "processing", + "TextKwargs": "processing", +} + + +def find_file_type(class_name: str) -> str: + """Based on a class name, find the file type corresponding to the class. + If the class name is `LlamaConfig` it will return `configuration`. + The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling` + """ + match_pattern = "|".join(TYPE_TO_FILE_TYPE.keys()) + match = re.search(rf"({match_pattern})$", class_name) + if match: + file_type = TYPE_TO_FILE_TYPE[match.group(1)] + else: + file_type = "modeling" + return file_type + + +# These top-level variables will always appear at the very beginning of the file, in the order they are defined in +# this list (this is to avoid having variables at weird places, even if they are not used before) +VARIABLES_AT_THE_BEGINNING = ( + "logger", + "_CHECKPOINT_FOR_DOC", + "_CONFIG_FOR_DOC", +) + +# These specific modeling imports should not be visited as other modeling files +IMPORTS_TO_SKIP_IN_MODULAR = ("auto.modeling_auto",) + + +def append_new_import_node( + node: cst.CSTNode, unused_imports: set[str], added_names: set, imports_to_keep: list[cst.CSTNode] +): + """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`. + Also modifies `added_names` in-place accordingly.""" + import_node = node.body[0] + names_to_keep = [] + for name in import_node.names: + name_value = name.evaluated_name + if name_value not in unused_imports and name_value not in added_names: + names_to_keep.append(name.with_changes(comma=cst.MaybeSentinel.DEFAULT)) + added_names.add(name_value) + if len(names_to_keep) > 0: + new_node = node.with_changes(body=[import_node.with_changes(names=names_to_keep)]) + imports_to_keep.append(new_node) + + +def get_needed_imports(body: dict[str, dict], all_imports: list[cst.CSTNode]) -> list[cst.CSTNode]: + """Get all the imports needed in the `body`, from the list of `all_imports`. + `body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`. + Note: we need to use `isinstance` on scope assignements, m.matches apparently does not work here yet! + """ + new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] + wrapper = MetadataWrapper(cst.Module(body=all_imports + new_body)) + scopes = set(wrapper.resolve(ScopeProvider).values()) + unused_imports = set() + import_ref_count = defaultdict(lambda: 0) + for scope in scopes: + for assignment in scope.assignments: + node = assignment.node + if isinstance(assignment, cst.metadata.Assignment) and isinstance(node, (cst.Import, cst.ImportFrom)): + ref_count = len(assignment.references) + name = assignment.name + import_ref_count[name] = max(ref_count, import_ref_count[name]) + # Similar imports may be redefined, and only used between their 1st and 2nd definition so if we already have + # a ref count > 0 at any point, the imports is actually used + unused_imports = {name for name, count in import_ref_count.items() if count <= 0 or name in body.keys()} + + imports_to_keep = [] + # We need to keep track of which names were already imported, because some import may be duplicated from multiple sources + # or be both protected and unprotected due to inconsistency between models + added_names = set() + existing_protected_statements = set() # str repr of the import nodes - does not work with the nodes directly + for node in all_imports: + if m.matches(node, m.If()): # handle safe imports + new_statements = [] + for stmt_node in node.body.body: + append_new_import_node(stmt_node, unused_imports, added_names, new_statements) + new_statements = [stmt for stmt in new_statements if str(stmt) not in existing_protected_statements] + if len(new_statements) > 0: + new_node = node.with_changes(body=node.body.with_changes(body=new_statements)) + imports_to_keep.append(new_node) + existing_protected_statements.update({str(stmt) for stmt in new_statements}) + else: + append_new_import_node(node, unused_imports, added_names, imports_to_keep) + + protected_import_nodes = [node for node in imports_to_keep if m.matches(node, m.If())] + usual_import_nodes = [node for node in imports_to_keep if not m.matches(node, m.If())] + + # Protected imports always appear at the end of all imports + return usual_import_nodes + protected_import_nodes + + +def split_all_assignment(node: cst.CSTNode) -> dict[str, cst.CSTNode]: + """Split the `__all__` assignment found in the modular between each corresponding files.""" + all_all_per_file = {} + assign_node = node.body[0] + if isinstance(assign_node.value, cst.List): + # Extract the elements from the list + all_all_to_add = defaultdict(list) + for element in assign_node.value.elements: + if isinstance(element.value, cst.SimpleString): + # Remove quotes and add the string to the elements list + class_name = element.value.value + file = find_file_type(element.value.evaluated_value) + all_all_to_add[file] += [class_name] + for file, new_alls in all_all_to_add.items(): + new_node = assign_node.with_changes( + value=cst.List(elements=[cst.Element(value=cst.SimpleString(value=k)) for k in new_alls]) + ) + all_all_per_file[file] = node.with_changes(body=[new_node]) + return all_all_per_file + + +class ModularFileMapper(ModuleMapper): + """This is a Mapper to visit a modular file (like `modular_llama.py`). It visits the whole file, recording dependency, + then visits all imported modeling files (like `modeling_llama.py`), and manages their mutual dependencies. + Calling the method `create_modules()` after visit will create all modules based on this modular file. + """ + + def __init__(self, python_module, new_name): + super().__init__(python_module) + # fmt: off + self.model_name = new_name # name of the model being defined. Should be in the format of `llama` or `layout_xlm` or `phi3` + + self.model_specific_imported_objects: Dict[str, str] = {} # e.g. {"LlamaModel": "transformers.models.llama.modeling_llama"} + self.model_specific_modules: Dict[str, cst.Module] = {} # e.g. {"transformers.models.llama.modeling_llama": cst.Module} + + self.all_all_to_add = {} + # fmt: on + + def visit_ImportFrom(self, node: cst.ImportFrom) -> None: + """When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it, + and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`. + """ + import_module = self.python_module.code_for_node(node.module) + import_statement = "." * len(node.relative) + import_module + if any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR): + return + if m.matches(node.module, m.Attribute()): + for imported_ in node.names: + _import = re.search( + rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement + ) + if _import: + source = _import.group(1) + if source == "modeling" and "Config" in self.python_module.code_for_node(imported_): + raise ValueError( + f"You are importing {self.python_module.code_for_node(imported_)} from the modeling file. Import from the `configuration_xxxx.py` file instead" + ) + if import_module not in self.model_specific_modules: + if "models" not in import_module: + import_module = "models." + import_module + if "transformers" not in import_module: + import_module = "transformers." + import_module + source_code = get_module_source_from_name(import_module) + tree = cst.parse_module(source_code) + self.model_specific_modules[import_module] = tree + imported_object = self.python_module.code_for_node(imported_.name) + self.model_specific_imported_objects[imported_object] = import_module + if m.matches(node.module, m.Name()): + if "transformers" == import_module: + raise ValueError( + f"You are importing from {import_module} directly using global imports. Import from the correct local path" + ) + + def visit_SimpleStatementLine(self, node): + """If we visit an import statement not previously visited, record it. If we visit a module-scope assignment, + simply record it or, if it is `__all__`, split it between files where we should dispatch it. + """ + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + if m.matches(parent_node, m.Module()): + if m.matches(node, m.SimpleStatementLine(body=[m.Import()])): + self.imports.append(node) + elif m.matches(node, m.SimpleStatementLine(body=[m.ImportFrom()])): + import_module = self.python_module.code_for_node(node.body[0].module) + import_statement = "." * len(node.body[0].relative) + import_module + if not ( + re.search(rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement) + and not any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR) + ): + self.imports.append(node) + elif m.matches(node, simple_top_level_assign_structure): + assigned_variable = node.body[0].targets[0].target.value + # __all__ is treated differently and not added to general assignments + if assigned_variable == "__all__": + self.all_all_to_add = split_all_assignment(node) + else: + self.current_assignment = assigned_variable + self.assignments[assigned_variable] = node + + def leave_Module(self, node): + """When we leave the modular file, we do the following in order: + 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update + its dependency graph with the new function and assignment definitions found in the modular + 2. update the modular dependency graph with the imported functions and assignments (found when visiting the matching files) + 3. compute the nested (recursive) function and assignment dependencies + """ + # Takes care of finalizing our visit + super().leave_Module(node) + + # 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update dependencies + self.visited_modules = {} + self.renamers = {} + name_prefixes = self.infer_new_model_name() + for file, module in self.model_specific_modules.items(): + file_model_name = file.split(".")[-2] + new_name = name_prefixes[file] + renamer = ReplaceNameTransformer(file_model_name, new_name, self.model_name) + renamed_module = module.visit(renamer) + self.visited_modules[file] = ModelFileMapper.visit_and_merge_dependencies( + renamed_module, + self.classes, + self.functions, + self.assignments, + self.object_dependency_mapping, + self.start_lines, + ) + # We record it so that we can rename classes later the exact same way + self.renamers[file] = renamer + + # 2. in turn, we need to add the imported functions/assignments to the dependencies of the modular mapper, using the + # definitions found in the visited files + self.merge_model_specific_imports(self.visited_modules) + + # 3. compute the nested (recursive) function and assignment dependencies + self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() + + # We need to keep track of which objects were imported directly into which modeling file to not add them wrongly later + # Note that we may visit several of the same file types, thus we save them per file type, not file + self.imported_objects_per_file = defaultdict(set) + for file, mapper in self.visited_modules.items(): + file_type = re.search(rf"^transformers\.models\.\w+\.({self.match_patterns})_.*", file).group(1) + self.imported_objects_per_file[file_type].update(mapper.objects_imported_from_modeling) + + def merge_model_specific_imports(self, visited_modules): + """Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph, + based on the visited files.""" + self.start_lines_file_mapping = {} + self.added_objects_file_mapping = {} + for object_name, file in self.model_specific_imported_objects.items(): + visited_module = visited_modules[file] + self.start_lines_file_mapping[file] = visited_module.start_lines + # Add functions and their dependencies + if object_name in visited_module.functions and object_name not in self.functions: + self.functions[object_name] = visited_module.functions[object_name] + self.added_objects_file_mapping[object_name] = file + dependencies = visited_module.object_dependency_mapping.get(object_name, None) + if dependencies is not None: + self.object_dependency_mapping[object_name] = dependencies + for dep in dependencies: + if dep not in self.global_nodes: + self.added_objects_file_mapping[dep] = file + self.functions[dep] = visited_module.global_nodes[dep] + + # Add/overwrite the imported functions to other visited modules as well, in case it is absent/different + # in he modeling source file of the inherited class. See `examples/modular-tranformers/modular_switch_function.py` + # and `examples/modular-tranformers/modular_add_function.py` for examples + recursive_dependencies = visited_module.object_recursive_dependency_mapping.get(object_name, set()) + node_recursive_dependencies_mapping = { + dep: visited_module.global_nodes[dep] for dep in recursive_dependencies + } + for filename, module_mapper in self.visited_modules.items(): + if filename != file: + module_mapper.global_nodes[object_name] = visited_module.functions[object_name] + if len(recursive_dependencies) > 0: + module_mapper.object_recursive_dependency_mapping[object_name] = recursive_dependencies + module_mapper.global_nodes.update(node_recursive_dependencies_mapping) + + # Add assignments and their dependencies + elif object_name in visited_module.assignments and object_name not in self.assignments: + self.assignments[object_name] = visited_module.assignments[object_name] + self.added_objects_file_mapping[object_name] = file + dependencies = visited_module.object_dependency_mapping.get(object_name, None) + if dependencies is not None: + self.object_dependency_mapping[object_name] = dependencies + for dep in dependencies: + if dep not in self.global_nodes: + self.added_objects_file_mapping[dep] = file + self.assignments[dep] = visited_module.global_nodes[dep] + + # Do not forget to re-assign all nodes after the merge + self.global_nodes = {**self.assignments, **self.classes, **self.functions} + # And restric dependencies to those nodes only + self._restrict_dependencies_to_known_entities() + + def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: + """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that + will be created based on the modular. + """ + relative_order = {} + idx = 0 + + original_dependencies = [] + other_files_dependencies = defaultdict(list) + for dep in tuple(missing_dependencies): + if dep in self.added_objects_file_mapping: + file = self.added_objects_file_mapping[dep] + other_files_dependencies[file].append(dep) + else: + original_dependencies.append(dep) + # Sort all lists according to the order in their respective file + all_dependencies = [] + for file, dependencies in other_files_dependencies.items(): + sorted_dependencies = sorted(dependencies, key=lambda x: self.start_lines_file_mapping[file][x]) + all_dependencies += sorted_dependencies + all_dependencies += sorted(original_dependencies, key=lambda x: self.start_lines[x]) + + # Add all original node first, then merged ones (one file at a time) + for dep in all_dependencies: + relative_order[dep] = idx + idx += 1 + + return relative_order + + def infer_new_model_name(self) -> dict: + """Infer whether we are using a model name prefix different from the usual model name as defined from the filename. + This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`, + so we have something like: + ```python + class NewModelNameTextDecoderLayer(LlamaDecoderLayer): + pass + ``` + with the `Text` prefix added to the model name. + However, in case of multiple prefix used, we raise a warning and use the most frequent prefix, to avoid parsing + the same file multiple times and inconsistencies in the objects added from dependencies. + If the new prefix collides with a prefix of another class in the file where we are importing from, then we also + raise a warning, and use the default prefix (model name) to avoid collisions in dependencies. + """ + prefix_model_name_mapping = defaultdict(Counter) + cased_default_name = get_cased_name(self.model_name) + # Iterate over all new classes to get modeling super classes + for class_name, class_node in self.classes.items(): + modeling_bases = [ + k.value.value for k in class_node.bases if k.value.value in self.model_specific_imported_objects + ] + if len(modeling_bases) > 1: + raise ValueError( + f"{class_name} was defined with more than 1 model-specific super class. This is unsupported. We found {(*modeling_bases,)}." + ) + if len(modeling_bases) == 1: + filename = self.model_specific_imported_objects[modeling_bases[0]] + cased_model_name = cased_default_name # the default name prefix + suffix = common_partial_suffix(class_name, modeling_bases[0]) + if len(suffix) > 0 and suffix[0].isupper(): + cased_model_name = class_name.replace(suffix, "") + prefix_model_name_mapping[filename].update([cased_model_name]) + + # Check if we found multiple prefixes for some modeling files + final_name_mapping = {} + for file, prefixes_counter in prefix_model_name_mapping.items(): + if len(prefixes_counter) > 1: + _, total = prefixes_counter.most_common(1)[0] + most_used_entities = [name for name, count in prefixes_counter.most_common() if count == total] + # if the default name is in the pool of equally used prefixes, use it, otherwise last encountered + final_name = cased_default_name if cased_default_name in most_used_entities else most_used_entities[-1] + else: + final_name = list(prefixes_counter)[0] + # Check if the prefix can be used without collisions in the names + old_cased_model_name = get_cased_name(file.split(".")[-2]) + old_model_name_prefix = final_name.replace(cased_default_name, old_cased_model_name) + # Raise adequate warning depending on the situation + has_prefix_collision = f"\nclass {old_model_name_prefix}" in get_module_source_from_name(file) + if final_name != cased_default_name and has_prefix_collision: + if len(prefixes_counter) > 1: + logger.warning( + f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. However, the " + f"most used one, '{final_name}', is already present in the source file and will likely cause consistency " + f"issues. For this reason we fallback to the default prefix '{cased_default_name}' when grabbing args " + "and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different " + f"from '{cased_default_name}') or use a single prefix in all the modular (best)." + ) + else: + logger.warning( + f"We detected the use of the new default prefix {final_name} when inheriting from {file}. However, it is " + "already present in the source file and will likely cause consistency issues. For this reason we fallback " + f"to the default prefix '{cased_default_name}' when grabbing args and dependencies. Make sure to subclass " + f"the intermediate classes with the prefix you want (if different from '{cased_default_name}')" + ) + final_name = cased_default_name + elif len(prefixes_counter) > 1: + logger.warning( + f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. We will only " + f"use the most used '{final_name}' prefix when grabbing args and dependencies. Make sure to subclass the " + f"intermediate classes with the prefix you want (if different from '{final_name}') or use a single prefix " + "in all the modular (best)." + ) + final_name_mapping[file] = get_lowercase_name(final_name) + + # Check we are not missing imported files + for file in self.model_specific_modules.keys(): + if file not in final_name_mapping.keys(): + final_name_mapping[file] = self.model_name + + return final_name_mapping + + +def check_dependencies_and_create_import_node( + file_type: str, new_dependencies: set[str], mapper: ModuleMapper, new_name: str +) -> tuple[set[str], dict[str, cst.CSTNode]]: + """Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case, + we need to remove it from the dependencies, and create a new import to it instead. + This scenario may appear in the following case: + 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` + (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 + part of the standard dependency graph (because we never encountered an import towards this new class in any file). + For example imagine the following `modular.py`: + ``` + from ..llama.modeling_llama import LlamaModel + + class NewNameTextConfig(PretrainedConfig): + ... + + class NewNameConfig(PretrainedConfig): + ... + + class NewNameModel(LlamaModel): + config = NewNameConfig() + text_config = NewNameTextConfig() + ... + ``` + then without the help of this function, `NewNameTextConfig` would be imported in the `modeling_newname.py` as well as + `configuration_newname.py`, because `modeling_llama.py` tells us to not import `NewNameConfig`, but has no + knowledge of `NewNameTextConfig`. + """ + class_dependencies = {dep for dep in new_dependencies if m.matches(mapper.global_nodes[dep], m.ClassDef())} + corrected_dependencies = new_dependencies.copy() + new_imports = {} + for class_name in class_dependencies: + class_file_type = find_file_type(class_name) + # In this case, we need to remove it from the dependencies and create a new import instead + if class_file_type != file_type: + corrected_dependencies.remove(class_name) + import_statement = f"from .{class_file_type}_{new_name} import {class_name}" + new_imports[class_name] = cst.parse_statement(import_statement) + + return corrected_dependencies, new_imports + + +def get_class_node_and_dependencies( + modular_mapper: ModularFileMapper, class_name: str, node: cst.CSTNode, files: dict[str, dict] +) -> tuple[dict, str, dict]: + """Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new + class node based on the inherited classes if needed. Also returns any new imports of a new class defined in + the modular that we nay need. + """ + # An exception was already raised if this has len > 1 + model_specific_bases = [ + k.value.value for k in node.bases if k.value.value in modular_mapper.model_specific_imported_objects + ] + super_class = model_specific_bases[0] if len(model_specific_bases) == 1 else None + + file_type = find_file_type(class_name) + file_to_update = files[file_type] + model_name = modular_mapper.model_name + + # This is used to avoid adding objects to the dependencies graph if they will be imported already + imported_objects = modular_mapper.imported_objects_per_file[file_type] + + # We need to replace the class node with the transformers (modeling file) super class node + if super_class is not None: + super_file_name = modular_mapper.model_specific_imported_objects[super_class] + + # Get the mapper corresponding to the inherited class + mapper = modular_mapper.visited_modules[super_file_name] + # Rename the super class according to the exact same rule we used when renaming the whole module + renamer = modular_mapper.renamers[super_file_name] + renamed_super_class = preserve_case_replace(super_class, renamer.patterns, renamer.cased_new_name) + + # Create the new class node + updated_node = replace_class_node(mapper, node, renamed_super_class, super_class) + + # Grab all immediate dependencies of the new node + new_node_dependencies = augmented_dependencies_for_class_node(updated_node, mapper, imported_objects) + + # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove + # it from the dependencies, and add a new import of it instead + new_node_dependencies, new_imports = check_dependencies_and_create_import_node( + file_type, new_node_dependencies, mapper, model_name + ) + + # The node was modified -> look for all recursive dependencies of the new node + all_dependencies_to_add = find_all_dependencies( + dependency_mapping=mapper.class_dependency_mapping, + initial_dependencies=new_node_dependencies, + initial_checked_dependencies=set(file_to_update.keys()), + ) + + relative_dependency_order = mapper.compute_relative_order(all_dependencies_to_add) + nodes_to_add = { + dep: (relative_dependency_order[dep], mapper.global_nodes[dep]) for dep in all_dependencies_to_add + } + + # No transformers (modeling file) super class, just check functions and assignments dependencies + else: + updated_node = node + # The node was NOT modified -> no need to look recursively for other class dependencies. Indeed, even if they are not + # already defined (which would mean a weird order of the code in the modular...), they will be in the future + all_dependencies_to_add = augmented_dependencies_for_class_node(updated_node, modular_mapper, imported_objects) + + # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove + # it from the dependencies, and add a new import of it instead + all_dependencies_to_add, new_imports = check_dependencies_and_create_import_node( + file_type, all_dependencies_to_add, modular_mapper, model_name + ) + + relative_dependency_order = modular_mapper.compute_relative_order(all_dependencies_to_add) + nodes_to_add = { + dep: (relative_dependency_order[dep], modular_mapper.global_nodes[dep]) + for dep in all_dependencies_to_add + if dep not in file_to_update.keys() + } + + # Add the class node itself to the nodes to add + class_idx = max(relative_dependency_order.values()) + 1 if len(relative_dependency_order) > 0 else 0 + nodes_to_add[class_name] = (class_idx, updated_node) + + return nodes_to_add, file_type, new_imports + + +def create_modules(modular_mapper: ModularFileMapper) -> dict[str, cst.Module]: + """Create all the new modules based on visiting the modular file. It replaces all classes as necesary.""" + files = defaultdict(dict) + current_file_indices = defaultdict(lambda: 0) + + # For each class defined in modular, potentially replace the node and add it with its dependencies + for class_name, node in modular_mapper.classes.items(): + nodes_to_add, file_type, new_imports = get_class_node_and_dependencies(modular_mapper, class_name, node, files) + + # Add the new potential new imports that we may need to the `modular_mapper` variable + modular_mapper.imported_objects_per_file[file_type].update(new_imports.keys()) + modular_mapper.imports.extend(list(new_imports.values())) + + # Sort the nodes according to their relative order + nodes_to_add = sorted(nodes_to_add.items(), key=lambda x: x[1][0]) + # Write all nodes to file + for dependency, (_, node) in nodes_to_add: + # This is used to keep certain variables at the beginning of the file + try: + # The -1000 is arbitrary -> just keep it bigger than the list + idx = -1000 + VARIABLES_AT_THE_BEGINNING.index(dependency) + except ValueError: + idx = current_file_indices[file_type] + current_file_indices[file_type] += 1 + files[file_type][dependency] = {"insert_idx": idx, "node": node} + + # Add the __all__ statement to files at the end + for file_type, node in modular_mapper.all_all_to_add.items(): + idx = current_file_indices[file_type] + files[file_type]["__all__"] = {"insert_idx": idx, "node": node} + + # Aggregate all the imports statements (we look for duplicates with the code_for_node, not the nodes themselves because + # they are wrapped in SimpleStatementLine or If which could have different newlines, blanks etc) + all_imports = modular_mapper.imports.copy() + all_imports_code = {modular_mapper.python_module.code_for_node(node).strip() for node in all_imports} + for file, mapper in modular_mapper.visited_modules.items(): + new_imports = [ + node for node in mapper.imports if mapper.python_module.code_for_node(node).strip() not in all_imports_code + ] + new_imports_code = {mapper.python_module.code_for_node(node).strip() for node in new_imports} + all_imports.extend(new_imports) + all_imports_code.update(new_imports_code) + + # Find the correct imports, and write the new modules + for file, body in files.items(): + new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] + needed_imports = get_needed_imports(body, all_imports) + full_module = needed_imports + new_body + new_module = cst.Module(body=full_module, header=modular_mapper.python_module.header) + files[file] = new_module + + return files + + +def convert_modular_file(modular_file): + pattern = re.search(r"modular_(.*)(?=\.py$)", modular_file) + output = {} + if pattern is not None: + model_name = pattern.groups()[0] + # Parse the Python file + with open(modular_file, "r", encoding="utf-8") as file: + code = file.read() + module = cst.parse_module(code) + wrapper = MetadataWrapper(module) + cst_transformers = ModularFileMapper(module, model_name) + wrapper.visit(cst_transformers) + for file, module in create_modules(cst_transformers).items(): + if module != {}: + # Get relative path starting from src/transformers/ + relative_path = re.search( + r"(src/transformers/.*|examples/.*)", os.path.abspath(modular_file).replace("\\", "/") + ).group(1) + + header = AUTO_GENERATED_MESSAGE.format( + relative_path=relative_path, short_name=os.path.basename(relative_path) + ) + ruffed_code = run_ruff(header + module.code, True) + formatted_code = run_ruff(ruffed_code, False) + output[file] = [formatted_code, ruffed_code] + return output + else: + print(f"modular pattern not found in {modular_file}, exiting") + return {} + + +def save_modeling_file(modular_file, converted_file): + for file_type in converted_file.keys(): + file_name_prefix = file_type.split("*")[0] + file_name_suffix = file_type.split("*")[-1] if "*" in file_type else "" + new_file_name = modular_file.replace("modular_", f"{file_name_prefix}_").replace( + ".py", f"{file_name_suffix}.py" + ) + non_comment_lines = len( + [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] + ) + if len(converted_file[file_type][0].strip()) > 0 and non_comment_lines > 0: + with open(new_file_name, "w", encoding="utf-8") as f: + f.write(converted_file[file_type][0]) + else: + non_comment_lines = len( + [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] + ) + if len(converted_file[file_type][1].strip()) > 0 and non_comment_lines > 0: + logger.warning("The modeling code contains errors, it's written without formatting") + with open(new_file_name, "w", encoding="utf-8") as f: + f.write(converted_file[file_type][1]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--files_to_parse", + default=["all"], + nargs="+", + help="A list of `modular_xxxx` files that should be converted to single model file", + ) + args = parser.parse_args() + if args.files_to_parse == ["all"]: + args.files_to_parse = glob.glob("src/transformers/models/**/modular_*.py", recursive=True) + if args.files_to_parse == ["examples"]: + args.files_to_parse = glob.glob("examples/**/modular_*.py", recursive=True) + + priority_list, _ = find_priority_list(args.files_to_parse) + assert len(priority_list) == len(args.files_to_parse), "Some files will not be converted" + + for file_name in priority_list: + print(f"Converting {file_name} to a single model single file format") + module_path = file_name.replace("/", ".").replace(".py", "").replace("src.", "") + converted_files = convert_modular_file(file_name) + converter = save_modeling_file(file_name, converted_files) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/not_doctested.txt b/tasks/tasksmith-441eeab80047/environment/source/utils/not_doctested.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c56ed144cae9b38a88aceee23319869a0df58ca --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/not_doctested.txt @@ -0,0 +1,979 @@ +docs/source/en/_config.py +docs/source/en/accelerate.md +docs/source/en/add_new_model.md +docs/source/en/add_new_pipeline.md +docs/source/en/agents.md +docs/source/en/agents.md +docs/source/en/attention.md +docs/source/en/community.md +docs/source/en/contributing.md +docs/source/en/custom_models.md +docs/source/en/debugging.md +docs/source/en/fast_tokenizers.md +docs/source/en/glossary.md +docs/source/en/hpo_train.md +docs/source/en/index.md +docs/source/en/installation.md +docs/source/en/internal/audio_utils.md +docs/source/en/internal/file_utils.md +docs/source/en/internal/image_processing_utils.md +docs/source/en/internal/modeling_utils.md +docs/source/en/internal/pipelines_utils.md +docs/source/en/internal/time_series_utils.md +docs/source/en/internal/tokenization_utils.md +docs/source/en/internal/trainer_utils.md +docs/source/en/llm_tutorial.md +docs/source/en/main_classes/agent.md +docs/source/en/main_classes/callback.md +docs/source/en/main_classes/configuration.md +docs/source/en/main_classes/data_collator.md +docs/source/en/main_classes/deepspeed.md +docs/source/en/main_classes/feature_extractor.md +docs/source/en/main_classes/image_processor.md +docs/source/en/main_classes/keras_callbacks.md +docs/source/en/main_classes/logging.md +docs/source/en/main_classes/model.md +docs/source/en/main_classes/onnx.md +docs/source/en/main_classes/optimizer_schedules.md +docs/source/en/main_classes/output.md +docs/source/en/main_classes/pipelines.md +docs/source/en/main_classes/processors.md +docs/source/en/main_classes/quantization.md +docs/source/en/main_classes/tokenizer.md +docs/source/en/main_classes/trainer.md +docs/source/en/model_doc/albert.md +docs/source/en/model_doc/align.md +docs/source/en/model_doc/altclip.md +docs/source/en/model_doc/audio-spectrogram-transformer.md +docs/source/en/model_doc/auto.md +docs/source/en/model_doc/autoformer.md +docs/source/en/model_doc/bark.md +docs/source/en/model_doc/bart.md +docs/source/en/model_doc/barthez.md +docs/source/en/model_doc/bartpho.md +docs/source/en/model_doc/beit.md +docs/source/en/model_doc/bert-generation.md +docs/source/en/model_doc/bert-japanese.md +docs/source/en/model_doc/bert.md +docs/source/en/model_doc/bertweet.md +docs/source/en/model_doc/big_bird.md +docs/source/en/model_doc/bigbird_pegasus.md +docs/source/en/model_doc/biogpt.md +docs/source/en/model_doc/bit.md +docs/source/en/model_doc/blenderbot-small.md +docs/source/en/model_doc/blenderbot.md +docs/source/en/model_doc/blip-2.md +docs/source/en/model_doc/blip.md +docs/source/en/model_doc/bloom.md +docs/source/en/model_doc/bort.md +docs/source/en/model_doc/bridgetower.md +docs/source/en/model_doc/camembert.md +docs/source/en/model_doc/canine.md +docs/source/en/model_doc/chinese_clip.md +docs/source/en/model_doc/clap.md +docs/source/en/model_doc/clip.md +docs/source/en/model_doc/clipseg.md +docs/source/en/model_doc/codegen.md +docs/source/en/model_doc/conditional_detr.md +docs/source/en/model_doc/convbert.md +docs/source/en/model_doc/convnext.md +docs/source/en/model_doc/convnextv2.md +docs/source/en/model_doc/cpm.md +docs/source/en/model_doc/cpmant.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/cvt.md +docs/source/en/model_doc/data2vec.md +docs/source/en/model_doc/deberta-v2.md +docs/source/en/model_doc/deberta.md +docs/source/en/model_doc/decision_transformer.md +docs/source/en/model_doc/deformable_detr.md +docs/source/en/model_doc/deit.md +docs/source/en/model_doc/deplot.md +docs/source/en/model_doc/deta.md +docs/source/en/model_doc/detr.md +docs/source/en/model_doc/dialogpt.md +docs/source/en/model_doc/dinat.md +docs/source/en/model_doc/dinov2.md +docs/source/en/model_doc/distilbert.md +docs/source/en/model_doc/dit.md +docs/source/en/model_doc/dpr.md +docs/source/en/model_doc/dpt.md +docs/source/en/model_doc/efficientformer.md +docs/source/en/model_doc/efficientnet.md +docs/source/en/model_doc/electra.md +docs/source/en/model_doc/encodec.md +docs/source/en/model_doc/ernie.md +docs/source/en/model_doc/ernie_m.md +docs/source/en/model_doc/esm.md +docs/source/en/model_doc/flan-t5.md +docs/source/en/model_doc/flan-ul2.md +docs/source/en/model_doc/flaubert.md +docs/source/en/model_doc/flava.md +docs/source/en/model_doc/fnet.md +docs/source/en/model_doc/focalnet.md +docs/source/en/model_doc/fsmt.md +docs/source/en/model_doc/funnel.md +docs/source/en/model_doc/git.md +docs/source/en/model_doc/glpn.md +docs/source/en/model_doc/gpt-sw3.md +docs/source/en/model_doc/gpt2.md +docs/source/en/model_doc/gpt_bigcode.md +docs/source/en/model_doc/gpt_neo.md +docs/source/en/model_doc/gpt_neox.md +docs/source/en/model_doc/gpt_neox_japanese.md +docs/source/en/model_doc/gptj.md +docs/source/en/model_doc/gptsan-japanese.md +docs/source/en/model_doc/graphormer.md +docs/source/en/model_doc/groupvit.md +docs/source/en/model_doc/herbert.md +docs/source/en/model_doc/hubert.md +docs/source/en/model_doc/ibert.md +docs/source/en/model_doc/idefics.md +docs/source/en/model_doc/imagegpt.md +docs/source/en/model_doc/informer.md +docs/source/en/model_doc/instructblip.md +docs/source/en/model_doc/jukebox.md +docs/source/en/model_doc/layoutlm.md +docs/source/en/model_doc/layoutlmv2.md +docs/source/en/model_doc/layoutlmv3.md +docs/source/en/model_doc/layoutxlm.md +docs/source/en/model_doc/led.md +docs/source/en/model_doc/levit.md +docs/source/en/model_doc/lilt.md +docs/source/en/model_doc/llama.md +docs/source/en/model_doc/llama2.md +docs/source/en/model_doc/llava.md +docs/source/en/model_doc/llava_next.md +docs/source/en/model_doc/longformer.md +docs/source/en/model_doc/longt5.md +docs/source/en/model_doc/luke.md +docs/source/en/model_doc/lxmert.md +docs/source/en/model_doc/m2m_100.md +docs/source/en/model_doc/madlad-400.md +docs/source/en/model_doc/marian.md +docs/source/en/model_doc/mask2former.md +docs/source/en/model_doc/maskformer.md +docs/source/en/model_doc/matcha.md +docs/source/en/model_doc/mbart.md +docs/source/en/model_doc/mctct.md +docs/source/en/model_doc/mega.md +docs/source/en/model_doc/megatron-bert.md +docs/source/en/model_doc/megatron_gpt2.md +docs/source/en/model_doc/mgp-str.md +docs/source/en/model_doc/mistral.md +docs/source/en/model_doc/mixtral.md +docs/source/en/model_doc/mluke.md +docs/source/en/model_doc/mms.md +docs/source/en/model_doc/mobilebert.md +docs/source/en/model_doc/mobilenet_v1.md +docs/source/en/model_doc/mobilenet_v2.md +docs/source/en/model_doc/mobilevit.md +docs/source/en/model_doc/mobilevitv2.md +docs/source/en/model_doc/mpnet.md +docs/source/en/model_doc/mpt.md +docs/source/en/model_doc/mra.md +docs/source/en/model_doc/mt5.md +docs/source/en/model_doc/musicgen.md +docs/source/en/model_doc/musicgen_melody.md +docs/source/en/model_doc/mvp.md +docs/source/en/model_doc/nat.md +docs/source/en/model_doc/nezha.md +docs/source/en/model_doc/nllb-moe.md +docs/source/en/model_doc/nllb.md +docs/source/en/model_doc/nystromformer.md +docs/source/en/model_doc/oneformer.md +docs/source/en/model_doc/open-llama.md +docs/source/en/model_doc/openai-gpt.md +docs/source/en/model_doc/opt.md +docs/source/en/model_doc/owlvit.md +docs/source/en/model_doc/pegasus.md +docs/source/en/model_doc/pegasus_x.md +docs/source/en/model_doc/perceiver.md +docs/source/en/model_doc/phobert.md +docs/source/en/model_doc/pix2struct.md +docs/source/en/model_doc/plbart.md +docs/source/en/model_doc/poolformer.md +docs/source/en/model_doc/pop2piano.md +docs/source/en/model_doc/prophetnet.md +docs/source/en/model_doc/pvt.md +docs/source/en/model_doc/qdqbert.md +docs/source/en/model_doc/qwen2.md +docs/source/en/model_doc/qwen2_moe.md +docs/source/en/model_doc/rag.md +docs/source/en/model_doc/realm.md +docs/source/en/model_doc/reformer.md +docs/source/en/model_doc/regnet.md +docs/source/en/model_doc/rembert.md +docs/source/en/model_doc/resnet.md +docs/source/en/model_doc/retribert.md +docs/source/en/model_doc/roberta-prelayernorm.md +docs/source/en/model_doc/roberta.md +docs/source/en/model_doc/roc_bert.md +docs/source/en/model_doc/roformer.md +docs/source/en/model_doc/rwkv.md +docs/source/en/model_doc/sam.md +docs/source/en/model_doc/segformer.md +docs/source/en/model_doc/sew-d.md +docs/source/en/model_doc/sew.md +docs/source/en/model_doc/speech-encoder-decoder.md +docs/source/en/model_doc/speech_to_text_2.md +docs/source/en/model_doc/speecht5.md +docs/source/en/model_doc/splinter.md +docs/source/en/model_doc/squeezebert.md +docs/source/en/model_doc/swiftformer.md +docs/source/en/model_doc/swin.md +docs/source/en/model_doc/swin2sr.md +docs/source/en/model_doc/swinv2.md +docs/source/en/model_doc/table-transformer.md +docs/source/en/model_doc/tapas.md +docs/source/en/model_doc/time_series_transformer.md +docs/source/en/model_doc/timesformer.md +docs/source/en/model_doc/trajectory_transformer.md +docs/source/en/model_doc/transfo-xl.md +docs/source/en/model_doc/trocr.md +docs/source/en/model_doc/tvlt.md +docs/source/en/model_doc/ul2.md +docs/source/en/model_doc/umt5.md +docs/source/en/model_doc/unispeech-sat.md +docs/source/en/model_doc/unispeech.md +docs/source/en/model_doc/upernet.md +docs/source/en/model_doc/van.md +docs/source/en/model_doc/videomae.md +docs/source/en/model_doc/vilt.md +docs/source/en/model_doc/vipllava.md +docs/source/en/model_doc/vision-encoder-decoder.md +docs/source/en/model_doc/vision-text-dual-encoder.md +docs/source/en/model_doc/visual_bert.md +docs/source/en/model_doc/vit.md +docs/source/en/model_doc/vit_hybrid.md +docs/source/en/model_doc/vit_mae.md +docs/source/en/model_doc/vit_msn.md +docs/source/en/model_doc/vivit.md +docs/source/en/model_doc/wav2vec2-conformer.md +docs/source/en/model_doc/wav2vec2.md +docs/source/en/model_doc/wav2vec2_phoneme.md +docs/source/en/model_doc/wavlm.md +docs/source/en/model_doc/whisper.md +docs/source/en/model_doc/xclip.md +docs/source/en/model_doc/xglm.md +docs/source/en/model_doc/xlm-prophetnet.md +docs/source/en/model_doc/xlm-roberta-xl.md +docs/source/en/model_doc/xlm-roberta.md +docs/source/en/model_doc/xlm-v.md +docs/source/en/model_doc/xlm.md +docs/source/en/model_doc/xlnet.md +docs/source/en/model_doc/xls_r.md +docs/source/en/model_doc/xlsr_wav2vec2.md +docs/source/en/model_doc/xmod.md +docs/source/en/model_doc/yolos.md +docs/source/en/model_doc/yoso.md +docs/source/en/model_memory_anatomy.md +docs/source/en/model_sharing.md +docs/source/en/model_summary.md +docs/source/en/notebooks.md +docs/source/en/pad_truncation.md +docs/source/en/peft.md +docs/source/en/perf_hardware.md +docs/source/en/perf_infer_cpu.md +docs/source/en/perf_infer_gpu_one.md +docs/source/en/perf_torch_compile.md +docs/source/en/perf_train_cpu.md +docs/source/en/perf_train_cpu_many.md +docs/source/en/perf_train_gpu_many.md +docs/source/en/perf_train_gpu_one.md +docs/source/en/perf_train_special.md +docs/source/en/perf_train_tpu_tf.md +docs/source/en/perplexity.md +docs/source/en/philosophy.md +docs/source/en/pipeline_webserver.md +docs/source/en/pr_checks.md +docs/source/en/run_scripts.md +docs/source/en/serialization.md +docs/source/en/tasks/asr.md +docs/source/en/tasks/audio_classification.md +docs/source/en/tasks/document_question_answering.md +docs/source/en/tasks/idefics.md +docs/source/en/tasks/image_captioning.md +docs/source/en/tasks/image_classification.md +docs/source/en/tasks/language_modeling.md +docs/source/en/tasks/masked_language_modeling.md +docs/source/en/tasks/monocular_depth_estimation.md +docs/source/en/tasks/multiple_choice.md +docs/source/en/tasks/object_detection.md +docs/source/en/tasks/question_answering.md +docs/source/en/tasks/semantic_segmentation.md +docs/source/en/tasks/sequence_classification.md +docs/source/en/tasks/summarization.md +docs/source/en/tasks/text-to-speech.md +docs/source/en/tasks/token_classification.md +docs/source/en/tasks/translation.md +docs/source/en/tasks/video_classification.md +docs/source/en/tasks/visual_question_answering.md +docs/source/en/tasks/zero_shot_image_classification.md +docs/source/en/tasks/zero_shot_object_detection.md +docs/source/en/tasks_explained.md +docs/source/en/tf_xla.md +docs/source/en/tflite.md +docs/source/en/tokenizer_summary.md +docs/source/en/torchscript.md +docs/source/en/training.md +docs/source/en/troubleshooting.md +src/transformers/activations.py +src/transformers/activations_tf.py +src/transformers/agents/agent_types.py +src/transformers/agents/agents.py +src/transformers/agents/document_question_answering.py +src/transformers/agents/evaluate_agent.py +src/transformers/agents/image_question_answering.py +src/transformers/agents/prompts.py +src/transformers/agents/python_interpreter.py +src/transformers/agents/speech_to_text.py +src/transformers/agents/text_to_speech.py +src/transformers/agents/tools.py +src/transformers/agents/translation.py +src/transformers/audio_utils.py +src/transformers/commands/add_new_model_like.py +src/transformers/commands/convert.py +src/transformers/commands/download.py +src/transformers/commands/env.py +src/transformers/commands/run.py +src/transformers/commands/serving.py +src/transformers/commands/train.py +src/transformers/commands/transformers_cli.py +src/transformers/configuration_utils.py +src/transformers/convert_graph_to_onnx.py +src/transformers/convert_pytorch_checkpoint_to_tf2.py +src/transformers/convert_slow_tokenizer.py +src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py +src/transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py +src/transformers/data/data_collator.py +src/transformers/data/datasets/glue.py +src/transformers/data/datasets/language_modeling.py +src/transformers/data/datasets/squad.py +src/transformers/data/metrics/squad_metrics.py +src/transformers/data/processors/glue.py +src/transformers/data/processors/squad.py +src/transformers/data/processors/utils.py +src/transformers/data/processors/xnli.py +src/transformers/debug_utils.py +src/transformers/dependency_versions_check.py +src/transformers/dependency_versions_table.py +src/transformers/dynamic_module_utils.py +src/transformers/feature_extraction_sequence_utils.py +src/transformers/feature_extraction_utils.py +src/transformers/file_utils.py +src/transformers/hf_argparser.py +src/transformers/hyperparameter_search.py +src/transformers/image_processing_utils.py +src/transformers/image_transforms.py +src/transformers/image_utils.py +src/transformers/integrations/bitsandbytes.py +src/transformers/integrations/deepspeed.py +src/transformers/integrations/integration_utils.py +src/transformers/integrations/peft.py +src/transformers/keras_callbacks.py +src/transformers/modelcard.py +src/transformers/modeling_flax_outputs.py +src/transformers/modeling_flax_pytorch_utils.py +src/transformers/modeling_flax_utils.py +src/transformers/modeling_outputs.py +src/transformers/modeling_tf_outputs.py +src/transformers/modeling_tf_pytorch_utils.py +src/transformers/modeling_tf_utils.py +src/transformers/modeling_utils.py +src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/albert/modeling_flax_albert.py +src/transformers/models/align/configuration_align.py +src/transformers/models/align/convert_align_tf_to_hf.py +src/transformers/models/align/modeling_align.py +src/transformers/models/altclip/configuration_altclip.py +src/transformers/models/altclip/modeling_altclip.py +src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py +src/transformers/models/auto/auto_factory.py +src/transformers/models/auto/configuration_auto.py +src/transformers/models/auto/modeling_auto.py +src/transformers/models/auto/modeling_flax_auto.py +src/transformers/models/auto/modeling_tf_auto.py +src/transformers/models/autoformer/configuration_autoformer.py +src/transformers/models/autoformer/modeling_autoformer.py +src/transformers/models/bark/convert_suno_to_hf.py +src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/bart/modeling_flax_bart.py +src/transformers/models/bart/modeling_tf_bart.py +src/transformers/models/beit/convert_beit_unilm_to_pytorch.py +src/transformers/models/beit/modeling_flax_beit.py +src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py +src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/modeling_flax_bert.py +src/transformers/models/bert_generation/modeling_bert_generation.py +src/transformers/models/big_bird/convert_bigbird_original_tf_checkpoint_to_pytorch.py +src/transformers/models/big_bird/modeling_flax_big_bird.py +src/transformers/models/bigbird_pegasus/convert_bigbird_pegasus_tf_to_pytorch.py +src/transformers/models/biogpt/configuration_biogpt.py +src/transformers/models/biogpt/convert_biogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/biogpt/modeling_biogpt.py +src/transformers/models/bit/configuration_bit.py +src/transformers/models/bit/convert_bit_to_pytorch.py +src/transformers/models/bit/modeling_bit.py +src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/blenderbot/modeling_flax_blenderbot.py +src/transformers/models/blenderbot/modeling_tf_blenderbot.py +src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +src/transformers/models/blip/configuration_blip.py +src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py +src/transformers/models/blip/modeling_blip_text.py +src/transformers/models/blip/modeling_tf_blip_text.py +src/transformers/models/blip_2/configuration_blip_2.py +src/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py +src/transformers/models/bloom/modeling_bloom.py +src/transformers/models/bloom/modeling_flax_bloom.py +src/transformers/models/bridgetower/configuration_bridgetower.py +src/transformers/models/bridgetower/modeling_bridgetower.py +src/transformers/models/bros/convert_bros_to_pytorch.py +src/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/camembert/modeling_camembert.py +src/transformers/models/camembert/modeling_tf_camembert.py +src/transformers/models/canine/convert_canine_original_tf_checkpoint_to_pytorch.py +src/transformers/models/chinese_clip/configuration_chinese_clip.py +src/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py +src/transformers/models/chinese_clip/modeling_chinese_clip.py +src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py +src/transformers/models/clip/convert_clip_original_pytorch_to_hf.py +src/transformers/models/clip/modeling_clip.py +src/transformers/models/clip/modeling_flax_clip.py +src/transformers/models/clip/modeling_tf_clip.py +src/transformers/models/clipseg/configuration_clipseg.py +src/transformers/models/clipseg/convert_clipseg_original_pytorch_to_hf.py +src/transformers/models/codegen/modeling_codegen.py +src/transformers/models/conditional_detr/convert_conditional_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py +src/transformers/models/convbert/modeling_convbert.py +src/transformers/models/convbert/modeling_tf_convbert.py +src/transformers/models/convnext/convert_convnext_to_pytorch.py +src/transformers/models/convnext/modeling_tf_convnext.py +src/transformers/models/convnextv2/configuration_convnextv2.py +src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py +src/transformers/models/convnextv2/modeling_convnextv2.py +src/transformers/models/cpmant/configuration_cpmant.py +src/transformers/models/cpmant/modeling_cpmant.py +src/transformers/models/cpmant/tokenization_cpmant.py +src/transformers/models/ctrl/modeling_tf_ctrl.py +src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/cvt/modeling_tf_cvt.py +src/transformers/models/data2vec/convert_data2vec_audio_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_text_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_vision_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/modeling_data2vec_text.py +src/transformers/models/data2vec/modeling_tf_data2vec_vision.py +src/transformers/models/deberta/modeling_tf_deberta.py +src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py +src/transformers/models/decision_transformer/modeling_decision_transformer.py +src/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py +src/transformers/models/deformable_detr/load_custom.py +src/transformers/models/deit/convert_deit_timm_to_pytorch.py +src/transformers/models/deprecated/bort/convert_bort_original_gluonnlp_checkpoint_to_pytorch.py +src/transformers/models/deprecated/mctct/configuration_mctct.py +src/transformers/models/deprecated/mctct/feature_extraction_mctct.py +src/transformers/models/deprecated/mctct/modeling_mctct.py +src/transformers/models/deprecated/mctct/processing_mctct.py +src/transformers/models/deprecated/mmbt/configuration_mmbt.py +src/transformers/models/deprecated/mmbt/modeling_mmbt.py +src/transformers/models/deprecated/open_llama/configuration_open_llama.py +src/transformers/models/deprecated/open_llama/modeling_open_llama.py +src/transformers/models/deprecated/retribert/configuration_retribert.py +src/transformers/models/deprecated/retribert/modeling_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py +src/transformers/models/deprecated/tapex/tokenization_tapex.py +src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py +src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py +src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py +src/transformers/models/deprecated/van/configuration_van.py +src/transformers/models/deprecated/van/convert_van_to_pytorch.py +src/transformers/models/deprecated/van/modeling_van.py +src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/detr/convert_detr_to_pytorch.py +src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/dinov2/configuration_dinov2.py +src/transformers/models/dinov2/convert_dinov2_to_hf.py +src/transformers/models/dinov2/modeling_dinov2.py +src/transformers/models/distilbert/modeling_distilbert.py +src/transformers/models/distilbert/modeling_flax_distilbert.py +src/transformers/models/distilbert/modeling_tf_distilbert.py +src/transformers/models/dit/convert_dit_unilm_to_pytorch.py +src/transformers/models/donut/configuration_donut_swin.py +src/transformers/models/donut/convert_donut_to_pytorch.py +src/transformers/models/donut/modeling_donut_swin.py +src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py +src/transformers/models/dpr/modeling_dpr.py +src/transformers/models/dpr/modeling_tf_dpr.py +src/transformers/models/dpt/configuration_dpt.py +src/transformers/models/dpt/convert_dpt_hybrid_to_pytorch.py +src/transformers/models/dpt/convert_dpt_to_pytorch.py +src/transformers/models/efficientnet/configuration_efficientnet.py +src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py +src/transformers/models/efficientnet/modeling_efficientnet.py +src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py +src/transformers/models/electra/modeling_flax_electra.py +src/transformers/models/encodec/configuration_encodec.py +src/transformers/models/encodec/convert_encodec_checkpoint_to_pytorch.py +src/transformers/models/encoder_decoder/modeling_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py +src/transformers/models/ernie/modeling_ernie.py +src/transformers/models/esm/configuration_esm.py +src/transformers/models/esm/convert_esm.py +src/transformers/models/esm/modeling_esm.py +src/transformers/models/esm/modeling_esmfold.py +src/transformers/models/esm/modeling_tf_esm.py +src/transformers/models/esm/openfold_utils/chunk_utils.py +src/transformers/models/esm/openfold_utils/data_transforms.py +src/transformers/models/esm/openfold_utils/feats.py +src/transformers/models/esm/openfold_utils/loss.py +src/transformers/models/esm/openfold_utils/protein.py +src/transformers/models/esm/openfold_utils/residue_constants.py +src/transformers/models/esm/openfold_utils/rigid_utils.py +src/transformers/models/esm/openfold_utils/tensor_utils.py +src/transformers/models/falcon/configuration_falcon.py +src/transformers/models/falcon/modeling_falcon.py +src/transformers/models/flaubert/configuration_flaubert.py +src/transformers/models/flaubert/modeling_flaubert.py +src/transformers/models/flaubert/modeling_tf_flaubert.py +src/transformers/models/flava/convert_dalle_to_flava_codebook.py +src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py +src/transformers/models/flava/modeling_flava.py +src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +src/transformers/models/fnet/modeling_fnet.py +src/transformers/models/focalnet/configuration_focalnet.py +src/transformers/models/focalnet/convert_focalnet_to_hf_format.py +src/transformers/models/focalnet/modeling_focalnet.py +src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/fsmt/modeling_fsmt.py +src/transformers/models/funnel/configuration_funnel.py +src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py +src/transformers/models/funnel/modeling_funnel.py +src/transformers/models/funnel/modeling_tf_funnel.py +src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py +src/transformers/models/gemma/configuration_gemma.py +src/transformers/models/gemma/convert_gemma_weights_to_hf.py +src/transformers/models/gemma/modeling_flax_gemma.py +src/transformers/models/gemma/modeling_gemma.py +src/transformers/models/git/configuration_git.py +src/transformers/models/git/convert_git_to_pytorch.py +src/transformers/models/glpn/configuration_glpn.py +src/transformers/models/glpn/convert_glpn_to_pytorch.py +src/transformers/models/gpt2/CONVERSION.md +src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py +src/transformers/models/gpt2/modeling_flax_gpt2.py +src/transformers/models/gpt2/modeling_tf_gpt2.py +src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py +src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py +src/transformers/models/gpt_neo/convert_gpt_neo_mesh_tf_to_pytorch.py +src/transformers/models/gpt_neo/modeling_flax_gpt_neo.py +src/transformers/models/gpt_neo/modeling_gpt_neo.py +src/transformers/models/gpt_neox/modeling_gpt_neox.py +src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +src/transformers/models/gpt_sw3/convert_megatron_to_pytorch.py +src/transformers/models/gptj/configuration_gptj.py +src/transformers/models/gptj/modeling_flax_gptj.py +src/transformers/models/gptj/modeling_tf_gptj.py +src/transformers/models/groupvit/configuration_groupvit.py +src/transformers/models/groupvit/convert_groupvit_nvlab_to_hf.py +src/transformers/models/hubert/configuration_hubert.py +src/transformers/models/hubert/convert_distilhubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/modeling_tf_hubert.py +src/transformers/models/ibert/configuration_ibert.py +src/transformers/models/ibert/modeling_ibert.py +src/transformers/models/ibert/quant_modules.py +src/transformers/models/idefics/configuration_idefics.py +src/transformers/models/idefics/image_processing_idefics.py +src/transformers/models/idefics/modeling_idefics.py +src/transformers/models/idefics/perceiver.py +src/transformers/models/idefics/processing_idefics.py +src/transformers/models/idefics/vision.py +src/transformers/models/imagegpt/convert_imagegpt_original_tf2_to_pytorch.py +src/transformers/models/informer/configuration_informer.py +src/transformers/models/informer/modeling_informer.py +src/transformers/models/instructblip/configuration_instructblip.py +src/transformers/models/instructblip/convert_instructblip_original_to_pytorch.py +src/transformers/models/instructblip/modeling_instructblip.py +src/transformers/models/instructblip/processing_instructblip.py +src/transformers/models/jamba/configuration_jamba.py +src/transformers/models/jamba/modeling_jamba.py +src/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/led/configuration_led.py +src/transformers/models/led/modeling_led.py +src/transformers/models/led/modeling_tf_led.py +src/transformers/models/levit/convert_levit_timm_to_pytorch.py +src/transformers/models/levit/modeling_levit.py +src/transformers/models/lilt/configuration_lilt.py +src/transformers/models/llama/configuration_llama.py +src/transformers/models/llama/convert_llama_weights_to_hf.py +src/transformers/models/llama/modeling_llama.py +src/transformers/models/llava/configuration_llava.py +src/transformers/models/llava/modeling_llava.py +src/transformers/models/llava_next/configuration_llava_next.py +src/transformers/models/llava_next/modeling_llava_next.py +src/transformers/models/longformer/configuration_longformer.py +src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py +src/transformers/models/longt5/configuration_longt5.py +src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py +src/transformers/models/longt5/modeling_flax_longt5.py +src/transformers/models/luke/configuration_luke.py +src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/luke/modeling_luke.py +src/transformers/models/lxmert/configuration_lxmert.py +src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/lxmert/modeling_lxmert.py +src/transformers/models/lxmert/modeling_tf_lxmert.py +src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py +src/transformers/models/m2m_100/modeling_m2m_100.py +src/transformers/models/marian/configuration_marian.py +src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py +src/transformers/models/marian/convert_marian_to_pytorch.py +src/transformers/models/marian/modeling_flax_marian.py +src/transformers/models/marian/modeling_tf_marian.py +src/transformers/models/markuplm/configuration_markuplm.py +src/transformers/models/markuplm/feature_extraction_markuplm.py +src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/configuration_maskformer_swin.py +src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_resnet_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_swin_to_pytorch.py +src/transformers/models/maskformer/modeling_maskformer_swin.py +src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py +src/transformers/models/mbart/modeling_flax_mbart.py +src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py +src/transformers/models/megatron_bert/modeling_megatron_bert.py +src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py +src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py +src/transformers/models/mgp_str/configuration_mgp_str.py +src/transformers/models/mgp_str/modeling_mgp_str.py +src/transformers/models/mistral/configuration_mistral.py +src/transformers/models/mistral/modeling_mistral.py +src/transformers/models/mixtral/configuration_mixtral.py +src/transformers/models/mixtral/modeling_mixtral.py +src/transformers/models/mluke/convert_mluke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v1/configuration_mobilenet_v1.py +src/transformers/models/mobilenet_v1/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py +src/transformers/models/mobilenet_v2/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilevit/configuration_mobilevit.py +src/transformers/models/mobilevit/convert_mlcvnets_to_pytorch.py +src/transformers/models/mobilevitv2/convert_mlcvnets_to_pytorch.py +src/transformers/models/mpnet/configuration_mpnet.py +src/transformers/models/mpnet/modeling_mpnet.py +src/transformers/models/mpnet/modeling_tf_mpnet.py +src/transformers/models/mpt/configuration_mpt.py +src/transformers/models/mpt/modeling_mpt.py +src/transformers/models/mra/configuration_mra.py +src/transformers/models/mra/convert_mra_pytorch_to_pytorch.py +src/transformers/models/mra/modeling_mra.py +src/transformers/models/mt5/configuration_mt5.py +src/transformers/models/mt5/modeling_flax_mt5.py +src/transformers/models/mt5/modeling_mt5.py +src/transformers/models/mt5/modeling_tf_mt5.py +src/transformers/models/musicgen/convert_musicgen_transformers.py +src/transformers/models/musicgen_melody/convert_musicgen_melody_transformers.py +src/transformers/models/mvp/modeling_mvp.py +src/transformers/models/nllb_moe/configuration_nllb_moe.py +src/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py +src/transformers/models/nllb_moe/modeling_nllb_moe.py +src/transformers/models/nougat/convert_nougat_to_hf.py +src/transformers/models/nystromformer/configuration_nystromformer.py +src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/nystromformer/modeling_nystromformer.py +src/transformers/models/oneformer/convert_to_hf_oneformer.py +src/transformers/models/openai/convert_openai_original_tf_checkpoint_to_pytorch.py +src/transformers/models/openai/modeling_openai.py +src/transformers/models/openai/modeling_tf_openai.py +src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/opt/modeling_flax_opt.py +src/transformers/models/owlvit/configuration_owlvit.py +src/transformers/models/owlvit/convert_owlvit_original_flax_to_hf.py +src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py +src/transformers/models/pegasus/modeling_flax_pegasus.py +src/transformers/models/pegasus/modeling_tf_pegasus.py +src/transformers/models/pegasus_x/modeling_pegasus_x.py +src/transformers/models/perceiver/configuration_perceiver.py +src/transformers/models/perceiver/convert_perceiver_haiku_to_pytorch.py +src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py +src/transformers/models/persimmon/modeling_persimmon.py +src/transformers/models/pix2struct/configuration_pix2struct.py +src/transformers/models/pix2struct/convert_pix2struct_original_pytorch_to_hf.py +src/transformers/models/pix2struct/image_processing_pix2struct.py +src/transformers/models/pix2struct/processing_pix2struct.py +src/transformers/models/plbart/convert_plbart_original_checkpoint_to_torch.py +src/transformers/models/poolformer/convert_poolformer_original_to_pytorch.py +src/transformers/models/pop2piano/convert_pop2piano_weights_to_hf.py +src/transformers/models/pop2piano/feature_extraction_pop2piano.py +src/transformers/models/pop2piano/processing_pop2piano.py +src/transformers/models/pop2piano/tokenization_pop2piano.py +src/transformers/models/prophetnet/configuration_prophetnet.py +src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/prophetnet/modeling_prophetnet.py +src/transformers/models/pvt/configuration_pvt.py +src/transformers/models/pvt/convert_pvt_to_pytorch.py +src/transformers/models/pvt/image_processing_pvt.py +src/transformers/models/pvt/modeling_pvt.py +src/transformers/models/qwen2/configuration_qwen2.py +src/transformers/models/qwen2/modeling_qwen2.py +src/transformers/models/qwen2/tokenization_qwen2.py +src/transformers/models/qwen2/tokenization_qwen2_fast.py +src/transformers/models/qwen2_moe/configuration_qwen2_moe.py +src/transformers/models/qwen2_moe/modeling_qwen2_moe.py +src/transformers/models/rag/configuration_rag.py +src/transformers/models/rag/modeling_rag.py +src/transformers/models/rag/modeling_tf_rag.py +src/transformers/models/rag/retrieval_rag.py +src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py +src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py +src/transformers/models/regnet/configuration_regnet.py +src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py +src/transformers/models/regnet/convert_regnet_to_pytorch.py +src/transformers/models/regnet/modeling_flax_regnet.py +src/transformers/models/rembert/configuration_rembert.py +src/transformers/models/rembert/convert_rembert_tf_checkpoint_to_pytorch.py +src/transformers/models/rembert/modeling_rembert.py +src/transformers/models/rembert/modeling_tf_rembert.py +src/transformers/models/resnet/convert_resnet_to_pytorch.py +src/transformers/models/resnet/modeling_flax_resnet.py +src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta/modeling_flax_roberta.py +src/transformers/models/roberta_prelayernorm/convert_roberta_prelayernorm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py +src/transformers/models/roc_bert/configuration_roc_bert.py +src/transformers/models/roformer/convert_roformer_original_tf_checkpoint_to_pytorch.py +src/transformers/models/roformer/modeling_flax_roformer.py +src/transformers/models/roformer/modeling_roformer.py +src/transformers/models/roformer/modeling_tf_roformer.py +src/transformers/models/rwkv/configuration_rwkv.py +src/transformers/models/rwkv/convert_rwkv_checkpoint_to_hf.py +src/transformers/models/rwkv/modeling_rwkv.py +src/transformers/models/sam/configuration_sam.py +src/transformers/models/sam/convert_sam_to_hf.py +src/transformers/models/sam/image_processing_sam.py +src/transformers/models/sam/modeling_sam.py +src/transformers/models/sam/modeling_tf_sam.py +src/transformers/models/sam/processing_sam.py +src/transformers/models/seamless_m4t/convert_fairseq2_to_hf.py +src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py +src/transformers/models/segformer/configuration_segformer.py +src/transformers/models/segformer/convert_segformer_original_to_pytorch.py +src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py +src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py +src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py +src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py +src/transformers/models/speecht5/configuration_speecht5.py +src/transformers/models/speecht5/convert_hifigan.py +src/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speecht5/number_normalizer.py +src/transformers/models/splinter/configuration_splinter.py +src/transformers/models/splinter/modeling_splinter.py +src/transformers/models/squeezebert/modeling_squeezebert.py +src/transformers/models/stablelm/modeling_stablelm.py +src/transformers/models/starcoder2/modeling_starcoder2.py +src/transformers/models/swiftformer/configuration_swiftformer.py +src/transformers/models/swiftformer/convert_swiftformer_original_to_hf.py +src/transformers/models/swiftformer/modeling_swiftformer.py +src/transformers/models/swin/convert_swin_simmim_to_pytorch.py +src/transformers/models/swin/convert_swin_timm_to_pytorch.py +src/transformers/models/swin/modeling_tf_swin.py +src/transformers/models/swin2sr/configuration_swin2sr.py +src/transformers/models/swin2sr/convert_swin2sr_original_to_pytorch.py +src/transformers/models/swinv2/convert_swinv2_timm_to_pytorch.py +src/transformers/models/swinv2/modeling_swinv2.py +src/transformers/models/switch_transformers/configuration_switch_transformers.py +src/transformers/models/switch_transformers/convert_big_switch.py +src/transformers/models/switch_transformers/convert_switch_transformers_original_flax_checkpoint_to_pytorch.py +src/transformers/models/switch_transformers/modeling_switch_transformers.py +src/transformers/models/t5/configuration_t5.py +src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py +src/transformers/models/t5/convert_t5x_checkpoint_to_pytorch.py +src/transformers/models/t5/modeling_flax_t5.py +src/transformers/models/t5/modeling_t5.py +src/transformers/models/t5/modeling_tf_t5.py +src/transformers/models/table_transformer/configuration_table_transformer.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf_no_timm.py +src/transformers/models/tapas/configuration_tapas.py +src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py +src/transformers/models/tapas/modeling_tapas.py +src/transformers/models/tapas/modeling_tf_tapas.py +src/transformers/models/timesformer/convert_timesformer_to_pytorch.py +src/transformers/models/timm_backbone/configuration_timm_backbone.py +src/transformers/models/timm_backbone/modeling_timm_backbone.py +src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py +src/transformers/models/umt5/configuration_umt5.py +src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py +src/transformers/models/umt5/modeling_umt5.py +src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/upernet/configuration_upernet.py +src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py +src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py +src/transformers/models/videomae/configuration_videomae.py +src/transformers/models/videomae/convert_videomae_to_pytorch.py +src/transformers/models/vilt/configuration_vilt.py +src/transformers/models/vilt/convert_vilt_original_to_pytorch.py +src/transformers/models/vipllava/configuration_vipllava.py +src/transformers/models/vipllava/modeling_vipllava.py +src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py +src/transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py +src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py +src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py +src/transformers/models/visual_bert/convert_visual_bert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/visual_bert/modeling_visual_bert.py +src/transformers/models/vit/convert_dino_to_pytorch.py +src/transformers/models/vit/convert_vit_timm_to_pytorch.py +src/transformers/models/vit/modeling_flax_vit.py +src/transformers/models/vit_mae/convert_vit_mae_to_pytorch.py +src/transformers/models/vit_mae/modeling_tf_vit_mae.py +src/transformers/models/vit_msn/configuration_vit_msn.py +src/transformers/models/vit_msn/convert_msn_to_pytorch.py +src/transformers/models/vivit/configuration_vivit.py +src/transformers/models/vivit/convert_vivit_flax_to_pytorch.py +src/transformers/models/vivit/image_processing_vivit.py +src/transformers/models/vivit/modeling_vivit.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py +src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py +src/transformers/models/wav2vec2_bert/convert_wav2vec2_seamless_checkpoint.py +src/transformers/models/wav2vec2_conformer/convert_wav2vec2_conformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/whisper/convert_openai_to_hf.py +src/transformers/models/whisper/english_normalizer.py +src/transformers/models/whisper/modeling_flax_whisper.py +src/transformers/models/x_clip/configuration_x_clip.py +src/transformers/models/x_clip/convert_x_clip_original_pytorch_to_hf.py +src/transformers/models/xglm/configuration_xglm.py +src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py +src/transformers/models/xglm/modeling_flax_xglm.py +src/transformers/models/xglm/modeling_tf_xglm.py +src/transformers/models/xglm/modeling_xglm.py +src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm/modeling_tf_xlm.py +src/transformers/models/xlm/modeling_xlm.py +src/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_xlm_roberta.py +src/transformers/models/xlm_roberta_xl/convert_xlm_roberta_xl_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py +src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py +src/transformers/models/xlnet/modeling_tf_xlnet.py +src/transformers/models/xlnet/modeling_xlnet.py +src/transformers/models/xmod/convert_xmod_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/yolos/convert_yolos_to_pytorch.py +src/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py +src/transformers/models/yoso/modeling_yoso.py +src/transformers/models/zamba/configuration_zamba.py +src/transformers/models/zamba/modeling_zamba.py +src/transformers/onnx/__main__.py +src/transformers/onnx/config.py +src/transformers/onnx/convert.py +src/transformers/onnx/features.py +src/transformers/onnx/utils.py +src/transformers/optimization.py +src/transformers/optimization_tf.py +src/transformers/pipelines/audio_classification.py +src/transformers/pipelines/audio_utils.py +src/transformers/pipelines/automatic_speech_recognition.py +src/transformers/pipelines/base.py +src/transformers/pipelines/depth_estimation.py +src/transformers/pipelines/document_question_answering.py +src/transformers/pipelines/feature_extraction.py +src/transformers/pipelines/fill_mask.py +src/transformers/pipelines/image_classification.py +src/transformers/pipelines/image_segmentation.py +src/transformers/pipelines/image_to_text.py +src/transformers/pipelines/mask_generation.py +src/transformers/pipelines/object_detection.py +src/transformers/pipelines/pt_utils.py +src/transformers/pipelines/question_answering.py +src/transformers/pipelines/table_question_answering.py +src/transformers/pipelines/text_classification.py +src/transformers/pipelines/token_classification.py +src/transformers/pipelines/video_classification.py +src/transformers/pipelines/visual_question_answering.py +src/transformers/pipelines/zero_shot_audio_classification.py +src/transformers/pipelines/zero_shot_classification.py +src/transformers/pipelines/zero_shot_image_classification.py +src/transformers/pipelines/zero_shot_object_detection.py +src/transformers/processing_utils.py +src/transformers/pytorch_utils.py +src/transformers/quantizers/auto.py +src/transformers/quantizers/base.py +src/transformers/quantizers/quantizer_awq.py +src/transformers/quantizers/quantizer_bnb_4bit.py +src/transformers/quantizers/quantizer_bnb_8bit.py +src/transformers/quantizers/quantizer_gptq.py +src/transformers/quantizers/quantizers_utils.py +src/transformers/sagemaker/trainer_sm.py +src/transformers/sagemaker/training_args_sm.py +src/transformers/testing_utils.py +src/transformers/tf_utils.py +src/transformers/time_series_utils.py +src/transformers/tokenization_utils.py +src/transformers/tokenization_utils_base.py +src/transformers/tokenization_utils_fast.py +src/transformers/trainer.py +src/transformers/trainer_callback.py +src/transformers/trainer_pt_utils.py +src/transformers/trainer_seq2seq.py +src/transformers/trainer_utils.py +src/transformers/training_args.py +src/transformers/training_args_seq2seq.py +src/transformers/training_args_tf.py +src/transformers/utils/backbone_utils.py +src/transformers/utils/bitsandbytes.py +src/transformers/utils/constants.py +src/transformers/utils/doc.py +src/transformers/utils/dummy_detectron2_objects.py +src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py +src/transformers/utils/dummy_flax_objects.py +src/transformers/utils/dummy_keras_nlp_objects.py +src/transformers/utils/dummy_music_objects.py +src/transformers/utils/dummy_pt_objects.py +src/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py +src/transformers/utils/dummy_sentencepiece_objects.py +src/transformers/utils/dummy_speech_objects.py +src/transformers/utils/dummy_tensorflow_text_objects.py +src/transformers/utils/dummy_tf_objects.py +src/transformers/utils/dummy_tokenizers_objects.py +src/transformers/utils/dummy_vision_objects.py +src/transformers/utils/fx.py +src/transformers/utils/generic.py +src/transformers/utils/hp_naming.py +src/transformers/utils/hub.py +src/transformers/utils/import_utils.py +src/transformers/utils/logging.py +src/transformers/utils/model_parallel_utils.py +src/transformers/utils/notebook.py +src/transformers/utils/peft_utils.py +src/transformers/utils/quantization_config.py +src/transformers/utils/sentencepiece_model_pb2.py +src/transformers/utils/sentencepiece_model_pb2_new.py +src/transformers/utils/versions.py diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service.py b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service.py new file mode 100644 index 0000000000000000000000000000000000000000..f3bcfcd4f266db684b2209a4e64bdca61cfb69de --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service.py @@ -0,0 +1,1285 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import ast +import collections +import datetime +import functools +import json +import operator +import os +import re +import sys +import time +from typing import Dict, List, Optional, Union + +import requests +from get_ci_error_statistics import get_jobs +from get_previous_daily_ci import get_last_daily_ci_reports +from huggingface_hub import HfApi +from slack_sdk import WebClient + + +api = HfApi() +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + +NON_MODEL_TEST_MODULES = [ + "deepspeed", + "extended", + "fixtures", + "generation", + "onnx", + "optimization", + "pipelines", + "sagemaker", + "trainer", + "utils", +] + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + + return failed, success, time_spent + + +def handle_stacktraces(test_results): + # These files should follow the following architecture: + # === FAILURES === + # :: Error ... + # :: Error ... + # + + total_stacktraces = test_results.split("\n")[1:-1] + stacktraces = [] + for stacktrace in total_stacktraces: + try: + line = stacktrace[: stacktrace.index(" ")].split(":")[-2] + error_message = stacktrace[stacktrace.index(" ") :] + + stacktraces.append(f"(line {line}) {error_message}") + except Exception: + stacktraces.append("Cannot retrieve error message.") + + return stacktraces + + +def dicts_to_sum(objects: Union[Dict[str, Dict], List[dict]]): + if isinstance(objects, dict): + lists = objects.values() + else: + lists = objects + + # Convert each dictionary to counter + counters = map(collections.Counter, lists) + # Sum all the counters + return functools.reduce(operator.add, counters) + + +class Message: + def __init__( + self, + title: str, + ci_title: str, + model_results: Dict, + additional_results: Dict, + selected_warnings: List = None, + prev_ci_artifacts=None, + ): + self.title = title + self.ci_title = ci_title + + # Failures and success of the modeling tests + self.n_model_success = sum(r["success"] for r in model_results.values()) + self.n_model_single_gpu_failures = sum(dicts_to_sum(r["failed"])["single"] for r in model_results.values()) + self.n_model_multi_gpu_failures = sum(dicts_to_sum(r["failed"])["multi"] for r in model_results.values()) + + # Some suites do not have a distinction between single and multi GPU. + self.n_model_unknown_failures = sum(dicts_to_sum(r["failed"])["unclassified"] for r in model_results.values()) + self.n_model_failures = ( + self.n_model_single_gpu_failures + self.n_model_multi_gpu_failures + self.n_model_unknown_failures + ) + + # Failures and success of the additional tests + self.n_additional_success = sum(r["success"] for r in additional_results.values()) + + if len(additional_results) > 0: + # `dicts_to_sum` uses `dicts_to_sum` which requires a non empty dictionary. Let's just add an empty entry. + all_additional_failures = dicts_to_sum([r["failed"] for r in additional_results.values()]) + self.n_additional_single_gpu_failures = all_additional_failures["single"] + self.n_additional_multi_gpu_failures = all_additional_failures["multi"] + self.n_additional_unknown_gpu_failures = all_additional_failures["unclassified"] + else: + self.n_additional_single_gpu_failures = 0 + self.n_additional_multi_gpu_failures = 0 + self.n_additional_unknown_gpu_failures = 0 + + self.n_additional_failures = ( + self.n_additional_single_gpu_failures + + self.n_additional_multi_gpu_failures + + self.n_additional_unknown_gpu_failures + ) + + # Results + self.n_failures = self.n_model_failures + self.n_additional_failures + self.n_success = self.n_model_success + self.n_additional_success + self.n_tests = self.n_failures + self.n_success + + self.model_results = model_results + self.additional_results = additional_results + + self.thread_ts = None + + if selected_warnings is None: + selected_warnings = [] + self.selected_warnings = selected_warnings + + self.prev_ci_artifacts = prev_ci_artifacts + + @property + def time(self) -> str: + all_results = [*self.model_results.values(), *self.additional_results.values()] + time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])] + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> Dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def ci_title_section(self) -> Dict: + return {"type": "section", "text": {"type": "mrkdwn", "text": self.ci_title}} + + @property + def no_failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n" + f"Number of model failures: {self.n_model_failures}.\n" + f"The suite ran in {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def warnings(self) -> Dict: + # If something goes wrong, let's avoid the CI report failing to be sent. + button_text = "Check warnings (Link not found)" + # Use the workflow run link + job_link = f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}" + + for job in github_actions_jobs: + if "Extract warnings in CI artifacts" in job["name"] and job["conclusion"] == "success": + button_text = "Check warnings" + # Use the actual job link + job_link = job["html_url"] + break + + huggingface_hub_warnings = [x for x in self.selected_warnings if "huggingface_hub" in x] + text = f"There are {len(self.selected_warnings)} warnings being selected." + text += f"\n{len(huggingface_hub_warnings)} of them are from `huggingface_hub`." + + return { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": button_text, "emoji": True}, + "url": job_link, + }, + } + + @staticmethod + def get_device_report(report, rjust=6): + if "single" in report and "multi" in report: + return f"{str(report['single']).rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + elif "single" in report: + return f"{str(report['single']).rjust(rjust)} | {'0'.rjust(rjust)} | " + elif "multi" in report: + return f"{'0'.rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + + @property + def category_failures(self) -> Dict: + model_failures = [v["failed"] for v in self.model_results.values()] + + category_failures = {} + + for model_failure in model_failures: + for key, value in model_failure.items(): + if key not in category_failures: + category_failures[key] = dict(value) + else: + category_failures[key]["unclassified"] += value["unclassified"] + category_failures[key]["single"] += value["single"] + category_failures[key]["multi"] += value["multi"] + + individual_reports = [] + for key, value in category_failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + individual_reports.append(f"{device_report}{key}") + else: + individual_reports.append(key) + + header = "Single | Multi | Category\n" + category_failures_report = prepare_reports( + title="The following modeling categories had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": category_failures_report}} + + def compute_diff_for_failure_reports(self, curr_failure_report, prev_failure_report): # noqa + # Remove the leading and training parts that don't contain failure count information. + model_failures = curr_failure_report.split("\n")[3:-2] + prev_model_failures = prev_failure_report.split("\n")[3:-2] + entries_changed = set(model_failures).difference(prev_model_failures) + + prev_map = {} + for f in prev_model_failures: + items = [x.strip() for x in f.split("| ")] + prev_map[items[-1]] = [int(x) for x in items[:-1]] + + curr_map = {} + for f in entries_changed: + items = [x.strip() for x in f.split("| ")] + curr_map[items[-1]] = [int(x) for x in items[:-1]] + + diff_map = {} + for k, v in curr_map.items(): + if k not in prev_map: + diff_map[k] = v + else: + diff = [x - y for x, y in zip(v, prev_map[k])] + if max(diff) > 0: + diff_map[k] = diff + + entries_changed = [] + for model_name, diff_values in diff_map.items(): + diff = [str(x) for x in diff_values] + diff = [f"+{x}" if (x != "0" and not x.startswith("-")) else x for x in diff] + diff = [x.rjust(9) for x in diff] + device_report = " | ".join(diff) + " | " + report = f"{device_report}{model_name}" + entries_changed.append(report) + entries_changed = sorted(entries_changed, key=lambda s: s.split("| ")[-1]) + + return entries_changed + + @property + def model_failures(self) -> List[Dict]: + # Obtain per-model failures + def per_model_sum(model_category_dict): + return dicts_to_sum(model_category_dict["failed"].values()) + + failures = {} + non_model_failures = { + k: per_model_sum(v) for k, v in self.model_results.items() if sum(per_model_sum(v).values()) + } + + for k, v in self.model_results.items(): + if k in NON_MODEL_TEST_MODULES: + pass + + if sum(per_model_sum(v).values()): + dict_failed = dict(v["failed"]) + pytorch_specific_failures = dict_failed.pop("PyTorch") + tensorflow_specific_failures = dict_failed.pop("TensorFlow") + other_failures = dicts_to_sum(dict_failed.values()) + + failures[k] = { + "PyTorch": pytorch_specific_failures, + "TensorFlow": tensorflow_specific_failures, + "other": other_failures, + } + + model_reports = [] + other_module_reports = [] + + for key, value in non_model_failures.items(): + if key in NON_MODEL_TEST_MODULES: + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + report = f"{device_report}{key}" + else: + report = key + + other_module_reports.append(report) + + for key, value in failures.items(): + device_report_values = [ + value["PyTorch"]["single"], + value["PyTorch"]["multi"], + value["TensorFlow"]["single"], + value["TensorFlow"]["multi"], + sum(value["other"].values()), + ] + + if sum(device_report_values): + device_report = " | ".join([str(x).rjust(9) for x in device_report_values]) + " | " + report = f"{device_report}{key}" + + model_reports.append(report) + + # (Possibly truncated) reports for the current workflow run - to be sent to Slack channels + model_header = "Single PT | Multi PT | Single TF | Multi TF | Other | Category\n" + sorted_model_reports = sorted(model_reports, key=lambda s: s.split("| ")[-1]) + model_failures_report = prepare_reports( + title="These following model modules had failures", header=model_header, reports=sorted_model_reports + ) + + module_header = "Single | Multi | Category\n" + sorted_module_reports = sorted(other_module_reports, key=lambda s: s.split("| ")[-1]) + module_failures_report = prepare_reports( + title="The following non-model modules had failures", header=module_header, reports=sorted_module_reports + ) + + # To be sent to Slack channels + model_failure_sections = [ + {"type": "section", "text": {"type": "mrkdwn", "text": model_failures_report}}, + {"type": "section", "text": {"type": "mrkdwn", "text": module_failures_report}}, + ] + + # Save the complete (i.e. no truncation) failure tables (of the current workflow run) + # (to be uploaded as artifacts) + + model_failures_report = prepare_reports( + title="These following model modules had failures", + header=model_header, + reports=sorted_model_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(model_failures_report) + + module_failures_report = prepare_reports( + title="The following non-model modules had failures", + header=module_header, + reports=sorted_module_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/module_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(module_failures_report) + + if self.prev_ci_artifacts is not None: + # if the last run produces artifact named `ci_results_{job_name}` + if ( + f"ci_results_{job_name}" in self.prev_ci_artifacts + and "model_failures_report.txt" in self.prev_ci_artifacts[f"ci_results_{job_name}"] + ): + # Compute the difference of the previous/current (model failure) table + prev_model_failures = self.prev_ci_artifacts[f"ci_results_{job_name}"]["model_failures_report.txt"] + entries_changed = self.compute_diff_for_failure_reports(model_failures_report, prev_model_failures) + if len(entries_changed) > 0: + # Save the complete difference + diff_report = prepare_reports( + title="Changed model modules failures", + header=model_header, + reports=entries_changed, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/changed_model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(diff_report) + + # To be sent to Slack channels + diff_report = prepare_reports( + title="*Changed model modules failures*", + header=model_header, + reports=entries_changed, + ) + model_failure_sections.append( + {"type": "section", "text": {"type": "mrkdwn", "text": diff_report}}, + ) + + return model_failure_sections + + @property + def additional_failures(self) -> Dict: + failures = {k: v["failed"] for k, v in self.additional_results.items()} + errors = {k: v["error"] for k, v in self.additional_results.items()} + + individual_reports = [] + for key, value in failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()) or errors[key]: + report = f"{key}" + if errors[key]: + report = f"[Errored out] {report}" + if device_report: + report = f"{device_report}{report}" + + individual_reports.append(report) + + header = "Single | Multi | Category\n" + failures_report = prepare_reports( + title="The following non-modeling tests had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}} + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.ci_title: + blocks.append(self.ci_title_section) + + if self.n_model_failures > 0 or self.n_additional_failures > 0: + blocks.append(self.failures) + + if self.n_model_failures > 0: + blocks.append(self.category_failures) + for block in self.model_failures: + if block["text"]["text"]: + blocks.append(block) + + if self.n_additional_failures > 0: + blocks.append(self.additional_failures) + + if self.n_model_failures == 0 and self.n_additional_failures == 0: + blocks.append(self.no_failures) + + if len(self.selected_warnings) > 0: + blocks.append(self.warnings) + + new_failure_blocks = self.get_new_model_failure_blocks(with_header=False) + if len(new_failure_blocks) > 0: + blocks.extend(new_failure_blocks) + + # To save the list of new model failures + extra_blocks = self.get_new_model_failure_blocks(to_truncate=False) + if extra_blocks: + failure_text = extra_blocks[-1]["text"]["text"] + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(failure_text) + + # upload results to Hub dataset + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.txt") + commit_info = api.upload_file( + path_or_fileobj=file_path, + path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/new_model_failures.txt", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + 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" + + # extra processing to save to json format + new_failed_tests = {} + for line in failure_text.split(): + if "https://github.com/huggingface/transformers/actions/runs" in line: + pattern = r"<(https://github.com/huggingface/transformers/actions/runs/.+?/job/.+?)\|(.+?)>" + items = re.findall(pattern, line) + elif "tests/models/" in line: + model = line.split("/")[2] + if model not in new_failed_tests: + new_failed_tests[model] = {"single-gpu": [], "multi-gpu": []} + for url, device in items: + new_failed_tests[model][f"{device}-gpu"].append(line) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.json") + with open(file_path, "w", encoding="UTF-8") as fp: + json.dump(new_failed_tests, fp, ensure_ascii=False, indent=4) + + # upload results to Hub dataset + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.json") + _ = api.upload_file( + path_or_fileobj=file_path, + path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/new_model_failures.json", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + block = { + "type": "section", + "text": { + "type": "plain_text", + "text": " ", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check New model failures"}, + "url": url, + }, + } + blocks.append(block) + + return json.dumps(blocks) + + @staticmethod + def error_out(title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=False): + blocks = [] + title_block = {"type": "header", "text": {"type": "plain_text", "text": title}} + blocks.append(title_block) + + if ci_title: + ci_title_block = {"type": "section", "text": {"type": "mrkdwn", "text": ci_title}} + blocks.append(ci_title_block) + + offline_runners = [] + if runner_not_available: + text = "💔 CI runners are not available! Tests are not run. 😭" + result = os.environ.get("OFFLINE_RUNNERS") + if result is not None: + offline_runners = json.loads(result) + elif runner_failed: + text = "💔 CI runners have problems! Tests are not run. 😭" + elif setup_failed: + text = "💔 Setup job failed. Tests are not run. 😭" + else: + text = "💔 There was an issue running the tests. 😭" + + error_block_1 = { + "type": "header", + "text": { + "type": "plain_text", + "text": text, + }, + } + + text = "" + if len(offline_runners) > 0: + text = "\n • " + "\n • ".join(offline_runners) + text = f"The following runners are offline:\n{text}\n\n" + text += "🙏 Let's fix it ASAP! 🙏" + + error_block_2 = { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + blocks.extend([error_block_1, error_block_2]) + + payload = json.dumps(blocks) + + print("Sending the following payload") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=text, + blocks=payload, + ) + + def post(self): + payload = self.payload + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + blocks=payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_result, failures, device, text): + """ + failures: A list with elements of the form {"line": full test name, "trace": error trace} + """ + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for idx, error in enumerate(failures): + new_text = failure_text + f'*{error["line"]}*\n_{error["trace"]}_\n\n' + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + if device is not None: + title += f" ({device}-gpu)" + + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + # TODO: Make sure we always have a valid job link (or at least a way not to break the report sending) + # Currently we get the device from a job's artifact name. + # If a device is found, the job name should contain the device type, for example, `XXX (single-gpu)`. + # This could be done by adding `machine_type` in a job's `strategy`. + # (If `job_result["job_link"][device]` is `None`, we get an error: `... [ERROR] must provide a string ...`) + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_result["job_link"][device], + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def get_new_model_failure_blocks(self, with_header=True, to_truncate=True): + if self.prev_ci_artifacts is None: + return [] + + sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0]) + + prev_model_results = {} + if ( + f"ci_results_{job_name}" in self.prev_ci_artifacts + and "model_results.json" in self.prev_ci_artifacts[f"ci_results_{job_name}"] + ): + prev_model_results = json.loads(self.prev_ci_artifacts[f"ci_results_{job_name}"]["model_results.json"]) + + all_failure_lines = {} + for job, job_result in sorted_dict: + if len(job_result["failures"]): + devices = sorted(job_result["failures"].keys(), reverse=True) + for device in devices: + failures = job_result["failures"][device] + prev_error_lines = {} + if job in prev_model_results and device in prev_model_results[job]["failures"]: + prev_error_lines = {error["line"] for error in prev_model_results[job]["failures"][device]} + + url = None + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + url = job_result["job_link"][device] + + for idx, error in enumerate(failures): + if error["line"] in prev_error_lines: + continue + + new_text = f'{error["line"]}\n\n' + + if new_text not in all_failure_lines: + all_failure_lines[new_text] = [] + + all_failure_lines[new_text].append(f"<{url}|{device}>" if url is not None else device) + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") - len("```New model failures```\n\n") + if not to_truncate: + MAX_ERROR_TEXT = float("inf") + failure_text = "" + for line, devices in all_failure_lines.items(): + new_text = failure_text + f"{'|'.join(devices)} gpu\n{line}" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + blocks = [] + if failure_text: + if with_header: + blocks.append( + {"type": "header", "text": {"type": "plain_text", "text": "New model failures", "emoji": True}} + ) + else: + failure_text = f"*New model failures*\n\n{failure_text}" + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}) + + return blocks + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0]) + for job, job_result in sorted_dict: + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + text = "\n".join( + sorted([f"*{k}*: {v[device]}" for k, v in job_result["failed"].items() if v[device]]) + ) + + blocks = self.get_reply_blocks(job, job_result, failures, device, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + for job, job_result in self.additional_results.items(): + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + blocks = self.get_reply_blocks( + job, + job_result, + failures, + device, + text=f'Number of failures: {job_result["failed"][device]}', + ) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + blocks = self.get_new_model_failure_blocks() + if blocks: + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text="Results for new failures", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def retrieve_artifact(artifact_path: str, gpu: Optional[str]): + if gpu not in [None, "single", "multi"]: + raise ValueError(f"Invalid GPU for artifact. Passed GPU: `{gpu}`.") + + _artifact = {} + + if os.path.exists(artifact_path): + files = os.listdir(artifact_path) + for file in files: + try: + with open(os.path.join(artifact_path, file)) as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(artifact_path, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str, single_gpu: bool = False, multi_gpu: bool = False): + self.name = name + self.single_gpu = single_gpu + self.multi_gpu = multi_gpu + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str, gpu: str = None): + self.paths.append({"name": self.name, "path": path, "gpu": gpu}) + + _available_artifacts: Dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + + name_parts = artifact_name.split("_postfix_") + if len(name_parts) > 1: + artifact_name = name_parts[0] + + if artifact_name.startswith("single-gpu"): + artifact_name = artifact_name[len("single-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].single_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, single_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="single") + + elif artifact_name.startswith("multi-gpu"): + artifact_name = artifact_name[len("multi-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].multi_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, multi_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="multi") + else: + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +def prepare_reports(title, header, reports, to_truncate=True): + report = "" + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + if not to_truncate: + MAX_ERROR_TEXT = float("inf") + + if len(reports) > 0: + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + + for idx in range(len(reports)): + _report = header + "\n".join(reports[: idx + 1]) + new_report = f"{title}:\n```\n{_report}\n```\n" + if len(new_report) > MAX_ERROR_TEXT: + # `report` here has length <= 3000 + report = report + "[Truncated]" + break + report = new_report + + return report + + +if __name__ == "__main__": + SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"] + + # runner_status = os.environ.get("RUNNER_STATUS") + # runner_env_status = os.environ.get("RUNNER_ENV_STATUS") + setup_status = os.environ.get("SETUP_STATUS") + + # runner_not_available = True if runner_status is not None and runner_status != "success" else False + # runner_failed = True if runner_env_status is not None and runner_env_status != "success" else False + # Let's keep the lines regardig runners' status (we might be able to use them again in the future) + runner_not_available = False + runner_failed = False + # Some jobs don't depend (`needs`) on the job `setup`: in this case, the status of the job `setup` is `skipped`. + setup_failed = False if setup_status in ["skipped", "success"] else True + + org = "huggingface" + repo = "transformers" + repository_full_name = f"{org}/{repo}" + + # This env. variable is set in workflow file (under the job `send_results`). + ci_event = os.environ["CI_EVENT"] + + # To find the PR number in a commit title, for example, `Add AwesomeFormer model (#99999)` + pr_number_re = re.compile(r"\(#(\d+)\)$") + + title = f"🤗 Results of {ci_event} - {os.getenv('CI_TEST_JOB')}." + # Add Commit/PR title with a link for push CI + # (check the title in 2 env. variables - depending on the CI is triggered via `push` or `workflow_run` event) + ci_title_push = os.environ.get("CI_TITLE_PUSH") + ci_title_workflow_run = os.environ.get("CI_TITLE_WORKFLOW_RUN") + ci_title = ci_title_push if ci_title_push else ci_title_workflow_run + + ci_sha = os.environ.get("CI_SHA") + + ci_url = None + if ci_sha: + ci_url = f"https://github.com/{repository_full_name}/commit/{ci_sha}" + + if ci_title is not None: + if ci_url is None: + raise ValueError( + "When a title is found (`ci_title`), it means a `push` event or a `workflow_run` even (triggered by " + "another `push` event), and the commit SHA has to be provided in order to create the URL to the " + "commit page." + ) + ci_title = ci_title.strip().split("\n")[0].strip() + + # Retrieve the PR title and author login to complete the report + commit_number = ci_url.split("/")[-1] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/commits/{commit_number}" + ci_details = requests.get(ci_detail_url).json() + ci_author = ci_details["author"]["login"] + + merged_by = None + # Find the PR number (if any) and change the url to the actual PR page. + numbers = pr_number_re.findall(ci_title) + if len(numbers) > 0: + pr_number = numbers[0] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/pulls/{pr_number}" + ci_details = requests.get(ci_detail_url).json() + + ci_author = ci_details["user"]["login"] + ci_url = f"https://github.com/{repository_full_name}/pull/{pr_number}" + + merged_by = ci_details["merged_by"]["login"] + + if merged_by is None: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author}" + else: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author} | Merged by: {merged_by}" + + elif ci_sha: + ci_title = f"<{ci_url}|commit: {ci_sha}>" + + else: + ci_title = "" + + if runner_not_available or runner_failed or setup_failed: + Message.error_out(title, ci_title, runner_not_available, runner_failed, setup_failed) + exit(0) + + # sys.argv[0] is always `utils/notification_service.py`. + arguments = sys.argv[1:] + # In our usage in `.github/workflows/slack-report.yml`, we always pass an argument when calling this script. + # The argument could be an empty string `""` if a job doesn't depend on the job `setup`. + if arguments[0] == "": + models = [] + else: + model_list_as_str = arguments[0] + try: + folder_slices = ast.literal_eval(model_list_as_str) + # Need to change from elements like `models/bert` to `models_bert` (the ones used as artifact names). + models = [x.replace("models/", "models_") for folders in folder_slices for x in folders] + except Exception: + Message.error_out(title, ci_title) + raise ValueError("Errored out.") + + github_actions_jobs = get_jobs( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + github_actions_job_links = {job["name"]: job["html_url"] for job in github_actions_jobs} + + artifact_name_to_job_map = {} + for job in github_actions_jobs: + for step in job["steps"]: + if step["name"].startswith("Test suite reports artifacts: "): + artifact_name = step["name"][len("Test suite reports artifacts: ") :] + artifact_name_to_job_map[artifact_name] = job + break + + available_artifacts = retrieve_available_artifacts() + + modeling_categories = [ + "PyTorch", + "TensorFlow", + "Flax", + "Tokenizers", + "Pipelines", + "Trainer", + "ONNX", + "Auto", + "Unclassified", + ] + + # This dict will contain all the information relative to each model: + # - Failures: the total, as well as the number of failures per-category defined above + # - Success: total + # - Time spent: as a comma-separated list of elapsed time + # - Failures: as a line-break separated list of errors + model_results = { + model: { + "failed": {m: {"unclassified": 0, "single": 0, "multi": 0} for m in modeling_categories}, + "success": 0, + "time_spent": "", + "failures": {}, + "job_link": {}, + } + for model in models + if f"run_models_gpu_{model}_test_reports" in available_artifacts + } + + unclassified_model_failures = [] + + for model in model_results.keys(): + for artifact_path in available_artifacts[f"run_models_gpu_{model}_test_reports"].paths: + artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"]) + if "stats" in artifact: + # Link to the GitHub Action job + job = artifact_name_to_job_map[artifact_path["path"]] + model_results[model]["job_link"][artifact_path["gpu"]] = job["html_url"] + failed, success, time_spent = handle_test_results(artifact["stats"]) + model_results[model]["success"] += success + model_results[model]["time_spent"] += time_spent[1:-1] + ", " + + stacktraces = handle_stacktraces(artifact["failures_line"]) + + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + # Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling + # `stacktraces.pop` below. + # See `run_test_using_subprocess` in `src/transformers/testing_utils.py` + if " - Failed: (subprocess)" in line: + continue + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_path["gpu"] not in model_results[model]["failures"]: + model_results[model]["failures"][artifact_path["gpu"]] = [] + + model_results[model]["failures"][artifact_path["gpu"]].append( + {"line": line, "trace": stacktraces.pop(0)} + ) + + if re.search("test_modeling_tf_", line): + model_results[model]["failed"]["TensorFlow"][artifact_path["gpu"]] += 1 + + elif re.search("test_modeling_flax_", line): + model_results[model]["failed"]["Flax"][artifact_path["gpu"]] += 1 + + elif re.search("test_modeling", line): + model_results[model]["failed"]["PyTorch"][artifact_path["gpu"]] += 1 + + elif re.search("test_tokenization", line): + model_results[model]["failed"]["Tokenizers"][artifact_path["gpu"]] += 1 + + elif re.search("test_pipelines", line): + model_results[model]["failed"]["Pipelines"][artifact_path["gpu"]] += 1 + + elif re.search("test_trainer", line): + model_results[model]["failed"]["Trainer"][artifact_path["gpu"]] += 1 + + elif re.search("onnx", line): + model_results[model]["failed"]["ONNX"][artifact_path["gpu"]] += 1 + + elif re.search("auto", line): + model_results[model]["failed"]["Auto"][artifact_path["gpu"]] += 1 + + else: + model_results[model]["failed"]["Unclassified"][artifact_path["gpu"]] += 1 + unclassified_model_failures.append(line) + + # Additional runs + additional_files = { + "PyTorch pipelines": "run_pipelines_torch_gpu_test_reports", + "TensorFlow pipelines": "run_pipelines_tf_gpu_test_reports", + "Examples directory": "run_examples_gpu_test_reports", + "Torch CUDA extension tests": "run_torch_cuda_extensions_gpu_test_reports", + } + + if ci_event in ["push", "Nightly CI"] or ci_event.startswith("Past CI"): + del additional_files["Examples directory"] + del additional_files["PyTorch pipelines"] + del additional_files["TensorFlow pipelines"] + elif ci_event.startswith("Scheduled CI (AMD)"): + del additional_files["TensorFlow pipelines"] + del additional_files["Torch CUDA extension tests"] + elif ci_event.startswith("Push CI (AMD)"): + additional_files = {} + + # A map associating the job names (specified by `inputs.job` in a workflow file) with the keys of + # `additional_files`. This is used to remove some entries in `additional_files` that are not concerned by a + # specific job. See below. + job_to_test_map = { + "run_pipelines_torch_gpu": "PyTorch pipelines", + "run_pipelines_tf_gpu": "TensorFlow pipelines", + "run_examples_gpu": "Examples directory", + "run_torch_cuda_extensions_gpu": "Torch CUDA extension tests", + } + + # Remove some entries in `additional_files` if they are not concerned. + test_name = None + job_name = os.getenv("CI_TEST_JOB") + if job_name in job_to_test_map: + test_name = job_to_test_map[job_name] + additional_files = {k: v for k, v in additional_files.items() if k == test_name} + + additional_results = { + key: { + "failed": {"unclassified": 0, "single": 0, "multi": 0}, + "success": 0, + "time_spent": "", + "error": False, + "failures": {}, + "job_link": {}, + } + for key in additional_files.keys() + } + + for key in additional_results.keys(): + # If a whole suite of test fails, the artifact isn't available. + if additional_files[key] not in available_artifacts: + additional_results[key]["error"] = True + continue + + for artifact_path in available_artifacts[additional_files[key]].paths: + # Link to the GitHub Action job + job = artifact_name_to_job_map[artifact_path["path"]] + additional_results[key]["job_link"][artifact_path["gpu"]] = job["html_url"] + + artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"]) + stacktraces = handle_stacktraces(artifact["failures_line"]) + + failed, success, time_spent = handle_test_results(artifact["stats"]) + additional_results[key]["failed"][artifact_path["gpu"] or "unclassified"] += failed + additional_results[key]["success"] += success + additional_results[key]["time_spent"] += time_spent[1:-1] + ", " + + if len(artifact["errors"]): + additional_results[key]["error"] = True + + if failed: + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + # Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling + # `stacktraces.pop` below. + # See `run_test_using_subprocess` in `src/transformers/testing_utils.py` + if " - Failed: (subprocess)" in line: + continue + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_path["gpu"] not in additional_results[key]["failures"]: + additional_results[key]["failures"][artifact_path["gpu"]] = [] + + additional_results[key]["failures"][artifact_path["gpu"]].append( + {"line": line, "trace": stacktraces.pop(0)} + ) + + # Let's only check the warning for the model testing job. Currently, the job `run_extract_warnings` is only run + # when `inputs.job` (in the workflow file) is `run_models_gpu`. The reason is: otherwise we need to save several + # artifacts with different names which complicates the logic for an insignificant part of the CI workflow reporting. + selected_warnings = [] + if job_name == "run_models_gpu": + if "warnings_in_ci" in available_artifacts: + directory = available_artifacts["warnings_in_ci"].paths[0]["path"] + with open(os.path.join(directory, "selected_warnings.json")) as fp: + selected_warnings = json.load(fp) + + if not os.path.isdir(os.path.join(os.getcwd(), f"ci_results_{job_name}")): + os.makedirs(os.path.join(os.getcwd(), f"ci_results_{job_name}")) + + target_workflow = "huggingface/transformers/.github/workflows/self-scheduled-caller.yml@refs/heads/main" + is_scheduled_ci_run = os.environ.get("CI_WORKFLOW_REF") == target_workflow + + # Only the model testing job is concerned: this condition is to avoid other jobs to upload the empty list as + # results. + if job_name == "run_models_gpu": + with open(f"ci_results_{job_name}/model_results.json", "w", encoding="UTF-8") as fp: + json.dump(model_results, fp, indent=4, ensure_ascii=False) + + # upload results to Hub dataset (only for the scheduled daily CI run on `main`) + if is_scheduled_ci_run: + api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/model_results.json", + path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/model_results.json", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + # Must have the same keys as in `additional_results`. + # The values are used as the file names where to save the corresponding CI job results. + test_to_result_name = { + "PyTorch pipelines": "torch_pipeline", + "TensorFlow pipelines": "tf_pipeline", + "Examples directory": "example", + "Torch CUDA extension tests": "deepspeed", + } + for job, job_result in additional_results.items(): + with open(f"ci_results_{job_name}/{test_to_result_name[job]}_results.json", "w", encoding="UTF-8") as fp: + json.dump(job_result, fp, indent=4, ensure_ascii=False) + + # upload results to Hub dataset (only for the scheduled daily CI run on `main`) + if is_scheduled_ci_run: + api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/{test_to_result_name[job]}_results.json", + path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/{test_to_result_name[job]}_results.json", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + prev_ci_artifacts = None + if is_scheduled_ci_run: + if job_name == "run_models_gpu": + # Get the last previously completed CI's failure tables + artifact_names = [f"ci_results_{job_name}"] + output_dir = os.path.join(os.getcwd(), "previous_reports") + os.makedirs(output_dir, exist_ok=True) + prev_ci_artifacts = get_last_daily_ci_reports( + artifact_names=artifact_names, output_dir=output_dir, token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + + message = Message( + title, + ci_title, + model_results, + additional_results, + selected_warnings=selected_warnings, + prev_ci_artifacts=prev_ci_artifacts, + ) + + # send report only if there is any failure (for push CI) + if message.n_failures or (ci_event != "push" and not ci_event.startswith("Push CI (AMD)")): + message.post() + message.post_reply() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_doc_tests.py b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_doc_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..d944f73b637af2c496511998ce84bfd6fdcbd4be --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_doc_tests.py @@ -0,0 +1,385 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import re +import time +from typing import Dict, List + +from get_ci_error_statistics import get_jobs +from slack_sdk import WebClient + + +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + + return failed, success, time_spent + + +def extract_first_line_failure(failures_short_lines): + failures = {} + file = None + in_error = False + for line in failures_short_lines.split("\n"): + if re.search(r"_ \[doctest\]", line): + in_error = True + file = line.split(" ")[2] + elif in_error and not line.split(" ")[0].isdigit(): + failures[file] = line + in_error = False + + return failures + + +class Message: + def __init__(self, title: str, doc_test_results: Dict): + self.title = title + + self.n_success = sum(job_result["n_success"] for job_result in doc_test_results.values()) + self.n_failures = sum(job_result["n_failures"] for job_result in doc_test_results.values()) + self.n_tests = self.n_success + self.n_failures + + # Failures and success of the modeling tests + self.doc_test_results = doc_test_results + + @property + def time(self) -> str: + all_results = [*self.doc_test_results.values()] + time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])] + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> Dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def no_failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" + f" {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def category_failures(self) -> List[Dict]: + failure_blocks = [] + + MAX_ERROR_TEXT = 3000 - len("The following examples had failures:\n\n\n\n") - len("[Truncated]\n") + line_length = 40 + category_failures = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(v, dict)} + + def single_category_failures(category, failures): + text = "" + if len(failures) == 0: + return "" + text += f"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" + + for idx, failure in enumerate(failures): + new_text = text + f"`{failure}`\n" + if len(new_text) > MAX_ERROR_TEXT: + text = text + "[Truncated]\n" + break + text = new_text + + return text + + for category, failures in category_failures.items(): + report = single_category_failures(category, failures) + if len(report) == 0: + continue + block = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"The following examples had failures:\n\n\n{report}\n", + }, + } + failure_blocks.append(block) + + return failure_blocks + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.n_failures > 0: + blocks.append(self.failures) + + if self.n_failures > 0: + blocks.extend(self.category_failures) + + if self.n_failures == 0: + blocks.append(self.no_failures) + + return json.dumps(blocks) + + @staticmethod + def error_out(): + payload = [ + { + "type": "section", + "text": { + "type": "plain_text", + "text": "There was an issue running the tests.", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + ] + + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text="There was an issue running the tests.", + blocks=payload, + ) + + def post(self): + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(self.payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + blocks=self.payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_link, failures, text): + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for key, value in failures.items(): + new_text = failure_text + f"*{key}*\n_{value}_\n\n" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + if job_link is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_link, + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title, "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + sorted_dict = sorted(self.doc_test_results.items(), key=lambda t: t[0]) + for job_name, job_result in sorted_dict: + if len(job_result["failures"]) > 0: + text = f"*Num failures* :{len(job_result['failed'])} \n" + failures = job_result["failures"] + blocks = self.get_reply_blocks(job_name, job_result["job_link"], failures, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job_name}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def retrieve_artifact(name: str): + _artifact = {} + + if os.path.exists(name): + files = os.listdir(name) + for file in files: + try: + with open(os.path.join(name, file), encoding="utf-8") as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(name, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str): + self.name = name + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str): + self.paths.append({"name": self.name, "path": path}) + + _available_artifacts: Dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +if __name__ == "__main__": + SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"] + + github_actions_jobs = get_jobs( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + + artifact_name_to_job_map = {} + for job in github_actions_jobs: + for step in job["steps"]: + if step["name"].startswith("Test suite reports artifacts: "): + artifact_name = step["name"][len("Test suite reports artifacts: ") :] + artifact_name_to_job_map[artifact_name] = job + break + + available_artifacts = retrieve_available_artifacts() + + doc_test_results = {} + # `artifact_key` is the artifact path + for artifact_key, artifact_obj in available_artifacts.items(): + artifact_path = artifact_obj.paths[0] + if not artifact_path["path"].startswith("doc_tests_gpu_test_reports_"): + continue + + # change "_" back to "/" (to show the job name as path) + job_name = artifact_path["path"].replace("doc_tests_gpu_test_reports_", "").replace("_", "/") + + # This dict (for each job) will contain all the information relative to each doc test job, in particular: + # - failed: list of failed tests + # - failures: dict in the format 'test': 'error_message' + job_result = {} + doc_test_results[job_name] = job_result + + job = artifact_name_to_job_map[artifact_path["path"]] + job_result["job_link"] = job["html_url"] + job_result["category"] = "Python Examples" if job_name.startswith("src/") else "MD Examples" + + artifact = retrieve_artifact(artifact_path["path"]) + if "stats" in artifact: + failed, success, time_spent = handle_test_results(artifact["stats"]) + job_result["n_failures"] = failed + job_result["n_success"] = success + job_result["time_spent"] = time_spent[1:-1] + ", " + job_result["failed"] = [] + job_result["failures"] = {} + + all_failures = extract_first_line_failure(artifact["failures_short"]) + for line in artifact["summary_short"].split("\n"): + if re.search("FAILED", line): + line = line.replace("FAILED ", "") + line = line.split()[0].replace("\n", "") + + if "::" in line: + file_path, test = line.split("::") + else: + file_path, test = line, line + + job_result["failed"].append(test) + failure = all_failures[test] if test in all_failures else "N/A" + job_result["failures"][test] = failure + + # Save and to be uploaded as artifact + os.makedirs("doc_test_results", exist_ok=True) + with open("doc_test_results/doc_test_results.json", "w", encoding="UTF-8") as fp: + json.dump(doc_test_results, fp, ensure_ascii=False, indent=4) + + message = Message("🤗 Results of the doc tests.", doc_test_results) + message.post() + message.post_reply() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_quantization.py b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..0264797c94ef82778707dd6ffa5c02633b11617d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_quantization.py @@ -0,0 +1,274 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import ast +import datetime +import json +import os +import sys +import time +from typing import Dict + +from get_ci_error_statistics import get_jobs +from huggingface_hub import HfApi +from notification_service import ( + Message, + handle_stacktraces, + handle_test_results, + prepare_reports, + retrieve_artifact, + retrieve_available_artifacts, +) +from slack_sdk import WebClient + + +api = HfApi() +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + + +class QuantizationMessage(Message): + def __init__( + self, + title: str, + results: Dict, + ): + self.title = title + + # Failures and success of the modeling tests + self.n_success = sum(r["success"] for r in results.values()) + self.single_gpu_failures = sum(r["failed"]["single"] for r in results.values()) + self.multi_gpu_failures = sum(r["failed"]["multi"] for r in results.values()) + self.n_failures = self.single_gpu_failures + self.multi_gpu_failures + + self.n_tests = self.n_failures + self.n_success + self.results = results + self.thread_ts = None + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.n_failures > 0: + blocks.append(self.failures_overwiew) + blocks.append(self.failures_detailed) + + if self.n_failures == 0: + blocks.append(self.no_failures) + + return json.dumps(blocks) + + @property + def time(self) -> str: + all_results = self.results.values() + time_spent = [] + for r in all_results: + if len(r["time_spent"]): + time_spent.extend([x for x in r["time_spent"].split(", ") if len(x.strip())]) + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def failures_overwiew(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n" + f"The suite ran in {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures_detailed(self) -> Dict: + failures = {k: v["failed"] for k, v in self.results.items()} + + individual_reports = [] + for key, value in failures.items(): + device_report = self.get_device_report(value) + if sum(value.values()): + report = f"{device_report}{key}" + individual_reports.append(report) + + header = "Single | Multi | Category\n" + failures_report = prepare_reports( + title="The following quantization tests had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}} + + def post(self): + payload = self.payload + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + blocks=payload, + text=text, + ) + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + for job, job_result in self.results.items(): + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + blocks = self.get_reply_blocks( + job, + job_result, + failures, + device, + text=f'Number of failures: {job_result["failed"][device]}', + ) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel="#transformers-ci-daily-quantization", + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + time.sleep(1) + + +if __name__ == "__main__": + setup_status = os.environ.get("SETUP_STATUS") + SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"] + setup_failed = True if setup_status is not None and setup_status != "success" else False + + # This env. variable is set in workflow file (under the job `send_results`). + ci_event = os.environ["CI_EVENT"] + + title = f"🤗 Results of the {ci_event} - {os.getenv('CI_TEST_JOB')}." + + if setup_failed: + Message.error_out( + title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=setup_failed + ) + exit(0) + + arguments = sys.argv[1:][0] + try: + quantization_matrix = ast.literal_eval(arguments) + # Need to change from elements like `quantization/bnb` to `quantization_bnb` (the ones used as artifact names). + quantization_matrix = [x.replace("quantization/", "quantization_") for x in quantization_matrix] + except SyntaxError: + Message.error_out(title, ci_title="") + raise ValueError("Errored out.") + + available_artifacts = retrieve_available_artifacts() + + quantization_results = { + quant: { + "failed": {"single": 0, "multi": 0}, + "success": 0, + "time_spent": "", + "failures": {}, + "job_link": {}, + } + for quant in quantization_matrix + if f"run_quantization_torch_gpu_{ quant }_test_reports" in available_artifacts + } + + github_actions_jobs = get_jobs( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + github_actions_job_links = {job["name"]: job["html_url"] for job in github_actions_jobs} + + artifact_name_to_job_map = {} + for job in github_actions_jobs: + for step in job["steps"]: + if step["name"].startswith("Test suite reports artifacts: "): + artifact_name = step["name"][len("Test suite reports artifacts: ") :] + artifact_name_to_job_map[artifact_name] = job + break + + for quant in quantization_results.keys(): + for artifact_path in available_artifacts[f"run_quantization_torch_gpu_{ quant }_test_reports"].paths: + artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"]) + if "stats" in artifact: + # Link to the GitHub Action job + job = artifact_name_to_job_map[artifact_path["path"]] + quantization_results[quant]["job_link"][artifact_path["gpu"]] = job["html_url"] + failed, success, time_spent = handle_test_results(artifact["stats"]) + quantization_results[quant]["failed"][artifact_path["gpu"]] += failed + quantization_results[quant]["success"] += success + quantization_results[quant]["time_spent"] += time_spent[1:-1] + ", " + + stacktraces = handle_stacktraces(artifact["failures_line"]) + + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_path["gpu"] not in quantization_results[quant]["failures"]: + quantization_results[quant]["failures"][artifact_path["gpu"]] = [] + + quantization_results[quant]["failures"][artifact_path["gpu"]].append( + {"line": line, "trace": stacktraces.pop(0)} + ) + + job_name = os.getenv("CI_TEST_JOB") + if not os.path.isdir(os.path.join(os.getcwd(), f"ci_results_{job_name}")): + os.makedirs(os.path.join(os.getcwd(), f"ci_results_{job_name}")) + + with open(f"ci_results_{job_name}/quantization_results.json", "w", encoding="UTF-8") as fp: + json.dump(quantization_results, fp, indent=4, ensure_ascii=False) + + target_workflow = "huggingface/transformers/.github/workflows/self-scheduled-caller.yml@refs/heads/main" + is_scheduled_ci_run = os.environ.get("CI_WORKFLOW_REF") == target_workflow + + # upload results to Hub dataset (only for the scheduled daily CI run on `main`) + if is_scheduled_ci_run: + api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/quantization_results.json", + path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/quantization_results.json", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + message = QuantizationMessage( + title, + results=quantization_results, + ) + + message.post() + message.post_reply() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/past_ci_versions.py b/tasks/tasksmith-441eeab80047/environment/source/utils/past_ci_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..61495ab2a46fcd39801614b67d5734e9fd159a90 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/past_ci_versions.py @@ -0,0 +1,126 @@ +import argparse +import os + + +past_versions_testing = { + "pytorch": { + "1.13": { + "torch": "1.13.1", + "torchvision": "0.14.1", + "torchaudio": "0.13.1", + "python": 3.9, + "cuda": "cu116", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1" + " --extra-index-url https://download.pytorch.org/whl/cu116" + ), + "base_image": "nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04", + }, + "1.12": { + "torch": "1.12.1", + "torchvision": "0.13.1", + "torchaudio": "0.12.1", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.11": { + "torch": "1.11.0", + "torchvision": "0.12.0", + "torchaudio": "0.11.0", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.10": { + "torch": "1.10.2", + "torchvision": "0.11.3", + "torchaudio": "0.10.2", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.10.2 torchvision==0.11.3 torchaudio==0.10.2" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + # torchaudio < 0.10 has no CUDA-enabled binary distributions + "1.9": { + "torch": "1.9.1", + "torchvision": "0.10.1", + "torchaudio": "0.9.1", + "python": 3.9, + "cuda": "cu111", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.9.1 torchvision==0.10.1 torchaudio==0.9.1" + " --extra-index-url https://download.pytorch.org/whl/cu111" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, + "tensorflow": { + "2.11": { + "tensorflow": "2.11.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.11.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.10": { + "tensorflow": "2.10.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.10.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.9": { + "tensorflow": "2.9.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.9.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.8": { + "tensorflow": "2.8.2", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.8.2", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.7": { + "tensorflow": "2.7.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.7.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.6": { + "tensorflow": "2.6.5", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.6.5", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.5": { + "tensorflow": "2.5.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.5.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, +} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser("Choose the framework and version to install") + parser.add_argument( + "--framework", help="The framework to install. Should be `torch` or `tensorflow`", type=str, required=True + ) + parser.add_argument("--version", help="The version of the framework to install.", type=str, required=True) + args = parser.parse_args() + + info = past_versions_testing[args.framework][args.version] + + os.system(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile') + print(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile') + + cuda = "" + if args.framework == "pytorch": + cuda = info["cuda"] + os.system(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") + print(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/patch_helper.py b/tasks/tasksmith-441eeab80047/environment/source/utils/patch_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..f31e755efdc94e71c35c68a7d9b3ee48de12ca3a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/patch_helper.py @@ -0,0 +1,95 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +This should help you prepare a patch, automatically extracting the commits to cherry-pick +in chronological order to avoid merge conflicts. An equivalent way to do this is to use +`git log --pretty=oneline HEAD...v4.41.0` and grep. + +Potential TODO: automatically cherry-picks them. + +Pass in a list of PR: +`python utils/patch_helper.py --prs 31108 31054 31008 31010 31004` +will produce the following: +```bash +Skipping invalid version tag: list +Skipping invalid version tag: localattn1 +Git cherry-pick commands to run: +git cherry-pick 03935d300d60110bb86edb49d2315089cfb19789 #2024-05-24 11:00:59+02:00 +git cherry-pick bdb9106f247fca48a71eb384be25dbbd29b065a8 #2024-05-24 19:02:55+02:00 +git cherry-pick 84c4b72ee99e8e65a8a5754a5f9d6265b45cf67e #2024-05-27 10:34:14+02:00 +git cherry-pick 936ab7bae5e040ec58994cb722dd587b9ab26581 #2024-05-28 11:56:05+02:00 +git cherry-pick 0bef4a273825d2cfc52ddfe62ba486ee61cc116f #2024-05-29 13:33:26+01:00 +``` +""" + +import argparse + +from git import GitCommandError, Repo +from packaging import version + + +def get_merge_commit(repo, pr_number, since_tag): + try: + # Use git log to find the merge commit for the PR within the given tag range + merge_commit = next(repo.iter_commits(f"v{since_tag}...origin/main", grep=f"#{pr_number}")) + return merge_commit + except StopIteration: + print(f"No merge commit found for PR #{pr_number} between tags {since_tag} and {main}") + return None + except GitCommandError as e: + print(f"Error finding merge commit for PR #{pr_number}: {str(e)}") + return None + + +def main(pr_numbers): + repo = Repo(".") # Initialize the Repo object for the current directory + merge_commits = [] + + tags = {} + for tag in repo.tags: + try: + # Parse and sort tags, skip invalid ones + tag_ver = version.parse(tag.name) + tags[tag_ver] = tag + except Exception: + print(f"Skipping invalid version tag: {tag.name}") + + last_tag = sorted(tags)[-1] + major_minor = f"{last_tag.major}.{last_tag.minor}.0" + # Iterate through tag ranges to find the merge commits + for pr in pr_numbers: + pr = pr.split("https://github.com/huggingface/transformers/pull/")[-1] + commit = get_merge_commit(repo, pr, major_minor) + if commit: + merge_commits.append(commit) + + # Sort commits by date + merge_commits.sort(key=lambda commit: commit.committed_datetime) + + # Output the git cherry-pick commands + print("Git cherry-pick commands to run:") + for commit in merge_commits: + print(f"git cherry-pick {commit.hexsha} #{commit.committed_datetime}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Find and sort merge commits for specified PRs.") + parser.add_argument("--prs", nargs="+", required=False, type=str, help="PR numbers to find merge commits for") + + args = parser.parse_args() + if args.prs is None: + 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() + main(args.prs) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/pr_slow_ci_models.py b/tasks/tasksmith-441eeab80047/environment/source/utils/pr_slow_ci_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4403ade4980408120194c1cfb604016d3d13f72d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/pr_slow_ci_models.py @@ -0,0 +1,173 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This script is used to get the models for which to run slow CI. + +A new model added in a pull request will be included, as well as models specified in a GitHub pull request's comment +with a prefix `run-slow`, `run_slow` or `run slow`. For example, the commit message `run_slow: bert, gpt2` will give +`bert` and `gpt2`. + +Usage: + +```bash +python utils/pr_slow_ci_models.py +``` +""" + +import argparse +import os.path +import re +import string +from pathlib import Path +from typing import List + +from git import Repo + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() + + +def get_new_python_files_between_commits(base_commit: str, commits: List[str]) -> List[str]: + """ + Get the list of added python files between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of python files added between a base commit and one or several commits. + """ + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We always add new python files + if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): + code_diff.append(diff_obj.b_path) + + return code_diff + + +def get_new_python_files(diff_with_last_commit=False) -> List[str]: + """ + Return a list of python files that have been added between the current head and the main branch. + + Returns: + `List[str]`: The list of python files added. + """ + repo = Repo(PATH_TO_REPO) + + try: + # For the cases where the main branch exists locally + main = repo.refs.main + except AttributeError: + # On GitHub Actions runners, it doesn't have local main branch + main = repo.remotes.origin.refs.main + + if not diff_with_last_commit: + print(f"main is at {main.commit}") + print(f"Current head is at {repo.head.commit}") + + commits = repo.merge_base(main, repo.head) + for commit in commits: + print(f"Branching commit: {commit}") + else: + print(f"main is at {main.commit}") + commits = main.commit.parents + for commit in commits: + print(f"Parent commit: {commit}") + + return get_new_python_files_between_commits(repo.head.commit, commits) + + +def get_new_model(diff_with_last_commit=False): + new_files = get_new_python_files(diff_with_last_commit) + reg = re.compile(r"src/transformers/models/(.*)/modeling_.*\.py") + + new_model = "" + for x in new_files: + find_new_model = reg.findall(x) + if len(find_new_model) > 0: + new_model = find_new_model[0] + # It's unlikely we have 2 new modeling files in a pull request. + break + return new_model + + +def parse_message(message: str) -> str: + """ + Parses a GitHub pull request's comment to find the models specified in it to run slow CI. + + Args: + message (`str`): The body of a GitHub pull request's comment. + + Returns: + `str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the + empty string is returned. + """ + if message is None: + return "" + + message = message.strip().lower() + + # run-slow: model_1, model_2 + if not message.startswith(("run-slow", "run_slow", "run slow")): + return "" + message = message[len("run slow") :] + # remove leading `:` + while message.strip().startswith(":"): + message = message.strip()[1:] + + return message + + +def get_models(message: str): + models = parse_message(message) + return models.replace(",", " ").split() + + +def check_model_names(model_name: str): + allowed = string.ascii_letters + string.digits + "_" + return not (model_name.startswith("_") or model_name.endswith("_")) and all(c in allowed for c in model_name) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--message", type=str, default="", help="The content of a comment.") + parser.add_argument("--quantization", action="store_true", help="If we collect quantization tests") + args = parser.parse_args() + + new_model = get_new_model() + specified_models = get_models(args.message) + models = ([] if new_model == "" else [new_model]) + specified_models + # a guard for strange model names + models = [model for model in models if check_model_names(model)] + + # Add prefix + final_list = [] + for model in models: + if not args.quantization: + if os.path.isdir(f"tests/models/{model}"): + final_list.append(f"models/{model}") + elif os.path.isdir(f"tests/{model}") and model != "quantization": + final_list.append(model) + elif os.path.isdir(f"tests/quantization/{model}"): + final_list.append(f"quantization/{model}") + + print(sorted(set(final_list))) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/print_env.py b/tasks/tasksmith-441eeab80047/environment/source/utils/print_env.py new file mode 100644 index 0000000000000000000000000000000000000000..443ed6eab6c4b95bf82f8ae6a43da24852ad60b3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/print_env.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# this script dumps information about the environment + +import os +import sys + +import transformers + + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +print("Python version:", sys.version) +print("transformers version:", transformers.__version__) + +try: + import torch + + print("Torch version:", torch.__version__) + print("Cuda available:", torch.cuda.is_available()) + print("Cuda version:", torch.version.cuda) + print("CuDNN version:", torch.backends.cudnn.version()) + print("Number of GPUs available:", torch.cuda.device_count()) + print("NCCL version:", torch.cuda.nccl.version()) +except ImportError: + print("Torch version:", None) + +try: + import deepspeed + + print("DeepSpeed version:", deepspeed.__version__) +except ImportError: + print("DeepSpeed version:", None) + +try: + import tensorflow as tf + + print("TensorFlow version:", tf.__version__) + print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) + print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) +except ImportError: + print("TensorFlow version:", None) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/process_bad_commit_report.py b/tasks/tasksmith-441eeab80047/environment/source/utils/process_bad_commit_report.py new file mode 100644 index 0000000000000000000000000000000000000000..19812ff21f7d19c0d9576484b84388eb37a1264c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/process_bad_commit_report.py @@ -0,0 +1,90 @@ +"""An internal script to process `new_model_failures_with_bad_commit.json` produced by `utils/check_bad_commit.py`. + +This is used by `.github/workflows/check_failed_model_tests.yml` to produce a slack report of the following form + +``` +<{url}|New failed tests> +{ + "GH_ydshieh": { + "vit": 1 + } +} +``` +""" + +import datetime +import json +import os +from collections import Counter +from copy import deepcopy + +from huggingface_hub import HfApi + + +if __name__ == "__main__": + api = HfApi() + + with open("new_model_failures_with_bad_commit.json") as fp: + data = json.load(fp) + + # TODO: extend + team_members = [ + "ydshieh", + "zucchini-nlp", + "ArthurZucker", + "gante", + "LysandreJik", + "molbap", + "qubvel", + "Rocketknight1", + "muellerzr", + "SunMarc", + ] + + # Counting the number of failures grouped by authors + new_data = {} + for model, model_result in data.items(): + for device, failed_tests in model_result.items(): + for failed_test in failed_tests: + author = failed_test["author"] + + if author not in team_members: + author = failed_test["merged_by"] + + if author not in new_data: + new_data[author] = Counter() + new_data[author].update([model]) + for author in new_data: + new_data[author] = dict(new_data[author]) + + # Group by author + new_data_full = {author: deepcopy(data) for author in new_data} + for author, _data in new_data_full.items(): + for model, model_result in _data.items(): + for device, failed_tests in model_result.items(): + failed_tests = [x for x in failed_tests if x["author"] == author or x["merged_by"] == author] + model_result[device] = failed_tests + _data[model] = {k: v for k, v in model_result.items() if len(v) > 0} + new_data_full[author] = {k: v for k, v in _data.items() if len(v) > 0} + + # Upload to Hub and get the url + with open("new_model_failures_with_bad_commit_grouped_by_authors.json", "w") as fp: + json.dump(new_data_full, fp, ensure_ascii=False, indent=4) + commit_info = api.upload_file( + path_or_fileobj="new_model_failures_with_bad_commit_grouped_by_authors.json", + 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", + repo_id="hf-internal-testing/transformers_daily_ci", + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + 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" + + # Add `GH_` prefix as keyword mention + output = {} + for author, item in new_data.items(): + author = f"GH_{author}" + output[author] = item + + report = f"<{url}|New failed tests>\\n\\n" + report += json.dumps(output, indent=4).replace('"', '\\"').replace("\n", "\\n") + print(report) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/process_circleci_workflow_test_reports.py b/tasks/tasksmith-441eeab80047/environment/source/utils/process_circleci_workflow_test_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..944bc47a7e2fa42da1631eb6cfc5026aa54849df --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/process_circleci_workflow_test_reports.py @@ -0,0 +1,85 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import json +import os + +import requests + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--workflow_id", type=str, required=True) + args = parser.parse_args() + workflow_id = args.workflow_id + + r = requests.get( + f"https://circleci.com/api/v2/workflow/{workflow_id}/job", + headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}, + ) + jobs = r.json()["items"] + + os.makedirs("outputs", exist_ok=True) + + workflow_summary = {} + # for each job, download artifacts + for job in jobs: + project_slug = job["project_slug"] + if job["name"].startswith(("tests_", "examples_", "pipelines_")): + url = f'https://circleci.com/api/v2/project/{project_slug}/{job["job_number"]}/artifacts' + r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}) + job_artifacts = r.json()["items"] + + os.makedirs(job["name"], exist_ok=True) + os.makedirs(f'outputs/{job["name"]}', exist_ok=True) + + job_test_summaries = {} + for artifact in job_artifacts: + if artifact["path"].startswith("reports/") and artifact["path"].endswith("/summary_short.txt"): + node_index = artifact["node_index"] + url = artifact["url"] + r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}) + test_summary = r.text + job_test_summaries[node_index] = test_summary + + summary = {} + for node_index, node_test_summary in job_test_summaries.items(): + for line in node_test_summary.splitlines(): + if line.startswith("PASSED "): + test = line[len("PASSED ") :] + summary[test] = "passed" + elif line.startswith("FAILED "): + test = line[len("FAILED ") :].split()[0] + summary[test] = "failed" + # failed before passed + summary = dict(sorted(summary.items(), key=lambda x: (x[1], x[0]))) + workflow_summary[job["name"]] = summary + + # collected version + with open(f'outputs/{job["name"]}/test_summary.json', "w") as fp: + json.dump(summary, fp, indent=4) + + new_workflow_summary = {} + for job_name, job_summary in workflow_summary.items(): + for test, status in job_summary.items(): + if test not in new_workflow_summary: + new_workflow_summary[test] = {} + new_workflow_summary[test][job_name] = status + + for test, result in new_workflow_summary.items(): + new_workflow_summary[test] = dict(sorted(result.items())) + new_workflow_summary = dict(sorted(new_workflow_summary.items())) + + with open("outputs/test_summary.json", "w") as fp: + json.dump(new_workflow_summary, fp, indent=4) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/process_test_artifacts.py b/tasks/tasksmith-441eeab80047/environment/source/utils/process_test_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..e685a99095067b012fc8a036dd7555c6b0143271 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/process_test_artifacts.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" + +This helper computes the "ideal" number of nodes to use in circle CI. +For each job, we compute this parameter and pass it to the `generated_config.yaml`. +""" + +import json +import math +import os + + +MAX_PARALLEL_NODES = 8 # TODO create a mapping! +AVERAGE_TESTS_PER_NODES = 5 + + +def count_lines(filepath): + """Count the number of lines in a file.""" + try: + with open(filepath, "r") as f: + return len(f.read().split("\n")) + except FileNotFoundError: + return 0 + + +def compute_parallel_nodes(line_count, max_tests_per_node=10): + """Compute the number of parallel nodes required.""" + num_nodes = math.ceil(line_count / AVERAGE_TESTS_PER_NODES) + if line_count < 4: + return 1 + return min(MAX_PARALLEL_NODES, num_nodes) + + +def process_artifacts(input_file, output_file): + # Read the JSON data from the input file + with open(input_file, "r") as f: + data = json.load(f) + + # Process items and build the new JSON structure + transformed_data = {} + for item in data.get("items", []): + if "test_list" in item["path"]: + key = os.path.splitext(os.path.basename(item["path"]))[0] + transformed_data[key] = item["url"] + parallel_key = key.split("_test")[0] + "_parallelism" + file_path = os.path.join("test_preparation", f"{key}.txt") + line_count = count_lines(file_path) + transformed_data[parallel_key] = compute_parallel_nodes(line_count) + + # Remove the "generated_config" key if it exists + if "generated_config" in transformed_data: + del transformed_data["generated_config"] + + # Write the transformed data to the output file + with open(output_file, "w") as f: + json.dump(transformed_data, f, indent=2) + + +if __name__ == "__main__": + input_file = "test_preparation/artifacts.json" + output_file = "test_preparation/transformed_artifacts.json" + process_artifacts(input_file, output_file) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/release.py b/tasks/tasksmith-441eeab80047/environment/source/utils/release.py new file mode 100644 index 0000000000000000000000000000000000000000..e4e79cec1589bc097aa76b653b4bb85fd4aacfa3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/release.py @@ -0,0 +1,204 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that prepares the repository for releases (or patches) by updating all versions in the relevant places. It +also performs some post-release cleanup, by updating the links in the main README to respective model doc pages (from +main to stable). + +To prepare for a release, use from the root of the repo on the release branch with: + +```bash +python release.py +``` + +or use `make pre-release`. + +To prepare for a patch release, use from the root of the repo on the release branch with: + +```bash +python release.py --patch +``` + +or use `make pre-patch`. + +To do the post-release cleanup, use from the root of the repo on the main branch with: + +```bash +python release.py --post_release +``` + +or use `make post-release`. +""" + +import argparse +import os +import re +from pathlib import Path + +import packaging.version + + +# All paths are defined with the intent that this script should be run from the root of the repo. +PATH_TO_EXAMPLES = "examples/" +PATH_TO_MODELS = "src/transformers/models" +# This maps a type of file to the pattern to look for when searching where the version is defined, as well as the +# template to follow when replacing it with the new version. +REPLACE_PATTERNS = { + "examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), + "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), + "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'), +} +# This maps a type of file to its path in Transformers +REPLACE_FILES = { + "init": "src/transformers/__init__.py", + "setup": "setup.py", +} +README_FILE = "README.md" + + +def update_version_in_file(fname: str, version: str, file_type: str): + """ + Update the version of Transformers in one file. + + Args: + fname (`str`): The path to the file where we want to update the version. + version (`str`): The new version to set in the file. + file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`). + """ + with open(fname, "r", encoding="utf-8", newline="\n") as f: + code = f.read() + re_pattern, replace = REPLACE_PATTERNS[file_type] + replace = replace.replace("VERSION", version) + code = re_pattern.sub(replace, code) + with open(fname, "w", encoding="utf-8", newline="\n") as f: + f.write(code) + + +def update_version_in_examples(version: str): + """ + Update the version in all examples files. + + Args: + version (`str`): The new version to set in the examples. + """ + for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES): + # Removing some of the folders with non-actively maintained examples from the walk + if "legacy" in directories: + directories.remove("legacy") + for fname in fnames: + if fname.endswith(".py"): + update_version_in_file(os.path.join(folder, fname), version, file_type="examples") + + +def global_version_update(version: str, patch: bool = False): + """ + Update the version in all needed files. + + Args: + version (`str`): The new version to set everywhere. + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + for pattern, fname in REPLACE_FILES.items(): + update_version_in_file(fname, version, pattern) + if not patch: + # We don't update the version in the examples for patch releases. + update_version_in_examples(version) + + +def remove_conversion_scripts(): + """ + Delete the scripts that convert models from older, unsupported formats. We don't want to include these + in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in + vulnerability scanners flagging us and can cause compliance issues for users with strict security policies. + """ + model_dir = Path(PATH_TO_MODELS) + for conversion_script in list(model_dir.glob("**/convert*.py")): + conversion_script.unlink() + + +def get_version() -> packaging.version.Version: + """ + Reads the current version in the main __init__. + """ + with open(REPLACE_FILES["init"], "r") as f: + code = f.read() + default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0] + return packaging.version.parse(default_version) + + +def pre_release_work(patch: bool = False): + """ + Do all the necessary pre-release steps: + - figure out the next minor release version and ask confirmation + - update the version everywhere + - clean-up the model list in the main README + + Args: + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + # First let's get the default version: base version if we are in dev, bump minor otherwise. + default_version = get_version() + if patch and default_version.is_devrelease: + raise ValueError("Can't create a patch version from the dev branch, checkout a released version!") + if default_version.is_devrelease: + default_version = default_version.base_version + elif patch: + default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" + else: + default_version = f"{default_version.major}.{default_version.minor + 1}.0" + + # Now let's ask nicely if we have found the right version. + version = input(f"Which version are you releasing? [{default_version}]") + if len(version) == 0: + version = default_version + + print(f"Updating version to {version}.") + global_version_update(version, patch=patch) + print("Deleting conversion scripts.") + remove_conversion_scripts() + + +def post_release_work(): + """ + Do all the necessary post-release steps: + - figure out the next dev version and ask confirmation + - update the version everywhere + - clean-up the model list in the main README + """ + # First let's get the current version + current_version = get_version() + dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0" + current_version = current_version.base_version + + # Check with the user we got that right. + version = input(f"Which version are we developing now? [{dev_version}]") + if len(version) == 0: + version = dev_version + + print(f"Updating version to {version}.") + global_version_update(version) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") + parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") + args = parser.parse_args() + if not args.post_release: + pre_release_work(patch=args.patch) + elif args.patch: + print("Nothing to do after a patch :-)") + else: + post_release_work() diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/set_cuda_devices_for_ci.py b/tasks/tasksmith-441eeab80047/environment/source/utils/set_cuda_devices_for_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..da3638955ff3959fed7a2fe39f00c3608ff3d3fe --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/set_cuda_devices_for_ci.py @@ -0,0 +1,26 @@ +"""A simple script to set flexibly CUDA_VISIBLE_DEVICES in GitHub Actions CI workflow files.""" + +import argparse +import os + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--test_folder", + type=str, + default=None, + help="The test folder name of the model being tested. For example, `models/cohere`.", + ) + args = parser.parse_args() + + # `test_eager_matches_sdpa_generate` for `cohere` needs a lot of GPU memory! + # This depends on the runners. At this moment we are targeting our AWS CI runners. + if args.test_folder == "models/cohere": + cuda_visible_devices = "0,1,2,3" + elif "CUDA_VISIBLE_DEVICES" in os.environ: + cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") + else: + cuda_visible_devices = "0" + + print(cuda_visible_devices) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/slow_documentation_tests.txt b/tasks/tasksmith-441eeab80047/environment/source/utils/slow_documentation_tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..71b0f27839f71b4cc30aa29a62a9ba2c56b0c360 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/slow_documentation_tests.txt @@ -0,0 +1,16 @@ +docs/source/en/generation_strategies.md +docs/source/en/model_doc/code_llama.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/kosmos-2.md +docs/source/en/model_doc/seamless_m4t.md +docs/source/en/model_doc/seamless_m4t_v2.md +docs/source/en/task_summary.md +docs/source/en/tasks/prompting.md +docs/source/ja/model_doc/code_llama.md +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/ctrl/modeling_ctrl.py +src/transformers/models/fuyu/modeling_fuyu.py +src/transformers/models/idefics2/modeling_idefics2.py +src/transformers/models/kosmos2/modeling_kosmos2.py +src/transformers/models/musicgen_melody/modeling_musicgen_melody.py +src/transformers/models/musicgen_melody/processing_musicgen_melody.py diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/sort_auto_mappings.py b/tasks/tasksmith-441eeab80047/environment/source/utils/sort_auto_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..42382b6dfec07ac3d012a23b4920a073a11b62a6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/sort_auto_mappings.py @@ -0,0 +1,125 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that sorts the names in the auto mappings defines in the auto modules in alphabetical order. + +Use from the root of the repo with: + +```bash +python utils/sort_auto_mappings.py +``` + +to auto-fix all the auto mappings (used in `make style`). + +To only check if the mappings are properly sorted (as used in `make quality`), do: + +```bash +python utils/sort_auto_mappings.py --check_only +``` +""" + +import argparse +import os +import re +from typing import Optional + + +# Path are set with the intent you should run this script from the root of the repo. +PATH_TO_AUTO_MODULE = "src/transformers/models/auto" + + +# re pattern that matches mapping introductions: +# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict +_re_intro_mapping = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") +# re pattern that matches identifiers in mappings +_re_identifier = re.compile(r'\s*\(\s*"(\S[^"]+)"') + + +def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]: + """ + Sort all auto mappings in a file. + + Args: + fname (`str`): The name of the file where we want to sort auto-mappings. + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + + Returns: + `Optional[bool]`: Returns `None` if `overwrite=True`. Otherwise returns `True` if the file has an auto-mapping + improperly sorted, `False` if the file is okay. + """ + with open(fname, "r", encoding="utf-8") as f: + content = f.read() + + lines = content.split("\n") + new_lines = [] + line_idx = 0 + while line_idx < len(lines): + if _re_intro_mapping.search(lines[line_idx]) is not None: + # Start of a new mapping! + indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8 + while not lines[line_idx].startswith(" " * indent + "("): + new_lines.append(lines[line_idx]) + line_idx += 1 + + blocks = [] + while lines[line_idx].strip() != "]": + # Blocks either fit in one line or not + if lines[line_idx].strip() == "(": + start_idx = line_idx + while not lines[line_idx].startswith(" " * indent + ")"): + line_idx += 1 + blocks.append("\n".join(lines[start_idx : line_idx + 1])) + else: + blocks.append(lines[line_idx]) + line_idx += 1 + + # Sort blocks by their identifiers + blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0]) + new_lines += blocks + else: + new_lines.append(lines[line_idx]) + line_idx += 1 + + if overwrite: + with open(fname, "w", encoding="utf-8") as f: + f.write("\n".join(new_lines)) + else: + return "\n".join(new_lines) != content + + +def sort_all_auto_mappings(overwrite: bool = False): + """ + Sort all auto mappings in the library. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + """ + fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")] + diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames] + + if not overwrite and any(diffs): + failures = [f for f, d in zip(fnames, diffs) if d] + raise ValueError( + f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix" + " this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_all_auto_mappings(not args.check_only) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/split_doctest_jobs.py b/tasks/tasksmith-441eeab80047/environment/source/utils/split_doctest_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..0735298f3123aef0eb6375696ef60cbeab94023a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/split_doctest_jobs.py @@ -0,0 +1,91 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This script is used to get the files against which we will run doc testing. +This uses `tests_fetcher.get_all_doctest_files` then groups the test files by their directory paths. + +The files in `docs/source/en/model_doc` or `docs/source/en/tasks` are **NOT** grouped together with other files in the +same directory: the objective is to run doctest against them in independent GitHub Actions jobs. + +Assume we are under `transformers` root directory: +To get a map (dictionary) between directory (or file) paths and the corresponding files +```bash +python utils/split_doctest_jobs.py +``` +or to get a list of lists of directory (or file) paths +```bash +python utils/split_doctest_jobs.py --only_return_keys --num_splits 4 +``` +(this is used to allow GitHub Actions to generate more than 256 jobs using matrix) +""" + +import argparse +from collections import defaultdict +from pathlib import Path + +from tests_fetcher import get_all_doctest_files + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--only_return_keys", + action="store_true", + help="if to only return the keys (which is a list of list of files' directory or file paths).", + ) + parser.add_argument( + "--num_splits", + type=int, + default=1, + 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`.", + ) + args = parser.parse_args() + + all_doctest_files = get_all_doctest_files() + + raw_test_collection_map = defaultdict(list) + + for file in all_doctest_files: + file_dir = "/".join(Path(file).parents[0].parts) + raw_test_collection_map[file_dir].append(file) + + refined_test_collection_map = {} + for file_dir in raw_test_collection_map.keys(): + if file_dir in ["docs/source/en/model_doc", "docs/source/en/tasks"]: + for file in raw_test_collection_map[file_dir]: + refined_test_collection_map[file] = file + else: + refined_test_collection_map[file_dir] = " ".join(sorted(raw_test_collection_map[file_dir])) + + sorted_file_dirs = sorted(refined_test_collection_map.keys()) + + test_collection_map = {} + for file_dir in sorted_file_dirs: + test_collection_map[file_dir] = refined_test_collection_map[file_dir] + + num_jobs = len(test_collection_map) + num_jobs_per_splits = num_jobs // args.num_splits + + file_directory_splits = [] + end = 0 + for idx in range(args.num_splits): + start = end + end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0) + file_directory_splits.append(sorted_file_dirs[start:end]) + + if args.only_return_keys: + print(file_directory_splits) + else: + print(dict(test_collection_map)) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/split_model_tests.py b/tasks/tasksmith-441eeab80047/environment/source/utils/split_model_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..e5083aaeb46fa5bbbb7cf7e997423b0dfa40e53c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/split_model_tests.py @@ -0,0 +1,65 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This script is used to get the list of folders under `tests/models` and split the list into `NUM_SLICES` splits. +The main use case is a GitHub Actions workflow file calling this script to get the (nested) list of folders allowing it +to split the list of jobs to run into multiple slices each containing a smaller number of jobs. This way, we can bypass +the maximum of 256 jobs in a matrix. + +See the `setup` and `run_models_gpu` jobs defined in the workflow file `.github/workflows/self-scheduled.yml` for more +details. + +Usage: + +This script is required to be run under `tests` folder of `transformers` root directory. + +Assume we are under `transformers` root directory: +```bash +cd tests +python ../utils/split_model_tests.py --num_splits 64 +``` +""" + +import argparse +import os + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--num_splits", + type=int, + default=1, + help="the number of splits into which the (flat) list of folders will be split.", + ) + args = parser.parse_args() + + tests = os.getcwd() + model_tests = os.listdir(os.path.join(tests, "models")) + d1 = sorted(filter(os.path.isdir, os.listdir(tests))) + d2 = sorted(filter(os.path.isdir, [f"models/{x}" for x in model_tests])) + d1.remove("models") + d = d2 + d1 + + num_jobs = len(d) + num_jobs_per_splits = num_jobs // args.num_splits + + model_splits = [] + end = 0 + for idx in range(args.num_splits): + start = end + end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0) + model_splits.append(d[start:end]) + print(model_splits) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/__init__.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_configuration.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..676486fc517132d5ceb6eb69fb15fac2de2a03c8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_configuration.py @@ -0,0 +1,16 @@ +from transformers import PretrainedConfig + + +class CustomConfig(PretrainedConfig): + model_type = "custom" + + def __init__(self, attribute=1, **kwargs): + self.attribute = attribute + super().__init__(**kwargs) + + +class NoSuperInitConfig(PretrainedConfig): + model_type = "custom" + + def __init__(self, attribute=1, **kwargs): + self.attribute = attribute diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_feature_extraction.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..de367032d8fe8e73fc1b5f3d281eb21506af7b66 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_feature_extraction.py @@ -0,0 +1,5 @@ +from transformers import Wav2Vec2FeatureExtractor + + +class CustomFeatureExtractor(Wav2Vec2FeatureExtractor): + pass diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_image_processing.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_image_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..e4984854adc600678c12c156bac7264c481952e0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_image_processing.py @@ -0,0 +1,5 @@ +from transformers import CLIPImageProcessor + + +class CustomImageProcessor(CLIPImageProcessor): + pass diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_modeling.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..4b64b4a3df770346c3a5532fa290aa971af7133e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_modeling.py @@ -0,0 +1,33 @@ +import torch + +from transformers import PreTrainedModel + +from .custom_configuration import CustomConfig, NoSuperInitConfig + + +class CustomModel(PreTrainedModel): + config_class = CustomConfig + + def __init__(self, config): + super().__init__(config) + self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size) + + def forward(self, x): + return self.linear(x) + + def _init_weights(self, module): + pass + + +class NoSuperInitModel(PreTrainedModel): + config_class = NoSuperInitConfig + + def __init__(self, config): + super().__init__(config) + self.linear = torch.nn.Linear(config.attribute, config.attribute) + + def forward(self, x): + return self.linear(x) + + def _init_weights(self, module): + pass diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_pipeline.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7928b1ccd145fb8ea51c32554dc0b19567ce0c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_pipeline.py @@ -0,0 +1,33 @@ +import numpy as np + +from transformers import Pipeline + + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_processing.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..196fc511b65b3bd589a5456a965b630f2c8be91b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_processing.py @@ -0,0 +1,6 @@ +from transformers import ProcessorMixin + + +class CustomProcessor(ProcessorMixin): + feature_extractor_class = "AutoFeatureExtractor" + tokenizer_class = "AutoTokenizer" diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..d67b1373041e7c8b6682300cf507ffbaa0143211 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization.py @@ -0,0 +1,5 @@ +from transformers import BertTokenizer + + +class CustomTokenizer(BertTokenizer): + pass diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization_fast.py b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..ace94fdd1a5d1a726c3840db2b66e4f0a053e05c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization_fast.py @@ -0,0 +1,8 @@ +from transformers import BertTokenizerFast + +from .custom_tokenization import CustomTokenizer + + +class CustomTokenizerFast(BertTokenizerFast): + slow_tokenizer_class = CustomTokenizer + pass diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/tests_fetcher.py b/tasks/tasksmith-441eeab80047/environment/source/utils/tests_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..40749044260823491a55643b46d1b3a63b9accf0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/tests_fetcher.py @@ -0,0 +1,1255 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Welcome to tests_fetcher V2. + +This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and +when too many models are being impacted, only run the tests of a subset of core models. It works like this. + +Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit. +On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not +just the last commit) but excludes modifications that are on docstrings or comments only. + +Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A +imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the +dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests +impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules). + +Caveats: + - This module only filters tests by files (not individual tests) so it's better to have tests for different things + in different files. + - This module assumes inits are just importing things, not really building objects, so it's better to structure + them this way and move objects building in separate submodules. + +Usage: + +Base use to fetch the tests in a pull request + +```bash +python utils/tests_fetcher.py +``` + +Base use to fetch the tests on a the main branch (with diff from the last commit): + +```bash +python utils/tests_fetcher.py --diff_with_last_commit +``` +""" + +import argparse +import collections +import glob +import importlib.util +import json +import os +import re +import tempfile +from contextlib import contextmanager +from pathlib import Path +from typing import Dict, List, Tuple, Union + +from git import Repo + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +PATH_TO_EXAMPLES = PATH_TO_REPO / "examples" +PATH_TO_TRANFORMERS = PATH_TO_REPO / "src/transformers" +PATH_TO_TESTS = PATH_TO_REPO / "tests" + +# The value is just a heuristic to determine if we `guess` all models are impacted. +# This variable has effect only if `filter_models=False`. +NUM_MODELS_TO_TRIGGER_FULL_CI = 30 + +# List here the models to always test. +IMPORTANT_MODELS = [ + "auto", + # Most downloaded models + "bert", + "clip", + "t5", + "xlm-roberta", + "gpt2", + "bart", + "mpnet", + "gpt-j", + "wav2vec2", + "deberta-v2", + "layoutlm", + "llama", + "opt", + "longformer", + "vit", + "whisper", + # Pipeline-specific model (to be sure each pipeline has one model in this list) + "tapas", + "vilt", + "clap", + "detr", + "owlvit", + "dpt", + "videomae", +] + + +@contextmanager +def checkout_commit(repo: Repo, commit_id: str): + """ + Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + commit_id (`str`): The commit reference to checkout inside the context manager. + """ + current_head = repo.head.commit if repo.head.is_detached else repo.head.ref + + try: + repo.git.checkout(commit_id) + yield + + finally: + repo.git.checkout(current_head) + + +def clean_code(content: str) -> str: + """ + Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern + comments or docstings). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or + # this would mess up the result if this function applied to this particular file). + # fmt: off + # Remove docstrings by splitting on triple " then triple ': + splits = content.split('\"\"\"') + content = "".join(splits[::2]) + splits = content.split("\'\'\'") + # fmt: on + content = "".join(splits[::2]) + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def keep_doc_examples_only(content: str) -> str: + """ + Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc + tests or not). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # Keep doc examples only by splitting on triple "`" + splits = content.split("```") + # Add leading and trailing "```" so the navigation is easier when compared to the original input `content` + content = "```" + "```".join(splits[1::2]) + "```" + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def get_all_tests() -> List[str]: + """ + Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using + paralellism. The split is: + + - folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded. + - folders under `tests/models`: `bert`, `gpt2`, etc. + - test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc. + """ + + # test folders/files directly under `tests` folder + tests = os.listdir(PATH_TO_TESTS) + tests = [f"tests/{f}" for f in tests if "__pycache__" not in f] + tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")]) + + # model specific test folders + model_test_folders = os.listdir(PATH_TO_TESTS / "models") + model_test_folders = [f"tests/models/{f}" for f in model_test_folders if "__pycache__" not in f] + model_test_folders = sorted([f for f in model_test_folders if (PATH_TO_REPO / f).is_dir()]) + + tests.remove("tests/models") + # Sagemaker tests are not meant to be run on the CI. + if "tests/sagemaker" in tests: + tests.remove("tests/sagemaker") + tests = model_test_folders + tests + + return tests + + +def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in docstrings (or comments and whitespace) in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments. + + Returns: + `bool`: Whether the diff is docstring/comments only or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = clean_code(old_content) + new_content_clean = clean_code(new_content) + + return old_content_clean == new_content_clean + + +def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in code examples of the doc in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff is only in codes examples. + + Returns: + `bool`: Whether the diff is only in code examples of the doc or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = keep_doc_examples_only(old_content) + new_content_clean = keep_doc_examples_only(new_content) + + return old_content_clean != new_content_clean + + +def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python modeling files that are impacted by the changes of `tiny_model_summary.json`. + """ + repo = Repo(PATH_TO_REPO) + + folder = Path(repo.working_dir) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + commits = repo.merge_base(repo.refs.main, repo.head) + for commit in commits: + print(f"Branching commit: {commit}") + else: + print(f"main is at {repo.head.commit}") + commits = repo.head.commit.parents + for commit in commits: + print(f"Parent commit: {commit}") + + if not os.path.isfile(folder / "tests/utils/tiny_model_summary.json"): + return [] + + files = set() + for commit in commits: + with checkout_commit(repo, commit): + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + new_content = f.read() + + # get the content as json object + old_content = json.loads(old_content) + new_content = json.loads(new_content) + + old_keys = set(old_content.keys()) + new_keys = set(new_content.keys()) + + # get the difference + keys_with_diff = old_keys.symmetric_difference(new_keys) + common_keys = old_keys.intersection(new_keys) + # if both have the same key, check its content + for key in common_keys: + if old_content[key] != new_content[key]: + keys_with_diff.add(key) + + # get the model classes + impacted_model_classes = [] + for key in keys_with_diff: + if key in new_keys: + impacted_model_classes.extend(new_content[key]["model_classes"]) + + # get the module where the model classes are defined. We want to use the main `__init__` file, but it requires + # all the framework being installed, which is not ideal for a simple script like test fetcher. + # So we create a temporary and modified main `__init__` and access its `_import_structure`. + with open(folder / "src/transformers/__init__.py") as fp: + lines = fp.readlines() + new_lines = [] + # Get all the code related to `_import_structure` + for line in lines: + if line == "_import_structure = {\n": + new_lines.append(line) + elif line == "# Direct imports for type-checking\n": + break + elif len(new_lines) > 0: + # bypass the framework check so we can get all the information even if frameworks are not available + line = re.sub(r"is_.+_available\(\)", "True", line) + line = line.replace("OptionalDependencyNotAvailable", "Exception") + line = line.replace("Exception()", "Exception") + new_lines.append(line) + + # create and load the temporary module + with tempfile.TemporaryDirectory() as tmpdirname: + with open(os.path.join(tmpdirname, "temp_init.py"), "w") as fp: + fp.write("".join(new_lines)) + + spec = importlib.util.spec_from_file_location("temp_init", os.path.join(tmpdirname, "temp_init.py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + # Finally, get `_import_structure` that we need + import_structure = module._import_structure + + # map model classes to their defined module + reversed_structure = {} + for key, values in import_structure.items(): + for value in values: + reversed_structure[value] = key + + # Get the corresponding modeling file path + for model_class in impacted_model_classes: + module = reversed_structure[model_class] + framework = "" + if model_class.startswith("TF"): + framework = "tf" + elif model_class.startswith("Flax"): + framework = "flax" + fn = ( + f"modeling_{module.split('.')[-1]}.py" + if framework == "" + else f"modeling_{framework}_{module.split('.')[-1]}.py" + ) + files.add( + f"src.transformers.{module}.{fn}".replace(".", os.path.sep).replace(f"{os.path.sep}py", ".py") + ) + + return sorted(files) + + +def get_diff(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: + """ + Get the diff between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We always add new python files + if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): + code_diff.append(diff_obj.b_path) + # We check that deleted python files won't break corresponding tests. + elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"): + code_diff.append(diff_obj.a_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"): + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications are in code and not docstrings. + if diff_is_docstring_only(repo, commit, diff_obj.b_path): + print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.") + else: + code_diff.append(diff_obj.a_path) + + return code_diff + + +def get_modified_python_files(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python files that have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + repo = Repo(PATH_TO_REPO) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + return get_diff(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + return get_diff(repo, repo.head.commit, parent_commits) + + +def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: + """ + Get the diff in doc examples between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We only consider Python files and doc files. + if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"): + continue + # We always add new python/md files + if diff_obj.change_type in ["A"]: + code_diff.append(diff_obj.b_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"]: + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications contain some doc example(s). + if diff_contains_doc_examples(repo, commit, diff_obj.b_path): + code_diff.append(diff_obj.a_path) + else: + print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.") + + return code_diff + + +def get_all_doctest_files() -> List[str]: + """ + Return the complete list of python and Markdown files on which we run doctest. + + At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`. + + Returns: + `List[str]`: The complete list of Python and Markdown files on which we run doctest. + """ + py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")] + md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")] + + test_files_to_run = py_files + md_files + # change to use "/" as path separator + test_files_to_run = ["/".join(Path(x).parts) for x in test_files_to_run] + # don't run doctest for files in `src/transformers/models/deprecated` + test_files_to_run = [x for x in test_files_to_run if "models/deprecated" not in x] + + # only include files in `src` or `docs/source/en/` + test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))] + # not include init files + test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))] + + # These are files not doctested yet. + with open("utils/not_doctested.txt") as fp: + not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")} + + # So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%. + test_files_to_run = [x for x in test_files_to_run if x not in not_doctested] + + return sorted(test_files_to_run) + + +def get_new_doctest_files(repo, base_commit, branching_commit) -> List[str]: + """ + Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and + `branching_commit`. + + Returns: + `List[str]`: List of files that were removed from "utils/not_doctested.txt". + """ + for diff_obj in branching_commit.diff(base_commit): + # Ignores all but the "utils/not_doctested.txt" file. + if diff_obj.a_path != "utils/not_doctested.txt": + continue + # Loads the two versions + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_commit): + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + old_content = f.read() + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + new_content = f.read() + # Compute the removed lines and return them + removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - { + x.split(" ")[0] for x in new_content.split("\n") + } + return sorted(removed_content) + return [] + + +def get_doctest_files(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python and Markdown files where doc example have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + repo = Repo(PATH_TO_REPO) + + test_files_to_run = [] # noqa + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits) + + all_test_files_to_run = get_all_doctest_files() + + # Add to the test files to run any removed entry from "utils/not_doctested.txt". + new_test_files = get_new_doctest_files(repo, repo.head.commit, repo.refs.main.commit) + test_files_to_run = list(set(test_files_to_run + new_test_files)) + + # Do not run slow doctest tests on CircleCI + with open("utils/slow_documentation_tests.txt") as fp: + slow_documentation_tests = set(fp.read().strip().split("\n")) + test_files_to_run = [ + x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests + ] + + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + return sorted(test_files_to_run) + + +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy +# (?=\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 +# other import. +_re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy +# yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch +# .xxx and yyy +# (?=\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 +# other import. +_re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we +# catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\)") + + +def extract_imports(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: + """ + Get the imports a given module makes. + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that + is a subfolder will give its init file). + """ + if cache is not None and module_fname in cache: + return cache[module_fname] + + with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f: + content = f.read() + + # Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to + # keep this as escaped quotes and avoid this function failing on this file. + splits = content.split('\"\"\"') # fmt: skip + content = "".join(splits[::2]) + + module_parts = str(module_fname).split(os.path.sep) + imported_modules = [] + + # Let's start with relative imports + relative_imports = _re_single_line_relative_imports.findall(content) + relative_imports = [ + (mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "(" + ] + multiline_relative_imports = _re_multi_line_relative_imports.findall(content) + relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp] + + # We need to remove parts of the module name depending on the depth of the relative imports. + for module, imports in relative_imports: + level = 0 + while module.startswith("."): + module = module[1:] + level += 1 + + if len(module) > 0: + dep_parts = module_parts[: len(module_parts) - level] + module.split(".") + else: + dep_parts = module_parts[: len(module_parts) - level] + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + # Let's continue with direct imports + direct_imports = _re_single_line_direct_imports.findall(content) + direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("] + multiline_direct_imports = _re_multi_line_direct_imports.findall(content) + direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp] + + # We need to find the relative path of those imports. + for module, imports in direct_imports: + import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below. + dep_parts = ["src", "transformers"] + import_parts + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + result = [] + # Double check we get proper modules (either a python file or a folder with an init). + for module_file, imports in imported_modules: + if (PATH_TO_REPO / f"{module_file}.py").is_file(): + module_file = f"{module_file}.py" + elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file(): + module_file = os.path.sep.join([module_file, "__init__.py"]) + imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)] + if len(imports) > 0: + result.append((module_file, imports)) + + if cache is not None: + cache[module_fname] = result + + return result + + +def get_module_dependencies(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: + """ + Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file + as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse + the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py. + + Warning: This presupposes that all intermediate inits are properly built (with imports from the respective + submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the + intermediate init is added, and inits usually have a lot of dependencies). + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined). + """ + dependencies = [] + imported_modules = extract_imports(module_fname, cache=cache) + # The while loop is to recursively traverse all inits we may encounter: we will add things as we go. + while len(imported_modules) > 0: + new_modules = [] + for module, imports in imported_modules: + if "models" in module.split("/") and module.split("/")[-1].startswith("convert_"): + continue + # If we end up in an __init__ we are often not actually importing from this init (except in the case where + # the object is fully defined in the __init__) + if module.endswith("__init__.py"): + # So we get the imports from that init then try to find where our objects come from. + new_imported_modules = extract_imports(module, cache=cache) + + # Add imports via `define_import_structure` after the #35167 as we remove explicit import in `__init__.py` + from transformers.utils.import_utils import define_import_structure + + new_imported_modules_2 = define_import_structure(PATH_TO_REPO / module) + + for mapping in new_imported_modules_2.values(): + for _module, _imports in mapping.items(): + _module = module.replace("__init__.py", f"{_module}.py") + new_imported_modules.append((_module, list(_imports))) + + for new_module, new_imports in new_imported_modules: + if any(i in new_imports for i in imports): + if new_module not in dependencies: + new_modules.append((new_module, [i for i in new_imports if i in imports])) + imports = [i for i in imports if i not in new_imports] + + if len(imports) > 0: + # If there are any objects lefts, they may be a submodule + path_to_module = PATH_TO_REPO / module.replace("__init__.py", "") + dependencies.extend( + [ + os.path.join(module.replace("__init__.py", ""), f"{i}.py") + for i in imports + if (path_to_module / f"{i}.py").is_file() + ] + ) + imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()] + if len(imports) > 0: + # Then if there are still objects left, they are fully defined in the init, so we keep it as a + # dependency. + dependencies.append(module) + else: + dependencies.append(module) + + imported_modules = new_modules + + return dependencies + + +def create_reverse_dependency_tree() -> List[Tuple[str, str]]: + """ + Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files. + """ + cache = {} + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))] + all_modules += list(PATH_TO_TESTS.glob("**/*.py")) + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)] + + return list(set(edges)) + + +def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]: + """ + Returns the tree starting at a given module following all edges. + + Args: + module (`str`): The module that will be the root of the subtree we want. + eges (`List[Tuple[str, str]]`): The list of all edges of the tree. + + Returns: + `List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges + starting at module], [list of edges starting at the preceding level], ...] + """ + vertices_seen = [module] + new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]] + tree = [module] + while len(new_edges) > 0: + tree.append(new_edges) + final_vertices = list({edge[1] for edge in new_edges}) + vertices_seen.extend(final_vertices) + new_edges = [ + edge + for edge in edges + if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1] + ] + + return tree + + +def print_tree_deps_of(module, all_edges=None): + """ + Prints the tree of modules depending on a given module. + + Args: + module (`str`): The module that will be the root of the subtree we want. + all_eges (`List[Tuple[str, str]]`, *optional*): + The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed. + """ + if all_edges is None: + all_edges = create_reverse_dependency_tree() + tree = get_tree_starting_at(module, all_edges) + + # The list of lines is a list of tuples (line_to_be_printed, module) + # Keeping the modules lets us know where to insert each new lines in the list. + lines = [(tree[0], tree[0])] + for index in range(1, len(tree)): + edges = tree[index] + start_edges = {edge[0] for edge in edges} + + for start in start_edges: + end_edges = {edge[1] for edge in edges if edge[0] == start} + # We will insert all those edges just after the line showing start. + pos = 0 + while lines[pos][1] != start: + pos += 1 + lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :] + + for line in lines: + # We don't print the refs that where just here to help build lines. + print(line[0]) + + +def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]: + """ + The test examples do not import from the examples (which are just scripts, not modules) so we need som extra + care initializing the dependency map, which is the goal of this function. It initializes the dependency map for + example files by linking each example to the example test file for the example framework. + + Returns: + `Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a + dict test example file to list of example files potentially tested by that test file, and the list of all + example files (to avoid recomputing it later). + """ + test_example_deps = {} + all_examples = [] + for framework in ["flax", "pytorch", "tensorflow"]: + test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py")) + all_examples.extend(test_files) + # Remove the files at the root of examples/framework since they are not proper examples (they are eith utils + # or example test files). + examples = [ + f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework + ] + all_examples.extend(examples) + for test_file in test_files: + with open(test_file, "r", encoding="utf-8") as f: + content = f.read() + # Map all examples to the test files found in examples/framework. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [ + str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content + ] + # Also map the test files to themselves. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append( + str(test_file.relative_to(PATH_TO_REPO)) + ) + return test_example_deps, all_examples + + +def create_reverse_dependency_map() -> Dict[str, List[str]]: + """ + Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively. + + Returns: + `Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames + depending on it recursively. This way the tests impacted by a change in file A are the test files in the list + corresponding to key A in this result. + """ + + cache = {} + # Start from the example deps init. + example_deps, examples = init_test_examples_dependencies() + # Add all modules and all tests to all examples + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))] + all_modules += list(PATH_TO_TESTS.glob("**/*.py")) + examples + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + # Compute the direct dependencies of all modules. + direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} + direct_deps.update(example_deps) + + # This recurses the dependencies + something_changed = True + while something_changed: + something_changed = False + for m in all_modules: + for d in direct_deps[m]: + # We stop recursing at an init (cause we always end up in the main init and we don't want to add all + # files which the main init imports) + if d.endswith("__init__.py"): + continue + if d not in direct_deps: + raise ValueError(f"KeyError:{d}. From {m}") + new_deps = set(direct_deps[d]) - set(direct_deps[m]) + if len(new_deps) > 0: + direct_deps[m].extend(list(new_deps)) + something_changed = True + + # Finally we can build the reverse map. + reverse_map = collections.defaultdict(list) + for m in all_modules: + for d in direct_deps[m]: + reverse_map[d].append(m) + + # For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test + # all the modules impacted by that init. + for m in [f for f in all_modules if f.endswith("__init__.py")]: + direct_deps = get_module_dependencies(m, cache=cache) + deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps) + reverse_map[m] = list(set(deps) - {m}) + + return reverse_map + + +def create_module_to_test_map( + reverse_map: Dict[str, List[str]] = None, filter_models: bool = False +) -> Dict[str, List[str]]: + """ + Extract the tests from the reverse_dependency_map and potentially filters the model tests. + + Args: + reverse_map (`Dict[str, List[str]]`, *optional*): + The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of + that function if not provided. + filter_models (`bool`, *optional*, defaults to `False`): + Whether or not to filter model tests to only include core models if a file impacts a lot of models. + + Returns: + `Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified. + """ + if reverse_map is None: + reverse_map = create_reverse_dependency_map() + + # Utility that tells us if a given file is a test (taking test examples into account) + def is_test(fname): + if fname.startswith("tests"): + return True + if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"): + return True + return False + + # Build the test map + test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()} + + if not filter_models: + return test_map + + # Now we deal with the filtering if `filter_models` is True. + num_model_tests = len(list(PATH_TO_TESTS.glob("models/*"))) + + def has_many_models(tests): + # We filter to core models when a given file impacts more than half the model tests. + model_tests = {Path(t).parts[2] for t in tests if t.startswith("tests/models/")} + return len(model_tests) > num_model_tests // 2 + + # for each module (if specified in the argument `module`) of the form `models/my_model` (i.e. starting with it), + # we always keep the tests (those are already in the argument `tests`) which are in `tests/models/my_model`. + # This is to avoid them being excluded when a module has many impacted tests: the directly related test files should + # always be included! + def filter_tests(tests, module=""): + filtered_tests = [] + for t in tests: + if ( + not t.startswith("tests/models/") + or Path(t).parts[2] in IMPORTANT_MODELS + # at this point, `t` is of the form `tests/models/my_model`, and we check if `models/my_model` + # (i.e. `parts[1:3]`) is in `module`. + or "/".join(Path(t).parts[1:3]) in module + ): + filtered_tests += [t] + return filtered_tests + + return { + module: (filter_tests(tests, module=module) if has_many_models(tests) else tests) + for module, tests in test_map.items() + } + + +def _print_list(l) -> str: + """ + Pretty print a list of elements with one line per element and a - starting each line. + """ + return "\n".join([f"- {f}" for f in l]) + + +def infer_tests_to_run( + output_file: str, diff_with_last_commit: bool = False, filter_models: bool = False, test_all: bool = False +): + """ + The main function called by the test fetcher. Determines the tests to run from the diff. + + Args: + output_file (`str`): + The path where to store the summary of the test fetcher analysis. Other files will be stored in the same + folder: + + - examples_test_list.txt: The list of examples tests to run. + - test_repo_utils.txt: Will indicate if the repo utils tests should be run or not. + - doctest_list.txt: The list of doctests to run. + + diff_with_last_commit (`bool`, *optional*, defaults to `False`): + Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with + the branching point from main (for use on each PR). + filter_models (`bool`, *optional*, defaults to `True`): + Whether or not to filter the tests to core models only, when a file modified results in a lot of model + tests. + """ + if not test_all: + modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit) + else: + modified_files = [str(k) for k in PATH_TO_TESTS.glob("*/*") if str(k).endswith(".py") and "test_" in str(k)] + print("\n### test_all is TRUE, FETCHING ALL FILES###\n") + print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}") + + # Create the map that will give us all impacted modules. + reverse_map = create_reverse_dependency_map() + impacted_files = modified_files.copy() + for f in modified_files: + if f in reverse_map: + impacted_files.extend(reverse_map[f]) + + # Remove duplicates + impacted_files = sorted(set(impacted_files)) + print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}") + + model_impacted = {"/".join(x.split("/")[:3]) for x in impacted_files if x.startswith("tests/models/")} + # Grab the corresponding test files: + if ( + any(x in modified_files for x in ["setup.py", ".circleci/create_circleci_config.py"]) + or not filter_models + and len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI + or commit_flags["test_all"] + ): + test_files_to_run = glob.glob("tests/**/test_**.py", recursive=True) + glob.glob( + "examples/**/*.py", recursive=True + ) + if len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI and filter_models: + print( + f"More than {NUM_MODELS_TO_TRIGGER_FULL_CI - 1} models are impacted and `filter_models=False`. CI is configured to test everything." + ) + else: + # All modified tests need to be run. + test_files_to_run = [f for f in modified_files if f.startswith("tests") and "/test_" in f] + impacted_files = get_impacted_files_from_tiny_model_summary(diff_with_last_commit=diff_with_last_commit) + + # Then we grab the corresponding test files. + test_map = create_module_to_test_map(reverse_map=reverse_map, filter_models=filter_models) + for f in modified_files + impacted_files: + if f in test_map: + test_files_to_run.extend(test_map[f]) + test_files_to_run = sorted(set(test_files_to_run)) + # Remove repo utils tests + test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "repo_utils"] + # Remove SageMaker tests + test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "sagemaker"] + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}") + + create_test_list_from_filter(test_files_to_run, out_path="test_preparation/") + + doctest_list = get_doctest_files() + + print(f"\n### DOCTEST TO RUN ###\n{_print_list(doctest_list)}") + if len(doctest_list) > 0: + doctest_file = Path(output_file).parent / "doctest_list.txt" + with open(doctest_file, "w", encoding="utf-8") as f: + f.write(" ".join(doctest_list)) + + +def filter_tests(output_file: str, filters: List[str]): + """ + Reads the content of the output file and filters out all the tests in a list of given folders. + + Args: + output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher. + filters (`List[str]`): A list of folders to filter. + """ + if not os.path.isfile(output_file): + print("No test file found.") + return + with open(output_file, "r", encoding="utf-8") as f: + test_files = f.read().split(" ") + + if len(test_files) == 0 or test_files == [""]: + print("No tests to filter.") + return + + if test_files == ["tests"]: + test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters] + else: + test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters] + + with open(output_file, "w", encoding="utf-8") as f: + f.write(" ".join(test_files)) + + +def parse_commit_message(commit_message: str) -> Dict[str, bool]: + """ + Parses the commit message to detect if a command is there to skip, force all or part of the CI. + + Args: + commit_message (`str`): The commit message of the current commit. + + Returns: + `Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`, + `"test_all_models"` and `"test_all"`. + """ + if commit_message is None: + return {"skip": False, "no_filter": False, "test_all": False} + + command_search = re.search(r"\[([^\]]*)\]", commit_message) + if command_search is not None: + command = command_search.groups()[0] + command = command.lower().replace("-", " ").replace("_", " ") + skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"] + no_filter = set(command.split(" ")) == {"no", "filter"} + test_all = set(command.split(" ")) == {"test", "all"} + return {"skip": skip, "no_filter": no_filter, "test_all": test_all} + else: + return {"skip": False, "no_filter": False, "test_all": False} + + +JOB_TO_TEST_FILE = { + "tests_tf": r"tests/models/.*/test_modeling_tf_.*", + "tests_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_generate": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_tokenization": r"tests/models/.*/test_tokenization.*", + "tests_processors": r"tests/models/.*/test_(?!(?:modeling_|tokenization_)).*", # takes feature extractors, image processors, processors + "examples_torch": r"examples/pytorch/.*test_.*", + "examples_tensorflow": r"examples/tensorflow/.*test_.*", + "tests_exotic_models": r"tests/models/.*(?=layoutlmv|nat|deta|udop|nougat).*", + "tests_custom_tokenizers": r"tests/models/.*/test_tokenization_(?=bert_japanese|openai|clip).*", + # "repo_utils": r"tests/[^models].*test.*", TODO later on we might want to do + "pipelines_tf": r"tests/models/.*/test_modeling_tf_.*", + "pipelines_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_hub": r"tests/.*", + "tests_onnx": r"tests/models/.*/test_modeling_(?:tf_|(?!flax)).*", + "tests_non_model": r"tests/[^/]*?/test_.*\.py", +} + + +def create_test_list_from_filter(full_test_list, out_path): + os.makedirs(out_path, exist_ok=True) + all_test_files = "\n".join(full_test_list) + for job_name, _filter in JOB_TO_TEST_FILE.items(): + file_name = os.path.join(out_path, f"{job_name}_test_list.txt") + if job_name == "tests_hub": + files_to_test = ["tests"] + else: + files_to_test = list(re.findall(_filter, all_test_files)) + print(job_name, file_name) + if len(files_to_test) > 0: # No tests -> no file with test list + with open(file_name, "w") as f: + f.write("\n".join(files_to_test)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run" + ) + parser.add_argument( + "--json_output_file", + type=str, + default="test_map.json", + help="Where to store the tests to run in a dictionary format mapping test categories to test files", + ) + parser.add_argument( + "--diff_with_last_commit", + action="store_true", + help="To fetch the tests between the current commit and the last commit", + ) + parser.add_argument( + "--filter_tests", + action="store_true", + help="Will filter the pipeline/repo utils tests outside of the generated list of tests.", + ) + parser.add_argument( + "--print_dependencies_of", + type=str, + help="Will only print the tree of modules depending on the file passed.", + default=None, + ) + parser.add_argument( + "--fetch_all", + action="store_true", + help="Will fetch all tests.", + default=None, + ) + args = parser.parse_args() + if args.print_dependencies_of is not None: + print_tree_deps_of(args.print_dependencies_of) + elif args.filter_tests: + filter_tests(args.output_file, ["pipelines", "repo_utils"]) + else: + repo = Repo(PATH_TO_REPO) + commit_message = repo.head.commit.message + commit_flags = parse_commit_message(commit_message) + if commit_flags["skip"]: + print("Force-skipping the CI") + quit() + if commit_flags["no_filter"]: + print("Running all tests fetched without filtering.") + + if args.fetch_all: + commit_flags["test_all"] = True + if commit_flags["test_all"]: + print("Force-launching all tests") + + is_main_branch = not repo.head.is_detached and repo.head.ref == repo.refs.main + diff_with_last_commit = args.diff_with_last_commit + if not diff_with_last_commit and is_main_branch: + print("main branch detected, fetching tests against last commit.") + diff_with_last_commit = True + + infer_tests_to_run( + args.output_file, + diff_with_last_commit=diff_with_last_commit, + filter_models=False, + test_all=commit_flags["test_all"], + ) + filter_tests(args.output_file, ["repo_utils"]) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/tf_ops/onnx.json b/tasks/tasksmith-441eeab80047/environment/source/utils/tf_ops/onnx.json new file mode 100644 index 0000000000000000000000000000000000000000..a468145d66eb541bd39ef57d25be6263500491d7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/tf_ops/onnx.json @@ -0,0 +1,245 @@ +{ + "opsets": { + "1": [ + "Abs", + "Add", + "AddV2", + "ArgMax", + "ArgMin", + "AvgPool", + "AvgPool3D", + "BatchMatMul", + "BatchMatMulV2", + "BatchToSpaceND", + "BiasAdd", + "BiasAddV1", + "Cast", + "Ceil", + "CheckNumerics", + "ComplexAbs", + "Concat", + "ConcatV2", + "Const", + "ConstV2", + "Conv1D", + "Conv2D", + "Conv2DBackpropInput", + "Conv3D", + "Conv3DBackpropInputV2", + "DepthToSpace", + "DepthwiseConv2d", + "DepthwiseConv2dNative", + "Div", + "Dropout", + "Elu", + "Equal", + "Erf", + "Exp", + "ExpandDims", + "Flatten", + "Floor", + "Gather", + "GatherNd", + "GatherV2", + "Greater", + "Identity", + "IdentityN", + "If", + "LRN", + "LSTMBlockCell", + "LeakyRelu", + "Less", + "Log", + "LogSoftmax", + "LogicalAnd", + "LogicalNot", + "LogicalOr", + "LookupTableSizeV2", + "MatMul", + "Max", + "MaxPool", + "MaxPool3D", + "MaxPoolV2", + "Maximum", + "Mean", + "Min", + "Minimum", + "MirrorPad", + "Mul", + "Neg", + "NoOp", + "NotEqual", + "OneHot", + "Pack", + "Pad", + "PadV2", + "Placeholder", + "PlaceholderV2", + "PlaceholderWithDefault", + "Pow", + "Prod", + "RFFT", + "RandomNormal", + "RandomNormalLike", + "RandomUniform", + "RandomUniformLike", + "RealDiv", + "Reciprocal", + "Relu", + "Relu6", + "Reshape", + "Rsqrt", + "Selu", + "Shape", + "Sigmoid", + "Sign", + "Size", + "Slice", + "Softmax", + "Softplus", + "Softsign", + "SpaceToBatchND", + "SpaceToDepth", + "Split", + "SplitV", + "Sqrt", + "Square", + "SquaredDifference", + "Squeeze", + "StatelessIf", + "StopGradient", + "StridedSlice", + "StringJoin", + "Sub", + "Sum", + "Tanh", + "Tile", + "TopKV2", + "Transpose", + "TruncateDiv", + "Unpack", + "ZerosLike" + ], + "2": [], + "3": [], + "4": [], + "5": [], + "6": [ + "AddN", + "All", + "Any", + "FloorDiv", + "FusedBatchNorm", + "FusedBatchNormV2", + "FusedBatchNormV3" + ], + "7": [ + "Acos", + "Asin", + "Atan", + "Cos", + "Fill", + "FloorMod", + "GreaterEqual", + "LessEqual", + "Loop", + "MatrixBandPart", + "Multinomial", + "Range", + "ResizeBilinear", + "ResizeNearestNeighbor", + "Scan", + "Select", + "SelectV2", + "Sin", + "SoftmaxCrossEntropyWithLogits", + "SparseSoftmaxCrossEntropyWithLogits", + "StatelessWhile", + "Tan", + "TensorListFromTensor", + "TensorListGetItem", + "TensorListLength", + "TensorListReserve", + "TensorListResize", + "TensorListSetItem", + "TensorListStack", + "While" + ], + "8": [ + "BroadcastTo", + "ClipByValue", + "FIFOQueueV2", + "HashTableV2", + "IteratorGetNext", + "IteratorV2", + "LookupTableFindV2", + "MaxPoolWithArgmax", + "QueueDequeueManyV2", + "QueueDequeueUpToV2", + "QueueDequeueV2", + "ReverseSequence" + ], + "9": [ + "SegmentMax", + "SegmentMean", + "SegmentMin", + "SegmentProd", + "SegmentSum", + "Sinh", + "SparseSegmentMean", + "SparseSegmentMeanWithNumSegments", + "SparseSegmentSqrtN", + "SparseSegmentSqrtNWithNumSegments", + "SparseSegmentSum", + "SparseSegmentSumWithNumSegments", + "UnsortedSegmentMax", + "UnsortedSegmentMin", + "UnsortedSegmentProd", + "UnsortedSegmentSum", + "Where" + ], + "10": [ + "CropAndResize", + "CudnnRNN", + "DynamicStitch", + "FakeQuantWithMinMaxArgs", + "IsFinite", + "IsInf", + "NonMaxSuppressionV2", + "NonMaxSuppressionV3", + "NonMaxSuppressionV4", + "NonMaxSuppressionV5", + "ParallelDynamicStitch", + "ReverseV2", + "Roll" + ], + "11": [ + "Bincount", + "Cumsum", + "InvertPermutation", + "LeftShift", + "MatrixDeterminant", + "MatrixDiagPart", + "MatrixDiagPartV2", + "MatrixDiagPartV3", + "RaggedRange", + "RightShift", + "Round", + "ScatterNd", + "SparseFillEmptyRows", + "SparseReshape", + "SparseToDense", + "TensorScatterUpdate", + "Unique" + ], + "12": [ + "Einsum", + "MatrixDiag", + "MatrixDiagV2", + "MatrixDiagV3", + "MatrixSetDiagV3", + "SquaredDistance" + ], + "13": [] + } +} \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/update_metadata.py b/tasks/tasksmith-441eeab80047/environment/source/utils/update_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4a7e3fe5340e292a9409932f8e71989f5a4520 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/update_metadata.py @@ -0,0 +1,372 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that updates the metadata of the Transformers library in the repository `huggingface/transformers-metadata`. + +Usage for an update (as used by the GitHub action `update_metadata`): + +```bash +python utils/update_metadata.py --token --commit_sha +``` + +Usage to check all pipelines are properly defined in the constant `PIPELINE_TAGS_AND_AUTO_MODELS` of this script, so +that new pipelines are properly added as metadata (as used in `make repo-consistency`): + +```bash +python utils/update_metadata.py --check-only +``` +""" + +import argparse +import collections +import os +import re +import tempfile +from typing import Dict, List, Tuple + +import pandas as pd +from datasets import Dataset +from huggingface_hub import hf_hub_download, upload_folder + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/update_metadata.py +TRANSFORMERS_PATH = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +# Regexes that match TF/Flax/PT model names. +_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. +_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration|ForRetrieval)") + + +# Fill this with tuples (pipeline_tag, model_mapping, auto_model) +PIPELINE_TAGS_AND_AUTO_MODELS = [ + ("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"), + ("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"), + ("image-feature-extraction", "MODEL_FOR_IMAGE_MAPPING_NAMES", "AutoModel"), + ("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"), + ("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"), + ("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"), + ("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"), + ("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"), + ("image-text-to-text", "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "AutoModelForImageTextToText"), + ("image-to-image", "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES", "AutoModelForImageToImage"), + ("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"), + ("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"), + ( + "zero-shot-object-detection", + "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", + "AutoModelForZeroShotObjectDetection", + ), + ("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"), + ("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"), + ("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"), + ("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"), + ( + "table-question-answering", + "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForTableQuestionAnswering", + ), + ("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"), + ("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"), + ( + "next-sentence-prediction", + "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", + "AutoModelForNextSentencePrediction", + ), + ( + "audio-frame-classification", + "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForAudioFrameClassification", + ), + ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), + ( + "document-question-answering", + "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForDocumentQuestionAnswering", + ), + ( + "visual-question-answering", + "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForVisualQuestionAnswering", + ), + ("image-to-text", "MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"), + ( + "zero-shot-image-classification", + "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForZeroShotImageClassification", + ), + ("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"), + ("video-classification", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForVideoClassification"), + ("mask-generation", "MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "AutoModelForMaskGeneration"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "AutoModelForTextToSpectrogram"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "AutoModelForTextToWaveform"), +] + + +def camel_case_split(identifier: str) -> List[str]: + """ + Split a camel-cased name into words. + + Args: + identifier (`str`): The camel-cased name to parse. + + Returns: + `List[str]`: The list of words in the identifier (as seprated by capital letters). + + Example: + + ```py + >>> camel_case_split("CamelCasedClass") + ["Camel", "Cased", "Class"] + ``` + """ + # Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python + matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) + return [m.group(0) for m in matches] + + +def get_frameworks_table() -> pd.DataFrame: + """ + Generates a dataframe containing the supported auto classes for each model type, using the content of the auto + modules. + """ + # Dictionary model names to config. + config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES + model_prefix_to_model_type = { + config.replace("Config", ""): model_type for model_type, config in config_maping_names.items() + } + + # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. + pt_models = collections.defaultdict(bool) + tf_models = collections.defaultdict(bool) + flax_models = collections.defaultdict(bool) + + # Let's lookup through all transformers object (once) and find if models are supported by a given backend. + for attr_name in dir(transformers_module): + lookup_dict = None + if _re_tf_models.match(attr_name) is not None: + lookup_dict = tf_models + attr_name = _re_tf_models.match(attr_name).groups()[0] + elif _re_flax_models.match(attr_name) is not None: + lookup_dict = flax_models + attr_name = _re_flax_models.match(attr_name).groups()[0] + elif _re_pt_models.match(attr_name) is not None: + lookup_dict = pt_models + attr_name = _re_pt_models.match(attr_name).groups()[0] + + if lookup_dict is not None: + while len(attr_name) > 0: + if attr_name in model_prefix_to_model_type: + lookup_dict[model_prefix_to_model_type[attr_name]] = True + break + # Try again after removing the last word in the name + attr_name = "".join(camel_case_split(attr_name)[:-1]) + + all_models = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys())) + all_models = list(all_models) + all_models.sort() + + data = {"model_type": all_models} + data["pytorch"] = [pt_models[t] for t in all_models] + data["tensorflow"] = [tf_models[t] for t in all_models] + data["flax"] = [flax_models[t] for t in all_models] + + # Now let's find the right processing class for each model. In order we check if there is a Processor, then a + # Tokenizer, then a FeatureExtractor, then an ImageProcessor + processors = {} + for t in all_models: + if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoProcessor" + elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: + processors[t] = "AutoTokenizer" + elif t in transformers_module.models.auto.image_processing_auto.IMAGE_PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoImageProcessor" + elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: + processors[t] = "AutoFeatureExtractor" + else: + # Default to AutoTokenizer if a model has nothing, for backward compatibility. + processors[t] = "AutoTokenizer" + + data["processor"] = [processors[t] for t in all_models] + + return pd.DataFrame(data) + + +def update_pipeline_and_auto_class_table(table: Dict[str, Tuple[str, str]]) -> Dict[str, Tuple[str, str]]: + """ + Update the table maping models to pipelines and auto classes without removing old keys if they don't exist anymore. + + Args: + table (`Dict[str, Tuple[str, str]]`): + The existing table mapping model names to a tuple containing the pipeline tag and the auto-class name with + which they should be used. + + Returns: + `Dict[str, Tuple[str, str]]`: The updated table in the same format. + """ + auto_modules = [ + transformers_module.models.auto.modeling_auto, + transformers_module.models.auto.modeling_tf_auto, + transformers_module.models.auto.modeling_flax_auto, + ] + for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: + model_mappings = [model_mapping, f"TF_{model_mapping}", f"FLAX_{model_mapping}"] + auto_classes = [auto_class, f"TF_{auto_class}", f"Flax_{auto_class}"] + # Loop through all three frameworks + for module, cls, mapping in zip(auto_modules, auto_classes, model_mappings): + # The type of pipeline may not exist in this framework + if not hasattr(module, mapping): + continue + # First extract all model_names + model_names = [] + for name in getattr(module, mapping).values(): + if isinstance(name, str): + model_names.append(name) + else: + model_names.extend(list(name)) + + # Add pipeline tag and auto model class for those models + table.update({model_name: (pipeline_tag, cls) for model_name in model_names}) + + return table + + +def update_metadata(token: str, commit_sha: str): + """ + Update the metadata for the Transformers repo in `huggingface/transformers-metadata`. + + Args: + token (`str`): A valid token giving write access to `huggingface/transformers-metadata`. + commit_sha (`str`): The commit SHA on Transformers corresponding to this update. + """ + frameworks_table = get_frameworks_table() + frameworks_dataset = Dataset.from_pandas(frameworks_table) + + resolved_tags_file = hf_hub_download( + "huggingface/transformers-metadata", "pipeline_tags.json", repo_type="dataset", token=token + ) + tags_dataset = Dataset.from_json(resolved_tags_file) + table = { + tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"]) + for i in range(len(tags_dataset)) + } + table = update_pipeline_and_auto_class_table(table) + + # Sort the model classes to avoid some nondeterministic updates to create false update commits. + model_classes = sorted(table.keys()) + tags_table = pd.DataFrame( + { + "model_class": model_classes, + "pipeline_tag": [table[m][0] for m in model_classes], + "auto_class": [table[m][1] for m in model_classes], + } + ) + tags_dataset = Dataset.from_pandas(tags_table) + + hub_frameworks_json = hf_hub_download( + repo_id="huggingface/transformers-metadata", + filename="frameworks.json", + repo_type="dataset", + token=token, + ) + with open(hub_frameworks_json) as f: + hub_frameworks_json = f.read() + + hub_pipeline_tags_json = hf_hub_download( + repo_id="huggingface/transformers-metadata", + filename="pipeline_tags.json", + repo_type="dataset", + token=token, + ) + with open(hub_pipeline_tags_json) as f: + hub_pipeline_tags_json = f.read() + + with tempfile.TemporaryDirectory() as tmp_dir: + frameworks_dataset.to_json(os.path.join(tmp_dir, "frameworks.json")) + tags_dataset.to_json(os.path.join(tmp_dir, "pipeline_tags.json")) + + with open(os.path.join(tmp_dir, "frameworks.json")) as f: + frameworks_json = f.read() + with open(os.path.join(tmp_dir, "pipeline_tags.json")) as f: + pipeline_tags_json = f.read() + + frameworks_equal = hub_frameworks_json == frameworks_json + hub_pipeline_tags_equal = hub_pipeline_tags_json == pipeline_tags_json + + if frameworks_equal and hub_pipeline_tags_equal: + print("No updates on the Hub, not pushing the metadata files.") + return + + if commit_sha is not None: + commit_message = ( + f"Update with commit {commit_sha}\n\nSee: " + f"https://github.com/huggingface/transformers/commit/{commit_sha}" + ) + else: + commit_message = "Update" + + upload_folder( + repo_id="huggingface/transformers-metadata", + folder_path=tmp_dir, + repo_type="dataset", + token=token, + commit_message=commit_message, + ) + + +def check_pipeline_tags(): + """ + Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script. + """ + in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} + pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS + missing = [] + for key in pipeline_tasks: + if key not in in_table: + model = pipeline_tasks[key]["pt"] + if isinstance(model, (list, tuple)): + model = model[0] + model = model.__name__ + if model not in in_table.values(): + missing.append(key) + + if len(missing) > 0: + msg = ", ".join(missing) + raise ValueError( + "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " + f"`utils/update_metadata.py`: {msg}. Please add them!" + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--token", type=str, help="The token to use to push to the transformers-metadata dataset.") + parser.add_argument("--commit_sha", type=str, help="The sha of the commit going with this update.") + parser.add_argument("--check-only", action="store_true", help="Activate to just check all pipelines are present.") + args = parser.parse_args() + + if args.check_only: + check_pipeline_tags() + else: + update_metadata(args.token, args.commit_sha) diff --git a/tasks/tasksmith-441eeab80047/environment/source/utils/update_tiny_models.py b/tasks/tasksmith-441eeab80047/environment/source/utils/update_tiny_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc4cdf6e6b29e3a3df13b1685dd620a82c9ad3d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/environment/source/utils/update_tiny_models.py @@ -0,0 +1,199 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""A script running `create_dummy_models.py` with a pre-defined set of arguments. + +This file is intended to be used in a CI workflow file without the need of specifying arguments. It creates and uploads +tiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updated +version of `tests/utils/tiny_model_summary.json`. That updated file should be merged into the `main` branch of +`transformers` so the pipeline testing will use the latest created/updated tiny models. +""" + +import argparse +import copy +import json +import multiprocessing +import os +import time + +from create_dummy_models import COMPOSITE_MODELS, create_tiny_models +from huggingface_hub import ModelFilter, hf_api + +import transformers +from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer +from transformers.image_processing_utils import BaseImageProcessor + + +def get_all_model_names(): + model_names = set() + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [ + x + for x in dir(module) + if x.endswith("_MAPPING_NAMES") + and (x.startswith("MODEL_") or x.startswith("TF_MODEL_") or x.startswith("FLAX_MODEL_")) + ] + for name in mapping_names: + mapping = getattr(module, name) + if mapping is not None: + for v in mapping.values(): + if isinstance(v, (list, tuple)): + model_names.update(v) + elif isinstance(v, str): + model_names.add(v) + + return sorted(model_names) + + +def get_tiny_model_names_from_repo(): + # All model names defined in auto mappings + model_names = set(get_all_model_names()) + + with open("tests/utils/tiny_model_summary.json") as fp: + tiny_model_info = json.load(fp) + tiny_models_names = set() + for model_base_name in tiny_model_info: + tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"]) + + # Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub. + not_on_hub = model_names.difference(tiny_models_names) + for model_name in copy.copy(tiny_models_names): + if not model_name.startswith("TF") and f"TF{model_name}" in not_on_hub: + tiny_models_names.remove(model_name) + elif model_name.startswith("TF") and model_name[2:] in not_on_hub: + tiny_models_names.remove(model_name) + + return sorted(tiny_models_names) + + +def get_tiny_model_summary_from_hub(output_path): + special_models = COMPOSITE_MODELS.values() + + # All tiny model base names on Hub + model_names = get_all_model_names() + models = hf_api.list_models( + filter=ModelFilter( + author="hf-internal-testing", + ) + ) + _models = set() + for x in models: + model = x.id + org, model = model.split("/") + if not model.startswith("tiny-random-"): + continue + model = model.replace("tiny-random-", "") + if not model[0].isupper(): + continue + if model not in model_names and model not in special_models: + continue + _models.add(model) + + models = sorted(_models) + # All tiny model names on Hub + summary = {} + for model in models: + repo_id = f"hf-internal-testing/tiny-random-{model}" + model = model.split("-")[0] + try: + repo_info = hf_api.repo_info(repo_id) + content = { + "tokenizer_classes": set(), + "processor_classes": set(), + "model_classes": set(), + "sha": repo_info.sha, + } + except Exception: + continue + try: + time.sleep(1) + tokenizer_fast = AutoTokenizer.from_pretrained(repo_id) + content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + tokenizer_slow = AutoTokenizer.from_pretrained(repo_id, use_fast=False) + content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + img_p = AutoImageProcessor.from_pretrained(repo_id) + content["processor_classes"].add(img_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + feat_p = AutoFeatureExtractor.from_pretrained(repo_id) + if not isinstance(feat_p, BaseImageProcessor): + content["processor_classes"].add(feat_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, model) + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, f"TF{model}") + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + + content["tokenizer_classes"] = sorted(content["tokenizer_classes"]) + content["processor_classes"] = sorted(content["processor_classes"]) + content["model_classes"] = sorted(content["model_classes"]) + + summary[model] = content + with open(os.path.join(output_path, "hub_tiny_model_summary.json"), "w") as fp: + json.dump(summary, fp, ensure_ascii=False, indent=4) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + args = parser.parse_args() + + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + output_path = "tiny_models" + all = True + model_types = None + models_to_skip = get_tiny_model_names_from_repo() + no_check = True + upload = True + organization = "hf-internal-testing" + + create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token=os.environ.get("TOKEN", None), + num_workers=args.num_workers, + ) diff --git a/tasks/tasksmith-441eeab80047/instruction.md b/tasks/tasksmith-441eeab80047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d001b35200a72178e3cefc45196cce78a7ba096 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/instruction.md @@ -0,0 +1,15 @@ +Add a `Mistral3` multimodal vision-language model to the library. The implementation should include: + +**`Mistral3Config`** (`model_type="mistral3"`) with sub-configs `vision_config` (default: Pixtral) and `text_config` (default: Mistral), and fields: `image_token_index` (default 10), `projector_hidden_act` (default `"gelu"`), `vision_feature_layer` (default -1), `multimodal_projector_bias` (default `False`), `spatial_merge_size` (default 2). When sub-configs are passed as dicts, they must be instantiated using the auto config mapping. + +**`Mistral3ForConditionalGeneration`** combining a Pixtral vision tower, a multimodal projector, and a Mistral language model. The `forward` method accepts `input_ids`, `pixel_values`, `attention_mask`, `image_sizes`, `labels`, `past_key_values`, and `logits_to_keep`. When `pixel_values` is provided it must extract image features and replace `image_token_index` positions in the embedding. The model supports `use_cache`, gradient checkpointing, and computes cross-entropy loss when `labels` are given. Both `return_dict=True` and tuple output must work. The model must be save/load round-trip compatible. + +**`Mistral3MultiModalProjector`**: applies RMS normalization to vision features, then a spatial patch merger, then two linear layers with `projector_hidden_act` activation (and optional bias). The patch merger groups `spatial_merge_size × spatial_merge_size` adjacent patch tokens using `torch.nn.functional.unfold` with matching kernel and stride, concatenates their features along the channel dimension, and passes the result through a single linear layer, reducing the token count by `spatial_merge_size²`. The output shape is `(merged_tokens, text_hidden_size)`. + +**Pixtral processor change**: `PixtralProcessor` must accept and store a `spatial_merge_size` parameter (default 1). When expanding image tokens, divide by `patch_size * spatial_merge_size` instead of `patch_size` alone, producing `spatial_merge_size²` fewer tokens per image. + +**Pixtral image processor change**: when an image exceeds `longest_edge` and must be downscaled, compute the new dimensions using `floor` (not `ceil`) so the resized image is always ≤ `longest_edge`. For example, a 7×5 image at `longest_edge=5, patch_size=1` must resize to (5, 3), not (5, 4). + +Auto classes must map model type `"mistral3"` to `Mistral3Config`, `Mistral3ForConditionalGeneration`, `PixtralImageProcessor`/`PixtralImageProcessorFast`, and `PixtralProcessor`. + +Work in `/workspace`. Submit your fix in Python source files under `src/transformers`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files. diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/__init__.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c6ca0fe1e924615d246484a0ff7c633346de214 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/__init__.py @@ -0,0 +1,9688 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# When adding a new object to this init, remember to add it twice: once inside the `_import_structure` dictionary and +# once inside the `if TYPE_CHECKING` branch. The `TYPE_CHECKING` should have import statements as usual, but they are +# only there for type checking. The `_import_structure` is a dictionary submodule to list of object names, and is used +# to defer the actual importing for when the objects are requested. This way `import transformers` provides the names +# in the namespace without actually importing anything (and especially none of the backends). + +__version__ = "4.50.0.dev0" + +from typing import TYPE_CHECKING + +# Check the dependencies satisfy the minimal versions required. +from . import dependency_versions_check +from .utils import ( + OptionalDependencyNotAvailable, + _LazyModule, + is_bitsandbytes_available, + is_essentia_available, + is_flax_available, + is_g2p_en_available, + is_keras_nlp_available, + is_librosa_available, + is_pretty_midi_available, + is_scipy_available, + is_sentencepiece_available, + is_speech_available, + is_tensorflow_text_available, + is_tf_available, + is_timm_available, + is_tokenizers_available, + is_torch_available, + is_torchaudio_available, + is_torchvision_available, + is_vision_available, + logging, +) + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +# Base objects, independent of any specific backend +_import_structure = { + "agents": [ + "Agent", + "CodeAgent", + "HfApiEngine", + "ManagedAgent", + "PipelineTool", + "ReactAgent", + "ReactCodeAgent", + "ReactJsonAgent", + "Tool", + "Toolbox", + "ToolCollection", + "TransformersEngine", + "launch_gradio_demo", + "load_tool", + "stream_to_gradio", + "tool", + ], + "audio_utils": [], + "commands": [], + "configuration_utils": ["PretrainedConfig"], + "convert_graph_to_onnx": [], + "convert_slow_tokenizers_checkpoints_to_fast": [], + "convert_tf_hub_seq_to_seq_bert_to_pytorch": [], + "data": [ + "DataProcessor", + "InputExample", + "InputFeatures", + "SingleSentenceClassificationProcessor", + "SquadExample", + "SquadFeatures", + "SquadV1Processor", + "SquadV2Processor", + "glue_compute_metrics", + "glue_convert_examples_to_features", + "glue_output_modes", + "glue_processors", + "glue_tasks_num_labels", + "squad_convert_examples_to_features", + "xnli_compute_metrics", + "xnli_output_modes", + "xnli_processors", + "xnli_tasks_num_labels", + ], + "data.data_collator": [ + "DataCollator", + "DataCollatorForLanguageModeling", + "DataCollatorForMultipleChoice", + "DataCollatorForPermutationLanguageModeling", + "DataCollatorForSeq2Seq", + "DataCollatorForSOP", + "DataCollatorForTokenClassification", + "DataCollatorForWholeWordMask", + "DataCollatorWithFlattening", + "DataCollatorWithPadding", + "DefaultDataCollator", + "default_data_collator", + ], + "data.metrics": [], + "data.processors": [], + "debug_utils": [], + "dependency_versions_check": [], + "dependency_versions_table": [], + "dynamic_module_utils": [], + "feature_extraction_sequence_utils": ["SequenceFeatureExtractor"], + "feature_extraction_utils": ["BatchFeature", "FeatureExtractionMixin"], + "file_utils": [], + "generation": [ + "AsyncTextIteratorStreamer", + "CompileConfig", + "GenerationConfig", + "TextIteratorStreamer", + "TextStreamer", + "WatermarkingConfig", + ], + "hf_argparser": ["HfArgumentParser"], + "hyperparameter_search": [], + "image_transforms": [], + "integrations": [ + "is_clearml_available", + "is_comet_available", + "is_dvclive_available", + "is_neptune_available", + "is_optuna_available", + "is_ray_available", + "is_ray_tune_available", + "is_sigopt_available", + "is_swanlab_available", + "is_tensorboard_available", + "is_wandb_available", + ], + "loss": [], + "modelcard": ["ModelCard"], + # Losses + "modeling_tf_pytorch_utils": [ + "convert_tf_weight_name_to_pt_weight_name", + "load_pytorch_checkpoint_in_tf2_model", + "load_pytorch_model_in_tf2_model", + "load_pytorch_weights_in_tf2_model", + "load_tf2_checkpoint_in_pytorch_model", + "load_tf2_model_in_pytorch_model", + "load_tf2_weights_in_pytorch_model", + ], + # Models + "models": [], + "models.albert": ["AlbertConfig"], + "models.align": [ + "AlignConfig", + "AlignProcessor", + "AlignTextConfig", + "AlignVisionConfig", + ], + "models.altclip": [ + "AltCLIPConfig", + "AltCLIPProcessor", + "AltCLIPTextConfig", + "AltCLIPVisionConfig", + ], + "models.aria": [ + "AriaConfig", + "AriaProcessor", + "AriaTextConfig", + ], + "models.audio_spectrogram_transformer": [ + "ASTConfig", + "ASTFeatureExtractor", + ], + "models.auto": [ + "CONFIG_MAPPING", + "FEATURE_EXTRACTOR_MAPPING", + "IMAGE_PROCESSOR_MAPPING", + "MODEL_NAMES_MAPPING", + "PROCESSOR_MAPPING", + "TOKENIZER_MAPPING", + "AutoConfig", + "AutoFeatureExtractor", + "AutoImageProcessor", + "AutoProcessor", + "AutoTokenizer", + ], + "models.autoformer": ["AutoformerConfig"], + "models.aya_vision": ["AyaVisionConfig", "AyaVisionProcessor"], + "models.bamba": ["BambaConfig"], + "models.bark": [ + "BarkCoarseConfig", + "BarkConfig", + "BarkFineConfig", + "BarkProcessor", + "BarkSemanticConfig", + ], + "models.bart": ["BartConfig", "BartTokenizer"], + "models.barthez": [], + "models.bartpho": [], + "models.beit": ["BeitConfig"], + "models.bert": [ + "BasicTokenizer", + "BertConfig", + "BertTokenizer", + "WordpieceTokenizer", + ], + "models.bert_generation": ["BertGenerationConfig"], + "models.bert_japanese": [ + "BertJapaneseTokenizer", + "CharacterTokenizer", + "MecabTokenizer", + ], + "models.bertweet": ["BertweetTokenizer"], + "models.big_bird": ["BigBirdConfig"], + "models.bigbird_pegasus": ["BigBirdPegasusConfig"], + "models.biogpt": [ + "BioGptConfig", + "BioGptTokenizer", + ], + "models.bit": ["BitConfig"], + "models.blenderbot": [ + "BlenderbotConfig", + "BlenderbotTokenizer", + ], + "models.blenderbot_small": [ + "BlenderbotSmallConfig", + "BlenderbotSmallTokenizer", + ], + "models.blip": [ + "BlipConfig", + "BlipProcessor", + "BlipTextConfig", + "BlipVisionConfig", + ], + "models.blip_2": [ + "Blip2Config", + "Blip2Processor", + "Blip2QFormerConfig", + "Blip2VisionConfig", + ], + "models.bloom": ["BloomConfig"], + "models.bridgetower": [ + "BridgeTowerConfig", + "BridgeTowerProcessor", + "BridgeTowerTextConfig", + "BridgeTowerVisionConfig", + ], + "models.bros": [ + "BrosConfig", + "BrosProcessor", + ], + "models.byt5": ["ByT5Tokenizer"], + "models.camembert": ["CamembertConfig"], + "models.canine": [ + "CanineConfig", + "CanineTokenizer", + ], + "models.chameleon": [ + "ChameleonConfig", + "ChameleonProcessor", + "ChameleonVQVAEConfig", + ], + "models.chinese_clip": [ + "ChineseCLIPConfig", + "ChineseCLIPProcessor", + "ChineseCLIPTextConfig", + "ChineseCLIPVisionConfig", + ], + "models.clap": [ + "ClapAudioConfig", + "ClapConfig", + "ClapProcessor", + "ClapTextConfig", + ], + "models.clip": [ + "CLIPConfig", + "CLIPProcessor", + "CLIPTextConfig", + "CLIPTokenizer", + "CLIPVisionConfig", + ], + "models.clipseg": [ + "CLIPSegConfig", + "CLIPSegProcessor", + "CLIPSegTextConfig", + "CLIPSegVisionConfig", + ], + "models.clvp": [ + "ClvpConfig", + "ClvpDecoderConfig", + "ClvpEncoderConfig", + "ClvpFeatureExtractor", + "ClvpProcessor", + "ClvpTokenizer", + ], + "models.code_llama": [], + "models.codegen": [ + "CodeGenConfig", + "CodeGenTokenizer", + ], + "models.cohere": ["CohereConfig"], + "models.cohere2": ["Cohere2Config"], + "models.colpali": [ + "ColPaliConfig", + "ColPaliProcessor", + ], + "models.conditional_detr": ["ConditionalDetrConfig"], + "models.convbert": [ + "ConvBertConfig", + "ConvBertTokenizer", + ], + "models.convnext": ["ConvNextConfig"], + "models.convnextv2": ["ConvNextV2Config"], + "models.cpm": [], + "models.cpmant": [ + "CpmAntConfig", + "CpmAntTokenizer", + ], + "models.ctrl": [ + "CTRLConfig", + "CTRLTokenizer", + ], + "models.cvt": ["CvtConfig"], + "models.dab_detr": ["DabDetrConfig"], + "models.dac": ["DacConfig", "DacFeatureExtractor"], + "models.data2vec": [ + "Data2VecAudioConfig", + "Data2VecTextConfig", + "Data2VecVisionConfig", + ], + "models.dbrx": ["DbrxConfig"], + "models.deberta": [ + "DebertaConfig", + "DebertaTokenizer", + ], + "models.deberta_v2": ["DebertaV2Config"], + "models.decision_transformer": ["DecisionTransformerConfig"], + "models.deformable_detr": ["DeformableDetrConfig"], + "models.deit": ["DeiTConfig"], + "models.deprecated": [], + "models.deprecated.bort": [], + "models.deprecated.deta": ["DetaConfig"], + "models.deprecated.efficientformer": ["EfficientFormerConfig"], + "models.deprecated.ernie_m": ["ErnieMConfig"], + "models.deprecated.gptsan_japanese": [ + "GPTSanJapaneseConfig", + "GPTSanJapaneseTokenizer", + ], + "models.deprecated.graphormer": ["GraphormerConfig"], + "models.deprecated.jukebox": [ + "JukeboxConfig", + "JukeboxPriorConfig", + "JukeboxTokenizer", + "JukeboxVQVAEConfig", + ], + "models.deprecated.mctct": [ + "MCTCTConfig", + "MCTCTFeatureExtractor", + "MCTCTProcessor", + ], + "models.deprecated.mega": ["MegaConfig"], + "models.deprecated.mmbt": ["MMBTConfig"], + "models.deprecated.nat": ["NatConfig"], + "models.deprecated.nezha": ["NezhaConfig"], + "models.deprecated.open_llama": ["OpenLlamaConfig"], + "models.deprecated.qdqbert": ["QDQBertConfig"], + "models.deprecated.realm": [ + "RealmConfig", + "RealmTokenizer", + ], + "models.deprecated.retribert": [ + "RetriBertConfig", + "RetriBertTokenizer", + ], + "models.deprecated.speech_to_text_2": [ + "Speech2Text2Config", + "Speech2Text2Processor", + "Speech2Text2Tokenizer", + ], + "models.deprecated.tapex": ["TapexTokenizer"], + "models.deprecated.trajectory_transformer": ["TrajectoryTransformerConfig"], + "models.deprecated.transfo_xl": [ + "TransfoXLConfig", + "TransfoXLCorpus", + "TransfoXLTokenizer", + ], + "models.deprecated.tvlt": [ + "TvltConfig", + "TvltFeatureExtractor", + "TvltProcessor", + ], + "models.deprecated.van": ["VanConfig"], + "models.deprecated.vit_hybrid": ["ViTHybridConfig"], + "models.deprecated.xlm_prophetnet": ["XLMProphetNetConfig"], + "models.depth_anything": ["DepthAnythingConfig"], + "models.depth_pro": ["DepthProConfig"], + "models.detr": ["DetrConfig"], + "models.dialogpt": [], + "models.diffllama": ["DiffLlamaConfig"], + "models.dinat": ["DinatConfig"], + "models.dinov2": ["Dinov2Config"], + "models.dinov2_with_registers": ["Dinov2WithRegistersConfig"], + "models.distilbert": [ + "DistilBertConfig", + "DistilBertTokenizer", + ], + "models.dit": [], + "models.donut": [ + "DonutProcessor", + "DonutSwinConfig", + ], + "models.dpr": [ + "DPRConfig", + "DPRContextEncoderTokenizer", + "DPRQuestionEncoderTokenizer", + "DPRReaderOutput", + "DPRReaderTokenizer", + ], + "models.dpt": ["DPTConfig"], + "models.efficientnet": ["EfficientNetConfig"], + "models.electra": [ + "ElectraConfig", + "ElectraTokenizer", + ], + "models.emu3": [ + "Emu3Config", + "Emu3Processor", + "Emu3TextConfig", + "Emu3VQVAEConfig", + ], + "models.encodec": [ + "EncodecConfig", + "EncodecFeatureExtractor", + ], + "models.encoder_decoder": ["EncoderDecoderConfig"], + "models.ernie": ["ErnieConfig"], + "models.esm": ["EsmConfig", "EsmTokenizer"], + "models.falcon": ["FalconConfig"], + "models.falcon_mamba": ["FalconMambaConfig"], + "models.fastspeech2_conformer": [ + "FastSpeech2ConformerConfig", + "FastSpeech2ConformerHifiGanConfig", + "FastSpeech2ConformerTokenizer", + "FastSpeech2ConformerWithHifiGanConfig", + ], + "models.flaubert": ["FlaubertConfig", "FlaubertTokenizer"], + "models.flava": [ + "FlavaConfig", + "FlavaImageCodebookConfig", + "FlavaImageConfig", + "FlavaMultimodalConfig", + "FlavaTextConfig", + ], + "models.fnet": ["FNetConfig"], + "models.focalnet": ["FocalNetConfig"], + "models.fsmt": [ + "FSMTConfig", + "FSMTTokenizer", + ], + "models.funnel": [ + "FunnelConfig", + "FunnelTokenizer", + ], + "models.fuyu": ["FuyuConfig"], + "models.gemma": ["GemmaConfig"], + "models.gemma2": ["Gemma2Config"], + "models.gemma3": ["Gemma3Config", "Gemma3Processor", "Gemma3TextConfig"], + "models.git": [ + "GitConfig", + "GitProcessor", + "GitVisionConfig", + ], + "models.glm": ["GlmConfig"], + "models.glpn": ["GLPNConfig"], + "models.got_ocr2": [ + "GotOcr2Config", + "GotOcr2Processor", + "GotOcr2VisionConfig", + ], + "models.gpt2": [ + "GPT2Config", + "GPT2Tokenizer", + ], + "models.gpt_bigcode": ["GPTBigCodeConfig"], + "models.gpt_neo": ["GPTNeoConfig"], + "models.gpt_neox": ["GPTNeoXConfig"], + "models.gpt_neox_japanese": ["GPTNeoXJapaneseConfig"], + "models.gpt_sw3": [], + "models.gptj": ["GPTJConfig"], + "models.granite": ["GraniteConfig"], + "models.granitemoe": ["GraniteMoeConfig"], + "models.granitemoeshared": ["GraniteMoeSharedConfig"], + "models.grounding_dino": [ + "GroundingDinoConfig", + "GroundingDinoProcessor", + ], + "models.groupvit": [ + "GroupViTConfig", + "GroupViTTextConfig", + "GroupViTVisionConfig", + ], + "models.helium": ["HeliumConfig"], + "models.herbert": ["HerbertTokenizer"], + "models.hiera": ["HieraConfig"], + "models.hubert": ["HubertConfig"], + "models.ibert": ["IBertConfig"], + "models.idefics": ["IdeficsConfig"], + "models.idefics2": ["Idefics2Config"], + "models.idefics3": ["Idefics3Config"], + "models.ijepa": ["IJepaConfig"], + "models.imagegpt": ["ImageGPTConfig"], + "models.informer": ["InformerConfig"], + "models.instructblip": [ + "InstructBlipConfig", + "InstructBlipProcessor", + "InstructBlipQFormerConfig", + "InstructBlipVisionConfig", + ], + "models.instructblipvideo": [ + "InstructBlipVideoConfig", + "InstructBlipVideoProcessor", + "InstructBlipVideoQFormerConfig", + "InstructBlipVideoVisionConfig", + ], + "models.jamba": ["JambaConfig"], + "models.jetmoe": ["JetMoeConfig"], + "models.kosmos2": [ + "Kosmos2Config", + "Kosmos2Processor", + ], + "models.layoutlm": [ + "LayoutLMConfig", + "LayoutLMTokenizer", + ], + "models.layoutlmv2": [ + "LayoutLMv2Config", + "LayoutLMv2FeatureExtractor", + "LayoutLMv2ImageProcessor", + "LayoutLMv2Processor", + "LayoutLMv2Tokenizer", + ], + "models.layoutlmv3": [ + "LayoutLMv3Config", + "LayoutLMv3FeatureExtractor", + "LayoutLMv3ImageProcessor", + "LayoutLMv3Processor", + "LayoutLMv3Tokenizer", + ], + "models.layoutxlm": ["LayoutXLMProcessor"], + "models.led": ["LEDConfig", "LEDTokenizer"], + "models.levit": ["LevitConfig"], + "models.lilt": ["LiltConfig"], + "models.llama": ["LlamaConfig"], + "models.llava": [ + "LlavaConfig", + "LlavaProcessor", + ], + "models.llava_next": [ + "LlavaNextConfig", + "LlavaNextProcessor", + ], + "models.llava_next_video": [ + "LlavaNextVideoConfig", + "LlavaNextVideoProcessor", + ], + "models.llava_onevision": ["LlavaOnevisionConfig", "LlavaOnevisionProcessor"], + "models.longformer": [ + "LongformerConfig", + "LongformerTokenizer", + ], + "models.longt5": ["LongT5Config"], + "models.luke": [ + "LukeConfig", + "LukeTokenizer", + ], + "models.lxmert": [ + "LxmertConfig", + "LxmertTokenizer", + ], + "models.m2m_100": ["M2M100Config"], + "models.mamba": ["MambaConfig"], + "models.mamba2": ["Mamba2Config"], + "models.marian": ["MarianConfig"], + "models.markuplm": [ + "MarkupLMConfig", + "MarkupLMFeatureExtractor", + "MarkupLMProcessor", + "MarkupLMTokenizer", + ], + "models.mask2former": ["Mask2FormerConfig"], + "models.maskformer": [ + "MaskFormerConfig", + "MaskFormerSwinConfig", + ], + "models.mbart": ["MBartConfig"], + "models.mbart50": [], + "models.megatron_bert": ["MegatronBertConfig"], + "models.megatron_gpt2": [], + "models.mgp_str": [ + "MgpstrConfig", + "MgpstrProcessor", + "MgpstrTokenizer", + ], + "models.mimi": ["MimiConfig"], + "models.mistral": ["MistralConfig"], + "models.mistral3": ["Mistral3Config"], + "models.mixtral": ["MixtralConfig"], + "models.mllama": [ + "MllamaConfig", + "MllamaProcessor", + ], + "models.mluke": [], + "models.mobilebert": [ + "MobileBertConfig", + "MobileBertTokenizer", + ], + "models.mobilenet_v1": ["MobileNetV1Config"], + "models.mobilenet_v2": ["MobileNetV2Config"], + "models.mobilevit": ["MobileViTConfig"], + "models.mobilevitv2": ["MobileViTV2Config"], + "models.modernbert": ["ModernBertConfig"], + "models.moonshine": ["MoonshineConfig"], + "models.moshi": [ + "MoshiConfig", + "MoshiDepthConfig", + ], + "models.mpnet": [ + "MPNetConfig", + "MPNetTokenizer", + ], + "models.mpt": ["MptConfig"], + "models.mra": ["MraConfig"], + "models.mt5": ["MT5Config"], + "models.musicgen": [ + "MusicgenConfig", + "MusicgenDecoderConfig", + ], + "models.musicgen_melody": [ + "MusicgenMelodyConfig", + "MusicgenMelodyDecoderConfig", + ], + "models.mvp": ["MvpConfig", "MvpTokenizer"], + "models.myt5": ["MyT5Tokenizer"], + "models.nemotron": ["NemotronConfig"], + "models.nllb": [], + "models.nllb_moe": ["NllbMoeConfig"], + "models.nougat": ["NougatProcessor"], + "models.nystromformer": ["NystromformerConfig"], + "models.olmo": ["OlmoConfig"], + "models.olmo2": ["Olmo2Config"], + "models.olmoe": ["OlmoeConfig"], + "models.omdet_turbo": [ + "OmDetTurboConfig", + "OmDetTurboProcessor", + ], + "models.oneformer": [ + "OneFormerConfig", + "OneFormerProcessor", + ], + "models.openai": [ + "OpenAIGPTConfig", + "OpenAIGPTTokenizer", + ], + "models.opt": ["OPTConfig"], + "models.owlv2": [ + "Owlv2Config", + "Owlv2Processor", + "Owlv2TextConfig", + "Owlv2VisionConfig", + ], + "models.owlvit": [ + "OwlViTConfig", + "OwlViTProcessor", + "OwlViTTextConfig", + "OwlViTVisionConfig", + ], + "models.paligemma": ["PaliGemmaConfig"], + "models.patchtsmixer": ["PatchTSMixerConfig"], + "models.patchtst": ["PatchTSTConfig"], + "models.pegasus": [ + "PegasusConfig", + "PegasusTokenizer", + ], + "models.pegasus_x": ["PegasusXConfig"], + "models.perceiver": [ + "PerceiverConfig", + "PerceiverTokenizer", + ], + "models.persimmon": ["PersimmonConfig"], + "models.phi": ["PhiConfig"], + "models.phi3": ["Phi3Config"], + "models.phimoe": ["PhimoeConfig"], + "models.phobert": ["PhobertTokenizer"], + "models.pix2struct": [ + "Pix2StructConfig", + "Pix2StructProcessor", + "Pix2StructTextConfig", + "Pix2StructVisionConfig", + ], + "models.pixtral": ["PixtralProcessor", "PixtralVisionConfig"], + "models.plbart": ["PLBartConfig"], + "models.poolformer": ["PoolFormerConfig"], + "models.pop2piano": ["Pop2PianoConfig"], + "models.prophetnet": [ + "ProphetNetConfig", + "ProphetNetTokenizer", + ], + "models.pvt": ["PvtConfig"], + "models.pvt_v2": ["PvtV2Config"], + "models.qwen2": [ + "Qwen2Config", + "Qwen2Tokenizer", + ], + "models.qwen2_5_vl": [ + "Qwen2_5_VLConfig", + "Qwen2_5_VLProcessor", + ], + "models.qwen2_audio": [ + "Qwen2AudioConfig", + "Qwen2AudioEncoderConfig", + "Qwen2AudioProcessor", + ], + "models.qwen2_moe": ["Qwen2MoeConfig"], + "models.qwen2_vl": [ + "Qwen2VLConfig", + "Qwen2VLProcessor", + ], + "models.rag": ["RagConfig", "RagRetriever", "RagTokenizer"], + "models.recurrent_gemma": ["RecurrentGemmaConfig"], + "models.reformer": ["ReformerConfig"], + "models.regnet": ["RegNetConfig"], + "models.rembert": ["RemBertConfig"], + "models.resnet": ["ResNetConfig"], + "models.roberta": [ + "RobertaConfig", + "RobertaTokenizer", + ], + "models.roberta_prelayernorm": ["RobertaPreLayerNormConfig"], + "models.roc_bert": [ + "RoCBertConfig", + "RoCBertTokenizer", + ], + "models.roformer": [ + "RoFormerConfig", + "RoFormerTokenizer", + ], + "models.rt_detr": ["RTDetrConfig", "RTDetrResNetConfig"], + "models.rt_detr_v2": ["RTDetrV2Config"], + "models.rwkv": ["RwkvConfig"], + "models.sam": [ + "SamConfig", + "SamMaskDecoderConfig", + "SamProcessor", + "SamPromptEncoderConfig", + "SamVisionConfig", + ], + "models.seamless_m4t": [ + "SeamlessM4TConfig", + "SeamlessM4TFeatureExtractor", + "SeamlessM4TProcessor", + ], + "models.seamless_m4t_v2": ["SeamlessM4Tv2Config"], + "models.segformer": ["SegformerConfig"], + "models.seggpt": ["SegGptConfig"], + "models.sew": ["SEWConfig"], + "models.sew_d": ["SEWDConfig"], + "models.siglip": [ + "SiglipConfig", + "SiglipProcessor", + "SiglipTextConfig", + "SiglipVisionConfig", + ], + "models.siglip2": [ + "Siglip2Config", + "Siglip2Processor", + "Siglip2TextConfig", + "Siglip2VisionConfig", + ], + "models.smolvlm": ["SmolVLMConfig"], + "models.speech_encoder_decoder": ["SpeechEncoderDecoderConfig"], + "models.speech_to_text": [ + "Speech2TextConfig", + "Speech2TextFeatureExtractor", + "Speech2TextProcessor", + ], + "models.speecht5": [ + "SpeechT5Config", + "SpeechT5FeatureExtractor", + "SpeechT5HifiGanConfig", + "SpeechT5Processor", + ], + "models.splinter": [ + "SplinterConfig", + "SplinterTokenizer", + ], + "models.squeezebert": [ + "SqueezeBertConfig", + "SqueezeBertTokenizer", + ], + "models.stablelm": ["StableLmConfig"], + "models.starcoder2": ["Starcoder2Config"], + "models.superglue": ["SuperGlueConfig"], + "models.superpoint": ["SuperPointConfig"], + "models.swiftformer": ["SwiftFormerConfig"], + "models.swin": ["SwinConfig"], + "models.swin2sr": ["Swin2SRConfig"], + "models.swinv2": ["Swinv2Config"], + "models.switch_transformers": ["SwitchTransformersConfig"], + "models.t5": ["T5Config"], + "models.table_transformer": ["TableTransformerConfig"], + "models.tapas": [ + "TapasConfig", + "TapasTokenizer", + ], + "models.textnet": ["TextNetConfig"], + "models.time_series_transformer": ["TimeSeriesTransformerConfig"], + "models.timesformer": ["TimesformerConfig"], + "models.timm_backbone": ["TimmBackboneConfig"], + "models.timm_wrapper": ["TimmWrapperConfig"], + "models.trocr": [ + "TrOCRConfig", + "TrOCRProcessor", + ], + "models.tvp": [ + "TvpConfig", + "TvpProcessor", + ], + "models.udop": [ + "UdopConfig", + "UdopProcessor", + ], + "models.umt5": ["UMT5Config"], + "models.unispeech": ["UniSpeechConfig"], + "models.unispeech_sat": ["UniSpeechSatConfig"], + "models.univnet": [ + "UnivNetConfig", + "UnivNetFeatureExtractor", + ], + "models.upernet": ["UperNetConfig"], + "models.video_llava": ["VideoLlavaConfig"], + "models.videomae": ["VideoMAEConfig"], + "models.vilt": [ + "ViltConfig", + "ViltFeatureExtractor", + "ViltImageProcessor", + "ViltProcessor", + ], + "models.vipllava": ["VipLlavaConfig"], + "models.vision_encoder_decoder": ["VisionEncoderDecoderConfig"], + "models.vision_text_dual_encoder": [ + "VisionTextDualEncoderConfig", + "VisionTextDualEncoderProcessor", + ], + "models.visual_bert": ["VisualBertConfig"], + "models.vit": ["ViTConfig"], + "models.vit_mae": ["ViTMAEConfig"], + "models.vit_msn": ["ViTMSNConfig"], + "models.vitdet": ["VitDetConfig"], + "models.vitmatte": ["VitMatteConfig"], + "models.vitpose": ["VitPoseConfig"], + "models.vitpose_backbone": ["VitPoseBackboneConfig"], + "models.vits": [ + "VitsConfig", + "VitsTokenizer", + ], + "models.vivit": ["VivitConfig"], + "models.wav2vec2": [ + "Wav2Vec2Config", + "Wav2Vec2CTCTokenizer", + "Wav2Vec2FeatureExtractor", + "Wav2Vec2Processor", + "Wav2Vec2Tokenizer", + ], + "models.wav2vec2_bert": [ + "Wav2Vec2BertConfig", + "Wav2Vec2BertProcessor", + ], + "models.wav2vec2_conformer": ["Wav2Vec2ConformerConfig"], + "models.wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"], + "models.wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"], + "models.wavlm": ["WavLMConfig"], + "models.whisper": [ + "WhisperConfig", + "WhisperFeatureExtractor", + "WhisperProcessor", + "WhisperTokenizer", + ], + "models.x_clip": [ + "XCLIPConfig", + "XCLIPProcessor", + "XCLIPTextConfig", + "XCLIPVisionConfig", + ], + "models.xglm": ["XGLMConfig"], + "models.xlm": ["XLMConfig", "XLMTokenizer"], + "models.xlm_roberta": ["XLMRobertaConfig"], + "models.xlm_roberta_xl": ["XLMRobertaXLConfig"], + "models.xlnet": ["XLNetConfig"], + "models.xmod": ["XmodConfig"], + "models.yolos": ["YolosConfig"], + "models.yoso": ["YosoConfig"], + "models.zamba": ["ZambaConfig"], + "models.zamba2": ["Zamba2Config"], + "models.zoedepth": ["ZoeDepthConfig"], + "onnx": [], + "pipelines": [ + "AudioClassificationPipeline", + "AutomaticSpeechRecognitionPipeline", + "CsvPipelineDataFormat", + "DepthEstimationPipeline", + "DocumentQuestionAnsweringPipeline", + "FeatureExtractionPipeline", + "FillMaskPipeline", + "ImageClassificationPipeline", + "ImageFeatureExtractionPipeline", + "ImageSegmentationPipeline", + "ImageTextToTextPipeline", + "ImageToImagePipeline", + "ImageToTextPipeline", + "JsonPipelineDataFormat", + "MaskGenerationPipeline", + "NerPipeline", + "ObjectDetectionPipeline", + "PipedPipelineDataFormat", + "Pipeline", + "PipelineDataFormat", + "QuestionAnsweringPipeline", + "SummarizationPipeline", + "TableQuestionAnsweringPipeline", + "Text2TextGenerationPipeline", + "TextClassificationPipeline", + "TextGenerationPipeline", + "TextToAudioPipeline", + "TokenClassificationPipeline", + "TranslationPipeline", + "VideoClassificationPipeline", + "VisualQuestionAnsweringPipeline", + "ZeroShotAudioClassificationPipeline", + "ZeroShotClassificationPipeline", + "ZeroShotImageClassificationPipeline", + "ZeroShotObjectDetectionPipeline", + "pipeline", + ], + "processing_utils": ["ProcessorMixin"], + "quantizers": [], + "testing_utils": [], + "tokenization_utils": ["PreTrainedTokenizer"], + "tokenization_utils_base": [ + "AddedToken", + "BatchEncoding", + "CharSpan", + "PreTrainedTokenizerBase", + "SpecialTokensMixin", + "TokenSpan", + ], + "trainer_callback": [ + "DefaultFlowCallback", + "EarlyStoppingCallback", + "PrinterCallback", + "ProgressCallback", + "TrainerCallback", + "TrainerControl", + "TrainerState", + ], + "trainer_utils": [ + "EvalPrediction", + "IntervalStrategy", + "SchedulerType", + "enable_full_determinism", + "set_seed", + ], + "training_args": ["TrainingArguments"], + "training_args_seq2seq": ["Seq2SeqTrainingArguments"], + "training_args_tf": ["TFTrainingArguments"], + "utils": [ + "CONFIG_NAME", + "MODEL_CARD_NAME", + "PYTORCH_PRETRAINED_BERT_CACHE", + "PYTORCH_TRANSFORMERS_CACHE", + "SPIECE_UNDERLINE", + "TF2_WEIGHTS_NAME", + "TF_WEIGHTS_NAME", + "TRANSFORMERS_CACHE", + "WEIGHTS_NAME", + "TensorType", + "add_end_docstrings", + "add_start_docstrings", + "is_apex_available", + "is_av_available", + "is_bitsandbytes_available", + "is_datasets_available", + "is_faiss_available", + "is_flax_available", + "is_keras_nlp_available", + "is_phonemizer_available", + "is_psutil_available", + "is_py3nvml_available", + "is_pyctcdecode_available", + "is_sacremoses_available", + "is_safetensors_available", + "is_scipy_available", + "is_sentencepiece_available", + "is_sklearn_available", + "is_speech_available", + "is_tensorflow_text_available", + "is_tf_available", + "is_timm_available", + "is_tokenizers_available", + "is_torch_available", + "is_torch_hpu_available", + "is_torch_mlu_available", + "is_torch_musa_available", + "is_torch_neuroncore_available", + "is_torch_npu_available", + "is_torch_tpu_available", + "is_torchvision_available", + "is_torch_xla_available", + "is_torch_xpu_available", + "is_vision_available", + "logging", + ], + "utils.quantization_config": [ + "AqlmConfig", + "AwqConfig", + "BitNetConfig", + "BitsAndBytesConfig", + "CompressedTensorsConfig", + "EetqConfig", + "FbgemmFp8Config", + "FineGrainedFP8Config", + "GPTQConfig", + "HiggsConfig", + "HqqConfig", + "QuantoConfig", + "SpQRConfig", + "TorchAoConfig", + "VptqConfig", + ], +} + +# sentencepiece-backed objects +try: + if not is_sentencepiece_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_sentencepiece_objects + + _import_structure["utils.dummy_sentencepiece_objects"] = [ + name for name in dir(dummy_sentencepiece_objects) if not name.startswith("_") + ] +else: + _import_structure["models.albert"].append("AlbertTokenizer") + _import_structure["models.barthez"].append("BarthezTokenizer") + _import_structure["models.bartpho"].append("BartphoTokenizer") + _import_structure["models.bert_generation"].append("BertGenerationTokenizer") + _import_structure["models.big_bird"].append("BigBirdTokenizer") + _import_structure["models.camembert"].append("CamembertTokenizer") + _import_structure["models.code_llama"].append("CodeLlamaTokenizer") + _import_structure["models.cpm"].append("CpmTokenizer") + _import_structure["models.deberta_v2"].append("DebertaV2Tokenizer") + _import_structure["models.deprecated.ernie_m"].append("ErnieMTokenizer") + _import_structure["models.deprecated.xlm_prophetnet"].append("XLMProphetNetTokenizer") + _import_structure["models.fnet"].append("FNetTokenizer") + _import_structure["models.gemma"].append("GemmaTokenizer") + _import_structure["models.gpt_sw3"].append("GPTSw3Tokenizer") + _import_structure["models.layoutxlm"].append("LayoutXLMTokenizer") + _import_structure["models.llama"].append("LlamaTokenizer") + _import_structure["models.m2m_100"].append("M2M100Tokenizer") + _import_structure["models.marian"].append("MarianTokenizer") + _import_structure["models.mbart"].append("MBartTokenizer") + _import_structure["models.mbart50"].append("MBart50Tokenizer") + _import_structure["models.mluke"].append("MLukeTokenizer") + _import_structure["models.mt5"].append("MT5Tokenizer") + _import_structure["models.nllb"].append("NllbTokenizer") + _import_structure["models.pegasus"].append("PegasusTokenizer") + _import_structure["models.plbart"].append("PLBartTokenizer") + _import_structure["models.reformer"].append("ReformerTokenizer") + _import_structure["models.rembert"].append("RemBertTokenizer") + _import_structure["models.seamless_m4t"].append("SeamlessM4TTokenizer") + _import_structure["models.siglip"].append("SiglipTokenizer") + _import_structure["models.speech_to_text"].append("Speech2TextTokenizer") + _import_structure["models.speecht5"].append("SpeechT5Tokenizer") + _import_structure["models.t5"].append("T5Tokenizer") + _import_structure["models.udop"].append("UdopTokenizer") + _import_structure["models.xglm"].append("XGLMTokenizer") + _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizer") + _import_structure["models.xlnet"].append("XLNetTokenizer") + +# tokenizers-backed objects +try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_tokenizers_objects + + _import_structure["utils.dummy_tokenizers_objects"] = [ + name for name in dir(dummy_tokenizers_objects) if not name.startswith("_") + ] +else: + # Fast tokenizers structure + _import_structure["models.albert"].append("AlbertTokenizerFast") + _import_structure["models.bart"].append("BartTokenizerFast") + _import_structure["models.barthez"].append("BarthezTokenizerFast") + _import_structure["models.bert"].append("BertTokenizerFast") + _import_structure["models.big_bird"].append("BigBirdTokenizerFast") + _import_structure["models.blenderbot"].append("BlenderbotTokenizerFast") + _import_structure["models.blenderbot_small"].append("BlenderbotSmallTokenizerFast") + _import_structure["models.bloom"].append("BloomTokenizerFast") + _import_structure["models.camembert"].append("CamembertTokenizerFast") + _import_structure["models.clip"].append("CLIPTokenizerFast") + _import_structure["models.code_llama"].append("CodeLlamaTokenizerFast") + _import_structure["models.codegen"].append("CodeGenTokenizerFast") + _import_structure["models.cohere"].append("CohereTokenizerFast") + _import_structure["models.convbert"].append("ConvBertTokenizerFast") + _import_structure["models.cpm"].append("CpmTokenizerFast") + _import_structure["models.deberta"].append("DebertaTokenizerFast") + _import_structure["models.deberta_v2"].append("DebertaV2TokenizerFast") + _import_structure["models.deprecated.realm"].append("RealmTokenizerFast") + _import_structure["models.deprecated.retribert"].append("RetriBertTokenizerFast") + _import_structure["models.distilbert"].append("DistilBertTokenizerFast") + _import_structure["models.dpr"].extend( + [ + "DPRContextEncoderTokenizerFast", + "DPRQuestionEncoderTokenizerFast", + "DPRReaderTokenizerFast", + ] + ) + _import_structure["models.electra"].append("ElectraTokenizerFast") + _import_structure["models.fnet"].append("FNetTokenizerFast") + _import_structure["models.funnel"].append("FunnelTokenizerFast") + _import_structure["models.gemma"].append("GemmaTokenizerFast") + _import_structure["models.gpt2"].append("GPT2TokenizerFast") + _import_structure["models.gpt_neox"].append("GPTNeoXTokenizerFast") + _import_structure["models.gpt_neox_japanese"].append("GPTNeoXJapaneseTokenizer") + _import_structure["models.herbert"].append("HerbertTokenizerFast") + _import_structure["models.layoutlm"].append("LayoutLMTokenizerFast") + _import_structure["models.layoutlmv2"].append("LayoutLMv2TokenizerFast") + _import_structure["models.layoutlmv3"].append("LayoutLMv3TokenizerFast") + _import_structure["models.layoutxlm"].append("LayoutXLMTokenizerFast") + _import_structure["models.led"].append("LEDTokenizerFast") + _import_structure["models.llama"].append("LlamaTokenizerFast") + _import_structure["models.longformer"].append("LongformerTokenizerFast") + _import_structure["models.lxmert"].append("LxmertTokenizerFast") + _import_structure["models.markuplm"].append("MarkupLMTokenizerFast") + _import_structure["models.mbart"].append("MBartTokenizerFast") + _import_structure["models.mbart50"].append("MBart50TokenizerFast") + _import_structure["models.mobilebert"].append("MobileBertTokenizerFast") + _import_structure["models.mpnet"].append("MPNetTokenizerFast") + _import_structure["models.mt5"].append("MT5TokenizerFast") + _import_structure["models.mvp"].append("MvpTokenizerFast") + _import_structure["models.nllb"].append("NllbTokenizerFast") + _import_structure["models.nougat"].append("NougatTokenizerFast") + _import_structure["models.openai"].append("OpenAIGPTTokenizerFast") + _import_structure["models.pegasus"].append("PegasusTokenizerFast") + _import_structure["models.qwen2"].append("Qwen2TokenizerFast") + _import_structure["models.reformer"].append("ReformerTokenizerFast") + _import_structure["models.rembert"].append("RemBertTokenizerFast") + _import_structure["models.roberta"].append("RobertaTokenizerFast") + _import_structure["models.roformer"].append("RoFormerTokenizerFast") + _import_structure["models.seamless_m4t"].append("SeamlessM4TTokenizerFast") + _import_structure["models.splinter"].append("SplinterTokenizerFast") + _import_structure["models.squeezebert"].append("SqueezeBertTokenizerFast") + _import_structure["models.t5"].append("T5TokenizerFast") + _import_structure["models.udop"].append("UdopTokenizerFast") + _import_structure["models.whisper"].append("WhisperTokenizerFast") + _import_structure["models.xglm"].append("XGLMTokenizerFast") + _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizerFast") + _import_structure["models.xlnet"].append("XLNetTokenizerFast") + _import_structure["tokenization_utils_fast"] = ["PreTrainedTokenizerFast"] + + +try: + if not (is_sentencepiece_available() and is_tokenizers_available()): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_sentencepiece_and_tokenizers_objects + + _import_structure["utils.dummy_sentencepiece_and_tokenizers_objects"] = [ + name for name in dir(dummy_sentencepiece_and_tokenizers_objects) if not name.startswith("_") + ] +else: + _import_structure["convert_slow_tokenizer"] = [ + "SLOW_TO_FAST_CONVERTERS", + "convert_slow_tokenizer", + ] + +# Tensorflow-text-specific objects +try: + if not is_tensorflow_text_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_tensorflow_text_objects + + _import_structure["utils.dummy_tensorflow_text_objects"] = [ + name for name in dir(dummy_tensorflow_text_objects) if not name.startswith("_") + ] +else: + _import_structure["models.bert"].append("TFBertTokenizer") + +# keras-nlp-specific objects +try: + if not is_keras_nlp_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_keras_nlp_objects + + _import_structure["utils.dummy_keras_nlp_objects"] = [ + name for name in dir(dummy_keras_nlp_objects) if not name.startswith("_") + ] +else: + _import_structure["models.gpt2"].append("TFGPT2Tokenizer") + +# Vision-specific objects +try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_vision_objects + + _import_structure["utils.dummy_vision_objects"] = [ + name for name in dir(dummy_vision_objects) if not name.startswith("_") + ] +else: + _import_structure["image_processing_base"] = ["ImageProcessingMixin"] + _import_structure["image_processing_utils"] = ["BaseImageProcessor"] + _import_structure["image_utils"] = ["ImageFeatureExtractionMixin"] + _import_structure["models.aria"].extend(["AriaImageProcessor"]) + _import_structure["models.beit"].extend(["BeitFeatureExtractor", "BeitImageProcessor"]) + _import_structure["models.bit"].extend(["BitImageProcessor"]) + _import_structure["models.blip"].extend(["BlipImageProcessor"]) + _import_structure["models.bridgetower"].append("BridgeTowerImageProcessor") + _import_structure["models.chameleon"].append("ChameleonImageProcessor") + _import_structure["models.chinese_clip"].extend(["ChineseCLIPFeatureExtractor", "ChineseCLIPImageProcessor"]) + _import_structure["models.clip"].extend(["CLIPFeatureExtractor", "CLIPImageProcessor"]) + _import_structure["models.conditional_detr"].extend( + ["ConditionalDetrFeatureExtractor", "ConditionalDetrImageProcessor"] + ) + _import_structure["models.convnext"].extend(["ConvNextFeatureExtractor", "ConvNextImageProcessor"]) + _import_structure["models.deformable_detr"].extend( + ["DeformableDetrFeatureExtractor", "DeformableDetrImageProcessor"] + ) + _import_structure["models.deit"].extend(["DeiTFeatureExtractor", "DeiTImageProcessor"]) + _import_structure["models.deprecated.deta"].append("DetaImageProcessor") + _import_structure["models.deprecated.efficientformer"].append("EfficientFormerImageProcessor") + _import_structure["models.deprecated.tvlt"].append("TvltImageProcessor") + _import_structure["models.deprecated.vit_hybrid"].extend(["ViTHybridImageProcessor"]) + _import_structure["models.depth_pro"].extend(["DepthProImageProcessor", "DepthProImageProcessorFast"]) + _import_structure["models.detr"].extend(["DetrFeatureExtractor", "DetrImageProcessor"]) + _import_structure["models.donut"].extend(["DonutFeatureExtractor", "DonutImageProcessor"]) + _import_structure["models.dpt"].extend(["DPTFeatureExtractor", "DPTImageProcessor"]) + _import_structure["models.efficientnet"].append("EfficientNetImageProcessor") + _import_structure["models.emu3"].append("Emu3ImageProcessor") + _import_structure["models.flava"].extend(["FlavaFeatureExtractor", "FlavaImageProcessor", "FlavaProcessor"]) + _import_structure["models.fuyu"].extend(["FuyuImageProcessor", "FuyuProcessor"]) + _import_structure["models.gemma3"].append("Gemma3ImageProcessor") + _import_structure["models.glpn"].extend(["GLPNFeatureExtractor", "GLPNImageProcessor"]) + _import_structure["models.got_ocr2"].extend(["GotOcr2ImageProcessor"]) + _import_structure["models.grounding_dino"].extend(["GroundingDinoImageProcessor"]) + _import_structure["models.idefics"].extend(["IdeficsImageProcessor"]) + _import_structure["models.idefics2"].extend(["Idefics2ImageProcessor"]) + _import_structure["models.idefics3"].extend(["Idefics3ImageProcessor"]) + _import_structure["models.imagegpt"].extend(["ImageGPTFeatureExtractor", "ImageGPTImageProcessor"]) + _import_structure["models.instructblipvideo"].extend(["InstructBlipVideoImageProcessor"]) + _import_structure["models.layoutlmv2"].extend(["LayoutLMv2FeatureExtractor", "LayoutLMv2ImageProcessor"]) + _import_structure["models.layoutlmv3"].extend(["LayoutLMv3FeatureExtractor", "LayoutLMv3ImageProcessor"]) + _import_structure["models.levit"].extend(["LevitFeatureExtractor", "LevitImageProcessor"]) + _import_structure["models.llava"].append("LlavaImageProcessor") + _import_structure["models.llava_next"].append("LlavaNextImageProcessor") + _import_structure["models.llava_next_video"].append("LlavaNextVideoImageProcessor") + _import_structure["models.llava_onevision"].extend( + ["LlavaOnevisionImageProcessor", "LlavaOnevisionVideoProcessor"] + ) + _import_structure["models.mask2former"].append("Mask2FormerImageProcessor") + _import_structure["models.maskformer"].extend(["MaskFormerFeatureExtractor", "MaskFormerImageProcessor"]) + _import_structure["models.mllama"].extend(["MllamaImageProcessor"]) + _import_structure["models.mobilenet_v1"].extend(["MobileNetV1FeatureExtractor", "MobileNetV1ImageProcessor"]) + _import_structure["models.mobilenet_v2"].extend(["MobileNetV2FeatureExtractor", "MobileNetV2ImageProcessor"]) + _import_structure["models.mobilevit"].extend(["MobileViTFeatureExtractor", "MobileViTImageProcessor"]) + _import_structure["models.nougat"].append("NougatImageProcessor") + _import_structure["models.oneformer"].extend(["OneFormerImageProcessor"]) + _import_structure["models.owlv2"].append("Owlv2ImageProcessor") + _import_structure["models.owlvit"].extend(["OwlViTFeatureExtractor", "OwlViTImageProcessor"]) + _import_structure["models.perceiver"].extend(["PerceiverFeatureExtractor", "PerceiverImageProcessor"]) + _import_structure["models.pix2struct"].extend(["Pix2StructImageProcessor"]) + _import_structure["models.pixtral"].append("PixtralImageProcessor") + _import_structure["models.poolformer"].extend(["PoolFormerFeatureExtractor", "PoolFormerImageProcessor"]) + _import_structure["models.pvt"].extend(["PvtImageProcessor"]) + _import_structure["models.qwen2_vl"].extend(["Qwen2VLImageProcessor"]) + _import_structure["models.rt_detr"].extend(["RTDetrImageProcessor"]) + _import_structure["models.sam"].extend(["SamImageProcessor"]) + _import_structure["models.segformer"].extend(["SegformerFeatureExtractor", "SegformerImageProcessor"]) + _import_structure["models.seggpt"].extend(["SegGptImageProcessor"]) + _import_structure["models.siglip"].append("SiglipImageProcessor") + _import_structure["models.siglip2"].append("Siglip2ImageProcessor") + _import_structure["models.smolvlm"].extend(["SmolVLMImageProcessor"]) + _import_structure["models.superglue"].extend(["SuperGlueImageProcessor"]) + _import_structure["models.superpoint"].extend(["SuperPointImageProcessor"]) + _import_structure["models.swin2sr"].append("Swin2SRImageProcessor") + _import_structure["models.textnet"].extend(["TextNetImageProcessor"]) + _import_structure["models.tvp"].append("TvpImageProcessor") + _import_structure["models.video_llava"].append("VideoLlavaImageProcessor") + _import_structure["models.videomae"].extend(["VideoMAEFeatureExtractor", "VideoMAEImageProcessor"]) + _import_structure["models.vilt"].extend(["ViltFeatureExtractor", "ViltImageProcessor", "ViltProcessor"]) + _import_structure["models.vit"].extend(["ViTFeatureExtractor", "ViTImageProcessor"]) + _import_structure["models.vitmatte"].append("VitMatteImageProcessor") + _import_structure["models.vitpose"].append("VitPoseImageProcessor") + _import_structure["models.vivit"].append("VivitImageProcessor") + _import_structure["models.yolos"].extend(["YolosFeatureExtractor", "YolosImageProcessor"]) + _import_structure["models.zoedepth"].append("ZoeDepthImageProcessor") + +try: + if not is_torchvision_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_torchvision_objects + + _import_structure["utils.dummy_torchvision_objects"] = [ + name for name in dir(dummy_torchvision_objects) if not name.startswith("_") + ] +else: + _import_structure["image_processing_utils_fast"] = ["BaseImageProcessorFast"] + _import_structure["models.blip"].append("BlipImageProcessorFast") + _import_structure["models.clip"].append("CLIPImageProcessorFast") + _import_structure["models.convnext"].append("ConvNextImageProcessorFast") + _import_structure["models.deformable_detr"].append("DeformableDetrImageProcessorFast") + _import_structure["models.deit"].append("DeiTImageProcessorFast") + _import_structure["models.depth_pro"].append("DepthProImageProcessorFast") + _import_structure["models.detr"].append("DetrImageProcessorFast") + _import_structure["models.gemma3"].append("Gemma3ImageProcessorFast") + _import_structure["models.got_ocr2"].append("GotOcr2ImageProcessorFast") + _import_structure["models.llava"].append("LlavaImageProcessorFast") + _import_structure["models.llava_next"].append("LlavaNextImageProcessorFast") + _import_structure["models.llava_onevision"].append("LlavaOnevisionImageProcessorFast") + _import_structure["models.pixtral"].append("PixtralImageProcessorFast") + _import_structure["models.qwen2_vl"].append("Qwen2VLImageProcessorFast") + _import_structure["models.rt_detr"].append("RTDetrImageProcessorFast") + _import_structure["models.siglip"].append("SiglipImageProcessorFast") + _import_structure["models.siglip2"].append("Siglip2ImageProcessorFast") + _import_structure["models.vit"].append("ViTImageProcessorFast") + +try: + if not (is_torchvision_available() and is_timm_available()): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_timm_and_torchvision_objects + + _import_structure["utils.dummy_timm_and_torchvision_objects"] = [ + name for name in dir(dummy_timm_and_torchvision_objects) if not name.startswith("_") + ] +else: + _import_structure["models.timm_wrapper"].extend(["TimmWrapperImageProcessor"]) + +# PyTorch-backed objects +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_pt_objects + + _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")] +else: + _import_structure["activations"] = [] + _import_structure["cache_utils"] = [ + "Cache", + "CacheConfig", + "DynamicCache", + "EncoderDecoderCache", + "HQQQuantizedCache", + "HybridCache", + "MambaCache", + "OffloadedCache", + "OffloadedStaticCache", + "QuantizedCache", + "QuantizedCacheConfig", + "QuantoQuantizedCache", + "SinkCache", + "SlidingWindowCache", + "StaticCache", + ] + _import_structure["data.datasets"] = [ + "GlueDataset", + "GlueDataTrainingArguments", + "LineByLineTextDataset", + "LineByLineWithRefDataset", + "LineByLineWithSOPTextDataset", + "SquadDataset", + "SquadDataTrainingArguments", + "TextDataset", + "TextDatasetForNextSentencePrediction", + ] + _import_structure["generation"].extend( + [ + "AlternatingCodebooksLogitsProcessor", + "BayesianDetectorConfig", + "BayesianDetectorModel", + "BeamScorer", + "BeamSearchScorer", + "ClassifierFreeGuidanceLogitsProcessor", + "ConstrainedBeamSearchScorer", + "Constraint", + "ConstraintListState", + "DisjunctiveConstraint", + "EncoderNoRepeatNGramLogitsProcessor", + "EncoderRepetitionPenaltyLogitsProcessor", + "EosTokenCriteria", + "EpsilonLogitsWarper", + "EtaLogitsWarper", + "ExponentialDecayLengthPenalty", + "ForcedBOSTokenLogitsProcessor", + "ForcedEOSTokenLogitsProcessor", + "GenerationMixin", + "HammingDiversityLogitsProcessor", + "InfNanRemoveLogitsProcessor", + "LogitNormalization", + "LogitsProcessor", + "LogitsProcessorList", + "MaxLengthCriteria", + "MaxTimeCriteria", + "MinLengthLogitsProcessor", + "MinNewTokensLengthLogitsProcessor", + "MinPLogitsWarper", + "NoBadWordsLogitsProcessor", + "NoRepeatNGramLogitsProcessor", + "PhrasalConstraint", + "PrefixConstrainedLogitsProcessor", + "RepetitionPenaltyLogitsProcessor", + "SequenceBiasLogitsProcessor", + "StoppingCriteria", + "StoppingCriteriaList", + "StopStringCriteria", + "SuppressTokensAtBeginLogitsProcessor", + "SuppressTokensLogitsProcessor", + "SynthIDTextWatermarkDetector", + "SynthIDTextWatermarkingConfig", + "SynthIDTextWatermarkLogitsProcessor", + "TemperatureLogitsWarper", + "TopKLogitsWarper", + "TopPLogitsWarper", + "TypicalLogitsWarper", + "UnbatchedClassifierFreeGuidanceLogitsProcessor", + "WatermarkDetector", + "WatermarkLogitsProcessor", + "WhisperTimeStampLogitsProcessor", + ] + ) + + # PyTorch domain libraries integration + _import_structure["integrations.executorch"] = [ + "TorchExportableModuleWithStaticCache", + "convert_and_export_with_cache", + ] + + _import_structure["modeling_flash_attention_utils"] = [] + _import_structure["modeling_outputs"] = [] + _import_structure["modeling_rope_utils"] = ["ROPE_INIT_FUNCTIONS"] + _import_structure["modeling_utils"] = ["PreTrainedModel"] + + # PyTorch models structure + + _import_structure["models.albert"].extend( + [ + "AlbertForMaskedLM", + "AlbertForMultipleChoice", + "AlbertForPreTraining", + "AlbertForQuestionAnswering", + "AlbertForSequenceClassification", + "AlbertForTokenClassification", + "AlbertModel", + "AlbertPreTrainedModel", + "load_tf_weights_in_albert", + ] + ) + + _import_structure["models.align"].extend( + [ + "AlignModel", + "AlignPreTrainedModel", + "AlignTextModel", + "AlignVisionModel", + ] + ) + _import_structure["models.altclip"].extend( + [ + "AltCLIPModel", + "AltCLIPPreTrainedModel", + "AltCLIPTextModel", + "AltCLIPVisionModel", + ] + ) + _import_structure["models.aria"].extend( + [ + "AriaForConditionalGeneration", + "AriaPreTrainedModel", + "AriaTextForCausalLM", + "AriaTextModel", + "AriaTextPreTrainedModel", + ] + ) + _import_structure["models.audio_spectrogram_transformer"].extend( + [ + "ASTForAudioClassification", + "ASTModel", + "ASTPreTrainedModel", + ] + ) + _import_structure["models.auto"].extend( + [ + "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING", + "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING", + "MODEL_FOR_AUDIO_XVECTOR_MAPPING", + "MODEL_FOR_BACKBONE_MAPPING", + "MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING", + "MODEL_FOR_CAUSAL_LM_MAPPING", + "MODEL_FOR_CTC_MAPPING", + "MODEL_FOR_DEPTH_ESTIMATION_MAPPING", + "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING", + "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", + "MODEL_FOR_IMAGE_MAPPING", + "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING", + "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING", + "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING", + "MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING", + "MODEL_FOR_KEYPOINT_DETECTION_MAPPING", + "MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING", + "MODEL_FOR_MASKED_LM_MAPPING", + "MODEL_FOR_MASK_GENERATION_MAPPING", + "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", + "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", + "MODEL_FOR_OBJECT_DETECTION_MAPPING", + "MODEL_FOR_PRETRAINING_MAPPING", + "MODEL_FOR_QUESTION_ANSWERING_MAPPING", + "MODEL_FOR_RETRIEVAL_MAPPING", + "MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING", + "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", + "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", + "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", + "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", + "MODEL_FOR_TEXT_ENCODING_MAPPING", + "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING", + "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING", + "MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING", + "MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING", + "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", + "MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING", + "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING", + "MODEL_FOR_VISION_2_SEQ_MAPPING", + "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING", + "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING", + "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING", + "MODEL_MAPPING", + "MODEL_WITH_LM_HEAD_MAPPING", + "AutoBackbone", + "AutoModel", + "AutoModelForAudioClassification", + "AutoModelForAudioFrameClassification", + "AutoModelForAudioXVector", + "AutoModelForCausalLM", + "AutoModelForCTC", + "AutoModelForDepthEstimation", + "AutoModelForDocumentQuestionAnswering", + "AutoModelForImageClassification", + "AutoModelForImageSegmentation", + "AutoModelForImageTextToText", + "AutoModelForImageToImage", + "AutoModelForInstanceSegmentation", + "AutoModelForKeypointDetection", + "AutoModelForMaskedImageModeling", + "AutoModelForMaskedLM", + "AutoModelForMaskGeneration", + "AutoModelForMultipleChoice", + "AutoModelForNextSentencePrediction", + "AutoModelForObjectDetection", + "AutoModelForPreTraining", + "AutoModelForQuestionAnswering", + "AutoModelForSemanticSegmentation", + "AutoModelForSeq2SeqLM", + "AutoModelForSequenceClassification", + "AutoModelForSpeechSeq2Seq", + "AutoModelForTableQuestionAnswering", + "AutoModelForTextEncoding", + "AutoModelForTextToSpectrogram", + "AutoModelForTextToWaveform", + "AutoModelForTokenClassification", + "AutoModelForUniversalSegmentation", + "AutoModelForVideoClassification", + "AutoModelForVision2Seq", + "AutoModelForVisualQuestionAnswering", + "AutoModelForZeroShotImageClassification", + "AutoModelForZeroShotObjectDetection", + "AutoModelWithLMHead", + ] + ) + _import_structure["models.autoformer"].extend( + [ + "AutoformerForPrediction", + "AutoformerModel", + "AutoformerPreTrainedModel", + ] + ) + _import_structure["models.aya_vision"].extend(["AyaVisionForConditionalGeneration", "AyaVisionPreTrainedModel"]) + _import_structure["models.bamba"].extend( + [ + "BambaForCausalLM", + "BambaModel", + "BambaPreTrainedModel", + ] + ) + _import_structure["models.bark"].extend( + [ + "BarkCausalModel", + "BarkCoarseModel", + "BarkFineModel", + "BarkModel", + "BarkPreTrainedModel", + "BarkSemanticModel", + ] + ) + _import_structure["models.bart"].extend( + [ + "BartForCausalLM", + "BartForConditionalGeneration", + "BartForQuestionAnswering", + "BartForSequenceClassification", + "BartModel", + "BartPretrainedModel", + "BartPreTrainedModel", + "PretrainedBartModel", + ] + ) + _import_structure["models.beit"].extend( + [ + "BeitBackbone", + "BeitForImageClassification", + "BeitForMaskedImageModeling", + "BeitForSemanticSegmentation", + "BeitModel", + "BeitPreTrainedModel", + ] + ) + _import_structure["models.bert"].extend( + [ + "BertForMaskedLM", + "BertForMultipleChoice", + "BertForNextSentencePrediction", + "BertForPreTraining", + "BertForQuestionAnswering", + "BertForSequenceClassification", + "BertForTokenClassification", + "BertLMHeadModel", + "BertModel", + "BertPreTrainedModel", + "load_tf_weights_in_bert", + ] + ) + _import_structure["models.bert_generation"].extend( + [ + "BertGenerationDecoder", + "BertGenerationEncoder", + "BertGenerationPreTrainedModel", + "load_tf_weights_in_bert_generation", + ] + ) + _import_structure["models.big_bird"].extend( + [ + "BigBirdForCausalLM", + "BigBirdForMaskedLM", + "BigBirdForMultipleChoice", + "BigBirdForPreTraining", + "BigBirdForQuestionAnswering", + "BigBirdForSequenceClassification", + "BigBirdForTokenClassification", + "BigBirdModel", + "BigBirdPreTrainedModel", + "load_tf_weights_in_big_bird", + ] + ) + _import_structure["models.bigbird_pegasus"].extend( + [ + "BigBirdPegasusForCausalLM", + "BigBirdPegasusForConditionalGeneration", + "BigBirdPegasusForQuestionAnswering", + "BigBirdPegasusForSequenceClassification", + "BigBirdPegasusModel", + "BigBirdPegasusPreTrainedModel", + ] + ) + _import_structure["models.biogpt"].extend( + [ + "BioGptForCausalLM", + "BioGptForSequenceClassification", + "BioGptForTokenClassification", + "BioGptModel", + "BioGptPreTrainedModel", + ] + ) + _import_structure["models.bit"].extend( + [ + "BitBackbone", + "BitForImageClassification", + "BitModel", + "BitPreTrainedModel", + ] + ) + _import_structure["models.blenderbot"].extend( + [ + "BlenderbotForCausalLM", + "BlenderbotForConditionalGeneration", + "BlenderbotModel", + "BlenderbotPreTrainedModel", + ] + ) + _import_structure["models.blenderbot_small"].extend( + [ + "BlenderbotSmallForCausalLM", + "BlenderbotSmallForConditionalGeneration", + "BlenderbotSmallModel", + "BlenderbotSmallPreTrainedModel", + ] + ) + _import_structure["models.blip"].extend( + [ + "BlipForConditionalGeneration", + "BlipForImageTextRetrieval", + "BlipForQuestionAnswering", + "BlipModel", + "BlipPreTrainedModel", + "BlipTextModel", + "BlipVisionModel", + ] + ) + _import_structure["models.blip_2"].extend( + [ + "Blip2ForConditionalGeneration", + "Blip2ForImageTextRetrieval", + "Blip2Model", + "Blip2PreTrainedModel", + "Blip2QFormerModel", + "Blip2TextModelWithProjection", + "Blip2VisionModel", + "Blip2VisionModelWithProjection", + ] + ) + _import_structure["models.bloom"].extend( + [ + "BloomForCausalLM", + "BloomForQuestionAnswering", + "BloomForSequenceClassification", + "BloomForTokenClassification", + "BloomModel", + "BloomPreTrainedModel", + ] + ) + _import_structure["models.bridgetower"].extend( + [ + "BridgeTowerForContrastiveLearning", + "BridgeTowerForImageAndTextRetrieval", + "BridgeTowerForMaskedLM", + "BridgeTowerModel", + "BridgeTowerPreTrainedModel", + ] + ) + _import_structure["models.bros"].extend( + [ + "BrosForTokenClassification", + "BrosModel", + "BrosPreTrainedModel", + "BrosProcessor", + "BrosSpadeEEForTokenClassification", + "BrosSpadeELForTokenClassification", + ] + ) + _import_structure["models.camembert"].extend( + [ + "CamembertForCausalLM", + "CamembertForMaskedLM", + "CamembertForMultipleChoice", + "CamembertForQuestionAnswering", + "CamembertForSequenceClassification", + "CamembertForTokenClassification", + "CamembertModel", + "CamembertPreTrainedModel", + ] + ) + _import_structure["models.canine"].extend( + [ + "CanineForMultipleChoice", + "CanineForQuestionAnswering", + "CanineForSequenceClassification", + "CanineForTokenClassification", + "CanineModel", + "CaninePreTrainedModel", + "load_tf_weights_in_canine", + ] + ) + _import_structure["models.chameleon"].extend( + [ + "ChameleonForConditionalGeneration", + "ChameleonModel", + "ChameleonPreTrainedModel", + "ChameleonProcessor", + "ChameleonVQVAE", + ] + ) + _import_structure["models.chinese_clip"].extend( + [ + "ChineseCLIPModel", + "ChineseCLIPPreTrainedModel", + "ChineseCLIPTextModel", + "ChineseCLIPVisionModel", + ] + ) + _import_structure["models.clap"].extend( + [ + "ClapAudioModel", + "ClapAudioModelWithProjection", + "ClapFeatureExtractor", + "ClapModel", + "ClapPreTrainedModel", + "ClapTextModel", + "ClapTextModelWithProjection", + ] + ) + _import_structure["models.clip"].extend( + [ + "CLIPForImageClassification", + "CLIPModel", + "CLIPPreTrainedModel", + "CLIPTextModel", + "CLIPTextModelWithProjection", + "CLIPVisionModel", + "CLIPVisionModelWithProjection", + ] + ) + _import_structure["models.clipseg"].extend( + [ + "CLIPSegForImageSegmentation", + "CLIPSegModel", + "CLIPSegPreTrainedModel", + "CLIPSegTextModel", + "CLIPSegVisionModel", + ] + ) + _import_structure["models.clvp"].extend( + [ + "ClvpDecoder", + "ClvpEncoder", + "ClvpForCausalLM", + "ClvpModel", + "ClvpModelForConditionalGeneration", + "ClvpPreTrainedModel", + ] + ) + _import_structure["models.codegen"].extend( + [ + "CodeGenForCausalLM", + "CodeGenModel", + "CodeGenPreTrainedModel", + ] + ) + _import_structure["models.cohere"].extend(["CohereForCausalLM", "CohereModel", "CoherePreTrainedModel"]) + _import_structure["models.cohere2"].extend(["Cohere2ForCausalLM", "Cohere2Model", "Cohere2PreTrainedModel"]) + _import_structure["models.colpali"].extend( + [ + "ColPaliForRetrieval", + "ColPaliPreTrainedModel", + ] + ) + _import_structure["models.conditional_detr"].extend( + [ + "ConditionalDetrForObjectDetection", + "ConditionalDetrForSegmentation", + "ConditionalDetrModel", + "ConditionalDetrPreTrainedModel", + ] + ) + _import_structure["models.convbert"].extend( + [ + "ConvBertForMaskedLM", + "ConvBertForMultipleChoice", + "ConvBertForQuestionAnswering", + "ConvBertForSequenceClassification", + "ConvBertForTokenClassification", + "ConvBertModel", + "ConvBertPreTrainedModel", + "load_tf_weights_in_convbert", + ] + ) + _import_structure["models.convnext"].extend( + [ + "ConvNextBackbone", + "ConvNextForImageClassification", + "ConvNextModel", + "ConvNextPreTrainedModel", + ] + ) + _import_structure["models.convnextv2"].extend( + [ + "ConvNextV2Backbone", + "ConvNextV2ForImageClassification", + "ConvNextV2Model", + "ConvNextV2PreTrainedModel", + ] + ) + _import_structure["models.cpmant"].extend( + [ + "CpmAntForCausalLM", + "CpmAntModel", + "CpmAntPreTrainedModel", + ] + ) + _import_structure["models.ctrl"].extend( + [ + "CTRLForSequenceClassification", + "CTRLLMHeadModel", + "CTRLModel", + "CTRLPreTrainedModel", + ] + ) + _import_structure["models.cvt"].extend( + [ + "CvtForImageClassification", + "CvtModel", + "CvtPreTrainedModel", + ] + ) + _import_structure["models.dab_detr"].extend( + [ + "DabDetrForObjectDetection", + "DabDetrModel", + "DabDetrPreTrainedModel", + ] + ) + _import_structure["models.dac"].extend( + [ + "DacModel", + "DacPreTrainedModel", + ] + ) + _import_structure["models.data2vec"].extend( + [ + "Data2VecAudioForAudioFrameClassification", + "Data2VecAudioForCTC", + "Data2VecAudioForSequenceClassification", + "Data2VecAudioForXVector", + "Data2VecAudioModel", + "Data2VecAudioPreTrainedModel", + "Data2VecTextForCausalLM", + "Data2VecTextForMaskedLM", + "Data2VecTextForMultipleChoice", + "Data2VecTextForQuestionAnswering", + "Data2VecTextForSequenceClassification", + "Data2VecTextForTokenClassification", + "Data2VecTextModel", + "Data2VecTextPreTrainedModel", + "Data2VecVisionForImageClassification", + "Data2VecVisionForSemanticSegmentation", + "Data2VecVisionModel", + "Data2VecVisionPreTrainedModel", + ] + ) + _import_structure["models.dbrx"].extend( + [ + "DbrxForCausalLM", + "DbrxModel", + "DbrxPreTrainedModel", + ] + ) + _import_structure["models.deberta"].extend( + [ + "DebertaForMaskedLM", + "DebertaForQuestionAnswering", + "DebertaForSequenceClassification", + "DebertaForTokenClassification", + "DebertaModel", + "DebertaPreTrainedModel", + ] + ) + _import_structure["models.deberta_v2"].extend( + [ + "DebertaV2ForMaskedLM", + "DebertaV2ForMultipleChoice", + "DebertaV2ForQuestionAnswering", + "DebertaV2ForSequenceClassification", + "DebertaV2ForTokenClassification", + "DebertaV2Model", + "DebertaV2PreTrainedModel", + ] + ) + _import_structure["models.decision_transformer"].extend( + [ + "DecisionTransformerGPT2Model", + "DecisionTransformerGPT2PreTrainedModel", + "DecisionTransformerModel", + "DecisionTransformerPreTrainedModel", + ] + ) + _import_structure["models.deformable_detr"].extend( + [ + "DeformableDetrForObjectDetection", + "DeformableDetrModel", + "DeformableDetrPreTrainedModel", + ] + ) + _import_structure["models.deit"].extend( + [ + "DeiTForImageClassification", + "DeiTForImageClassificationWithTeacher", + "DeiTForMaskedImageModeling", + "DeiTModel", + "DeiTPreTrainedModel", + ] + ) + _import_structure["models.deprecated.deta"].extend( + [ + "DetaForObjectDetection", + "DetaModel", + "DetaPreTrainedModel", + ] + ) + _import_structure["models.deprecated.efficientformer"].extend( + [ + "EfficientFormerForImageClassification", + "EfficientFormerForImageClassificationWithTeacher", + "EfficientFormerModel", + "EfficientFormerPreTrainedModel", + ] + ) + _import_structure["models.deprecated.ernie_m"].extend( + [ + "ErnieMForInformationExtraction", + "ErnieMForMultipleChoice", + "ErnieMForQuestionAnswering", + "ErnieMForSequenceClassification", + "ErnieMForTokenClassification", + "ErnieMModel", + "ErnieMPreTrainedModel", + ] + ) + _import_structure["models.deprecated.gptsan_japanese"].extend( + [ + "GPTSanJapaneseForConditionalGeneration", + "GPTSanJapaneseModel", + "GPTSanJapanesePreTrainedModel", + ] + ) + _import_structure["models.deprecated.graphormer"].extend( + [ + "GraphormerForGraphClassification", + "GraphormerModel", + "GraphormerPreTrainedModel", + ] + ) + _import_structure["models.deprecated.jukebox"].extend( + [ + "JukeboxModel", + "JukeboxPreTrainedModel", + "JukeboxPrior", + "JukeboxVQVAE", + ] + ) + _import_structure["models.deprecated.mctct"].extend( + [ + "MCTCTForCTC", + "MCTCTModel", + "MCTCTPreTrainedModel", + ] + ) + _import_structure["models.deprecated.mega"].extend( + [ + "MegaForCausalLM", + "MegaForMaskedLM", + "MegaForMultipleChoice", + "MegaForQuestionAnswering", + "MegaForSequenceClassification", + "MegaForTokenClassification", + "MegaModel", + "MegaPreTrainedModel", + ] + ) + _import_structure["models.deprecated.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"]) + _import_structure["models.deprecated.nat"].extend( + [ + "NatBackbone", + "NatForImageClassification", + "NatModel", + "NatPreTrainedModel", + ] + ) + _import_structure["models.deprecated.nezha"].extend( + [ + "NezhaForMaskedLM", + "NezhaForMultipleChoice", + "NezhaForNextSentencePrediction", + "NezhaForPreTraining", + "NezhaForQuestionAnswering", + "NezhaForSequenceClassification", + "NezhaForTokenClassification", + "NezhaModel", + "NezhaPreTrainedModel", + ] + ) + _import_structure["models.deprecated.open_llama"].extend( + [ + "OpenLlamaForCausalLM", + "OpenLlamaForSequenceClassification", + "OpenLlamaModel", + "OpenLlamaPreTrainedModel", + ] + ) + _import_structure["models.deprecated.qdqbert"].extend( + [ + "QDQBertForMaskedLM", + "QDQBertForMultipleChoice", + "QDQBertForNextSentencePrediction", + "QDQBertForQuestionAnswering", + "QDQBertForSequenceClassification", + "QDQBertForTokenClassification", + "QDQBertLMHeadModel", + "QDQBertModel", + "QDQBertPreTrainedModel", + "load_tf_weights_in_qdqbert", + ] + ) + _import_structure["models.deprecated.realm"].extend( + [ + "RealmEmbedder", + "RealmForOpenQA", + "RealmKnowledgeAugEncoder", + "RealmPreTrainedModel", + "RealmReader", + "RealmRetriever", + "RealmScorer", + "load_tf_weights_in_realm", + ] + ) + _import_structure["models.deprecated.retribert"].extend( + [ + "RetriBertModel", + "RetriBertPreTrainedModel", + ] + ) + _import_structure["models.deprecated.speech_to_text_2"].extend( + ["Speech2Text2ForCausalLM", "Speech2Text2PreTrainedModel"] + ) + _import_structure["models.deprecated.trajectory_transformer"].extend( + [ + "TrajectoryTransformerModel", + "TrajectoryTransformerPreTrainedModel", + ] + ) + _import_structure["models.deprecated.transfo_xl"].extend( + [ + "AdaptiveEmbedding", + "TransfoXLForSequenceClassification", + "TransfoXLLMHeadModel", + "TransfoXLModel", + "TransfoXLPreTrainedModel", + "load_tf_weights_in_transfo_xl", + ] + ) + _import_structure["models.deprecated.tvlt"].extend( + [ + "TvltForAudioVisualClassification", + "TvltForPreTraining", + "TvltModel", + "TvltPreTrainedModel", + ] + ) + _import_structure["models.deprecated.van"].extend( + [ + "VanForImageClassification", + "VanModel", + "VanPreTrainedModel", + ] + ) + _import_structure["models.deprecated.vit_hybrid"].extend( + [ + "ViTHybridForImageClassification", + "ViTHybridModel", + "ViTHybridPreTrainedModel", + ] + ) + _import_structure["models.deprecated.xlm_prophetnet"].extend( + [ + "XLMProphetNetDecoder", + "XLMProphetNetEncoder", + "XLMProphetNetForCausalLM", + "XLMProphetNetForConditionalGeneration", + "XLMProphetNetModel", + "XLMProphetNetPreTrainedModel", + ] + ) + _import_structure["models.depth_anything"].extend( + [ + "DepthAnythingForDepthEstimation", + "DepthAnythingPreTrainedModel", + ] + ) + _import_structure["models.depth_pro"].extend( + [ + "DepthProForDepthEstimation", + "DepthProModel", + "DepthProPreTrainedModel", + ] + ) + _import_structure["models.detr"].extend( + [ + "DetrForObjectDetection", + "DetrForSegmentation", + "DetrModel", + "DetrPreTrainedModel", + ] + ) + _import_structure["models.diffllama"].extend( + [ + "DiffLlamaForCausalLM", + "DiffLlamaForQuestionAnswering", + "DiffLlamaForSequenceClassification", + "DiffLlamaForTokenClassification", + "DiffLlamaModel", + "DiffLlamaPreTrainedModel", + ] + ) + _import_structure["models.dinat"].extend( + [ + "DinatBackbone", + "DinatForImageClassification", + "DinatModel", + "DinatPreTrainedModel", + ] + ) + _import_structure["models.dinov2"].extend( + [ + "Dinov2Backbone", + "Dinov2ForImageClassification", + "Dinov2Model", + "Dinov2PreTrainedModel", + ] + ) + _import_structure["models.dinov2_with_registers"].extend( + [ + "Dinov2WithRegistersBackbone", + "Dinov2WithRegistersForImageClassification", + "Dinov2WithRegistersModel", + "Dinov2WithRegistersPreTrainedModel", + ] + ) + _import_structure["models.distilbert"].extend( + [ + "DistilBertForMaskedLM", + "DistilBertForMultipleChoice", + "DistilBertForQuestionAnswering", + "DistilBertForSequenceClassification", + "DistilBertForTokenClassification", + "DistilBertModel", + "DistilBertPreTrainedModel", + ] + ) + _import_structure["models.donut"].extend( + [ + "DonutSwinModel", + "DonutSwinPreTrainedModel", + ] + ) + _import_structure["models.dpr"].extend( + [ + "DPRContextEncoder", + "DPRPretrainedContextEncoder", + "DPRPreTrainedModel", + "DPRPretrainedQuestionEncoder", + "DPRPretrainedReader", + "DPRQuestionEncoder", + "DPRReader", + ] + ) + _import_structure["models.dpt"].extend( + [ + "DPTForDepthEstimation", + "DPTForSemanticSegmentation", + "DPTModel", + "DPTPreTrainedModel", + ] + ) + _import_structure["models.efficientnet"].extend( + [ + "EfficientNetForImageClassification", + "EfficientNetModel", + "EfficientNetPreTrainedModel", + ] + ) + _import_structure["models.electra"].extend( + [ + "ElectraForCausalLM", + "ElectraForMaskedLM", + "ElectraForMultipleChoice", + "ElectraForPreTraining", + "ElectraForQuestionAnswering", + "ElectraForSequenceClassification", + "ElectraForTokenClassification", + "ElectraModel", + "ElectraPreTrainedModel", + "load_tf_weights_in_electra", + ] + ) + _import_structure["models.emu3"].extend( + [ + "Emu3ForCausalLM", + "Emu3ForConditionalGeneration", + "Emu3PreTrainedModel", + "Emu3TextModel", + "Emu3VQVAE", + ] + ) + _import_structure["models.encodec"].extend( + [ + "EncodecModel", + "EncodecPreTrainedModel", + ] + ) + _import_structure["models.encoder_decoder"].append("EncoderDecoderModel") + _import_structure["models.ernie"].extend( + [ + "ErnieForCausalLM", + "ErnieForMaskedLM", + "ErnieForMultipleChoice", + "ErnieForNextSentencePrediction", + "ErnieForPreTraining", + "ErnieForQuestionAnswering", + "ErnieForSequenceClassification", + "ErnieForTokenClassification", + "ErnieModel", + "ErniePreTrainedModel", + ] + ) + _import_structure["models.esm"].extend( + [ + "EsmFoldPreTrainedModel", + "EsmForMaskedLM", + "EsmForProteinFolding", + "EsmForSequenceClassification", + "EsmForTokenClassification", + "EsmModel", + "EsmPreTrainedModel", + ] + ) + _import_structure["models.falcon"].extend( + [ + "FalconForCausalLM", + "FalconForQuestionAnswering", + "FalconForSequenceClassification", + "FalconForTokenClassification", + "FalconModel", + "FalconPreTrainedModel", + ] + ) + _import_structure["models.falcon_mamba"].extend( + [ + "FalconMambaForCausalLM", + "FalconMambaModel", + "FalconMambaPreTrainedModel", + ] + ) + _import_structure["models.fastspeech2_conformer"].extend( + [ + "FastSpeech2ConformerHifiGan", + "FastSpeech2ConformerModel", + "FastSpeech2ConformerPreTrainedModel", + "FastSpeech2ConformerWithHifiGan", + ] + ) + _import_structure["models.flaubert"].extend( + [ + "FlaubertForMultipleChoice", + "FlaubertForQuestionAnswering", + "FlaubertForQuestionAnsweringSimple", + "FlaubertForSequenceClassification", + "FlaubertForTokenClassification", + "FlaubertModel", + "FlaubertPreTrainedModel", + "FlaubertWithLMHeadModel", + ] + ) + _import_structure["models.flava"].extend( + [ + "FlavaForPreTraining", + "FlavaImageCodebook", + "FlavaImageModel", + "FlavaModel", + "FlavaMultimodalModel", + "FlavaPreTrainedModel", + "FlavaTextModel", + ] + ) + _import_structure["models.fnet"].extend( + [ + "FNetForMaskedLM", + "FNetForMultipleChoice", + "FNetForNextSentencePrediction", + "FNetForPreTraining", + "FNetForQuestionAnswering", + "FNetForSequenceClassification", + "FNetForTokenClassification", + "FNetModel", + "FNetPreTrainedModel", + ] + ) + _import_structure["models.focalnet"].extend( + [ + "FocalNetBackbone", + "FocalNetForImageClassification", + "FocalNetForMaskedImageModeling", + "FocalNetModel", + "FocalNetPreTrainedModel", + ] + ) + _import_structure["models.fsmt"].extend(["FSMTForConditionalGeneration", "FSMTModel", "PretrainedFSMTModel"]) + _import_structure["models.funnel"].extend( + [ + "FunnelBaseModel", + "FunnelForMaskedLM", + "FunnelForMultipleChoice", + "FunnelForPreTraining", + "FunnelForQuestionAnswering", + "FunnelForSequenceClassification", + "FunnelForTokenClassification", + "FunnelModel", + "FunnelPreTrainedModel", + "load_tf_weights_in_funnel", + ] + ) + _import_structure["models.fuyu"].extend(["FuyuForCausalLM", "FuyuPreTrainedModel"]) + _import_structure["models.gemma"].extend( + [ + "GemmaForCausalLM", + "GemmaForSequenceClassification", + "GemmaForTokenClassification", + "GemmaModel", + "GemmaPreTrainedModel", + ] + ) + _import_structure["models.gemma2"].extend( + [ + "Gemma2ForCausalLM", + "Gemma2ForSequenceClassification", + "Gemma2ForTokenClassification", + "Gemma2Model", + "Gemma2PreTrainedModel", + ] + ) + _import_structure["models.gemma3"].extend( + [ + "Gemma3ForCausalLM", + "Gemma3ForConditionalGeneration", + "Gemma3PreTrainedModel", + "Gemma3TextModel", + ] + ) + _import_structure["models.git"].extend( + [ + "GitForCausalLM", + "GitModel", + "GitPreTrainedModel", + "GitVisionModel", + ] + ) + _import_structure["models.glm"].extend( + [ + "GlmForCausalLM", + "GlmForSequenceClassification", + "GlmForTokenClassification", + "GlmModel", + "GlmPreTrainedModel", + ] + ) + _import_structure["models.glpn"].extend( + [ + "GLPNForDepthEstimation", + "GLPNModel", + "GLPNPreTrainedModel", + ] + ) + _import_structure["models.got_ocr2"].extend( + [ + "GotOcr2ForConditionalGeneration", + "GotOcr2PreTrainedModel", + ] + ) + _import_structure["models.gpt2"].extend( + [ + "GPT2DoubleHeadsModel", + "GPT2ForQuestionAnswering", + "GPT2ForSequenceClassification", + "GPT2ForTokenClassification", + "GPT2LMHeadModel", + "GPT2Model", + "GPT2PreTrainedModel", + "load_tf_weights_in_gpt2", + ] + ) + _import_structure["models.gpt_bigcode"].extend( + [ + "GPTBigCodeForCausalLM", + "GPTBigCodeForSequenceClassification", + "GPTBigCodeForTokenClassification", + "GPTBigCodeModel", + "GPTBigCodePreTrainedModel", + ] + ) + _import_structure["models.gpt_neo"].extend( + [ + "GPTNeoForCausalLM", + "GPTNeoForQuestionAnswering", + "GPTNeoForSequenceClassification", + "GPTNeoForTokenClassification", + "GPTNeoModel", + "GPTNeoPreTrainedModel", + "load_tf_weights_in_gpt_neo", + ] + ) + _import_structure["models.gpt_neox"].extend( + [ + "GPTNeoXForCausalLM", + "GPTNeoXForQuestionAnswering", + "GPTNeoXForSequenceClassification", + "GPTNeoXForTokenClassification", + "GPTNeoXModel", + "GPTNeoXPreTrainedModel", + ] + ) + _import_structure["models.gpt_neox_japanese"].extend( + [ + "GPTNeoXJapaneseForCausalLM", + "GPTNeoXJapaneseModel", + "GPTNeoXJapanesePreTrainedModel", + ] + ) + _import_structure["models.gptj"].extend( + [ + "GPTJForCausalLM", + "GPTJForQuestionAnswering", + "GPTJForSequenceClassification", + "GPTJModel", + "GPTJPreTrainedModel", + ] + ) + _import_structure["models.granite"].extend( + [ + "GraniteForCausalLM", + "GraniteModel", + "GranitePreTrainedModel", + ] + ) + _import_structure["models.granitemoe"].extend( + [ + "GraniteMoeForCausalLM", + "GraniteMoeModel", + "GraniteMoePreTrainedModel", + ] + ) + + _import_structure["models.granitemoeshared"].extend( + [ + "GraniteMoeSharedForCausalLM", + "GraniteMoeSharedModel", + "GraniteMoeSharedPreTrainedModel", + ] + ) + _import_structure["models.grounding_dino"].extend( + [ + "GroundingDinoForObjectDetection", + "GroundingDinoModel", + "GroundingDinoPreTrainedModel", + ] + ) + _import_structure["models.groupvit"].extend( + [ + "GroupViTModel", + "GroupViTPreTrainedModel", + "GroupViTTextModel", + "GroupViTVisionModel", + ] + ) + _import_structure["models.helium"].extend( + [ + "HeliumForCausalLM", + "HeliumForSequenceClassification", + "HeliumForTokenClassification", + "HeliumModel", + "HeliumPreTrainedModel", + ] + ) + _import_structure["models.hiera"].extend( + [ + "HieraBackbone", + "HieraForImageClassification", + "HieraForPreTraining", + "HieraModel", + "HieraPreTrainedModel", + ] + ) + _import_structure["models.hubert"].extend( + [ + "HubertForCTC", + "HubertForSequenceClassification", + "HubertModel", + "HubertPreTrainedModel", + ] + ) + _import_structure["models.ibert"].extend( + [ + "IBertForMaskedLM", + "IBertForMultipleChoice", + "IBertForQuestionAnswering", + "IBertForSequenceClassification", + "IBertForTokenClassification", + "IBertModel", + "IBertPreTrainedModel", + ] + ) + _import_structure["models.idefics"].extend( + [ + "IdeficsForVisionText2Text", + "IdeficsModel", + "IdeficsPreTrainedModel", + "IdeficsProcessor", + ] + ) + _import_structure["models.idefics2"].extend( + [ + "Idefics2ForConditionalGeneration", + "Idefics2Model", + "Idefics2PreTrainedModel", + "Idefics2Processor", + ] + ) + _import_structure["models.idefics3"].extend( + [ + "Idefics3ForConditionalGeneration", + "Idefics3Model", + "Idefics3PreTrainedModel", + "Idefics3Processor", + "Idefics3VisionConfig", + "Idefics3VisionTransformer", + ] + ) + _import_structure["models.ijepa"].extend( + [ + "IJepaForImageClassification", + "IJepaModel", + "IJepaPreTrainedModel", + ] + ) + _import_structure["models.imagegpt"].extend( + [ + "ImageGPTForCausalImageModeling", + "ImageGPTForImageClassification", + "ImageGPTModel", + "ImageGPTPreTrainedModel", + "load_tf_weights_in_imagegpt", + ] + ) + _import_structure["models.informer"].extend( + [ + "InformerForPrediction", + "InformerModel", + "InformerPreTrainedModel", + ] + ) + _import_structure["models.instructblip"].extend( + [ + "InstructBlipForConditionalGeneration", + "InstructBlipPreTrainedModel", + "InstructBlipQFormerModel", + "InstructBlipVisionModel", + ] + ) + _import_structure["models.instructblipvideo"].extend( + [ + "InstructBlipVideoForConditionalGeneration", + "InstructBlipVideoPreTrainedModel", + "InstructBlipVideoQFormerModel", + "InstructBlipVideoVisionModel", + ] + ) + _import_structure["models.jamba"].extend( + [ + "JambaForCausalLM", + "JambaForSequenceClassification", + "JambaModel", + "JambaPreTrainedModel", + ] + ) + _import_structure["models.jetmoe"].extend( + [ + "JetMoeForCausalLM", + "JetMoeForSequenceClassification", + "JetMoeModel", + "JetMoePreTrainedModel", + ] + ) + _import_structure["models.kosmos2"].extend( + [ + "Kosmos2ForConditionalGeneration", + "Kosmos2Model", + "Kosmos2PreTrainedModel", + ] + ) + _import_structure["models.layoutlm"].extend( + [ + "LayoutLMForMaskedLM", + "LayoutLMForQuestionAnswering", + "LayoutLMForSequenceClassification", + "LayoutLMForTokenClassification", + "LayoutLMModel", + "LayoutLMPreTrainedModel", + ] + ) + _import_structure["models.layoutlmv2"].extend( + [ + "LayoutLMv2ForQuestionAnswering", + "LayoutLMv2ForSequenceClassification", + "LayoutLMv2ForTokenClassification", + "LayoutLMv2Model", + "LayoutLMv2PreTrainedModel", + ] + ) + _import_structure["models.layoutlmv3"].extend( + [ + "LayoutLMv3ForQuestionAnswering", + "LayoutLMv3ForSequenceClassification", + "LayoutLMv3ForTokenClassification", + "LayoutLMv3Model", + "LayoutLMv3PreTrainedModel", + ] + ) + _import_structure["models.led"].extend( + [ + "LEDForConditionalGeneration", + "LEDForQuestionAnswering", + "LEDForSequenceClassification", + "LEDModel", + "LEDPreTrainedModel", + ] + ) + _import_structure["models.levit"].extend( + [ + "LevitForImageClassification", + "LevitForImageClassificationWithTeacher", + "LevitModel", + "LevitPreTrainedModel", + ] + ) + _import_structure["models.lilt"].extend( + [ + "LiltForQuestionAnswering", + "LiltForSequenceClassification", + "LiltForTokenClassification", + "LiltModel", + "LiltPreTrainedModel", + ] + ) + _import_structure["models.llama"].extend( + [ + "LlamaForCausalLM", + "LlamaForQuestionAnswering", + "LlamaForSequenceClassification", + "LlamaForTokenClassification", + "LlamaModel", + "LlamaPreTrainedModel", + ] + ) + _import_structure["models.llava"].extend( + [ + "LlavaForConditionalGeneration", + "LlavaPreTrainedModel", + ] + ) + _import_structure["models.llava_next"].extend( + [ + "LlavaNextForConditionalGeneration", + "LlavaNextPreTrainedModel", + ] + ) + _import_structure["models.llava_next_video"].extend( + [ + "LlavaNextVideoForConditionalGeneration", + "LlavaNextVideoPreTrainedModel", + ] + ) + _import_structure["models.llava_onevision"].extend( + [ + "LlavaOnevisionForConditionalGeneration", + "LlavaOnevisionPreTrainedModel", + ] + ) + _import_structure["models.longformer"].extend( + [ + "LongformerForMaskedLM", + "LongformerForMultipleChoice", + "LongformerForQuestionAnswering", + "LongformerForSequenceClassification", + "LongformerForTokenClassification", + "LongformerModel", + "LongformerPreTrainedModel", + ] + ) + _import_structure["models.longt5"].extend( + [ + "LongT5EncoderModel", + "LongT5ForConditionalGeneration", + "LongT5Model", + "LongT5PreTrainedModel", + ] + ) + _import_structure["models.luke"].extend( + [ + "LukeForEntityClassification", + "LukeForEntityPairClassification", + "LukeForEntitySpanClassification", + "LukeForMaskedLM", + "LukeForMultipleChoice", + "LukeForQuestionAnswering", + "LukeForSequenceClassification", + "LukeForTokenClassification", + "LukeModel", + "LukePreTrainedModel", + ] + ) + _import_structure["models.lxmert"].extend( + [ + "LxmertEncoder", + "LxmertForPreTraining", + "LxmertForQuestionAnswering", + "LxmertModel", + "LxmertPreTrainedModel", + "LxmertVisualFeatureEncoder", + ] + ) + _import_structure["models.m2m_100"].extend( + [ + "M2M100ForConditionalGeneration", + "M2M100Model", + "M2M100PreTrainedModel", + ] + ) + _import_structure["models.mamba"].extend( + [ + "MambaForCausalLM", + "MambaModel", + "MambaPreTrainedModel", + ] + ) + _import_structure["models.mamba2"].extend( + [ + "Mamba2ForCausalLM", + "Mamba2Model", + "Mamba2PreTrainedModel", + ] + ) + _import_structure["models.marian"].extend( + ["MarianForCausalLM", "MarianModel", "MarianMTModel", "MarianPreTrainedModel"] + ) + _import_structure["models.markuplm"].extend( + [ + "MarkupLMForQuestionAnswering", + "MarkupLMForSequenceClassification", + "MarkupLMForTokenClassification", + "MarkupLMModel", + "MarkupLMPreTrainedModel", + ] + ) + _import_structure["models.mask2former"].extend( + [ + "Mask2FormerForUniversalSegmentation", + "Mask2FormerModel", + "Mask2FormerPreTrainedModel", + ] + ) + _import_structure["models.maskformer"].extend( + [ + "MaskFormerForInstanceSegmentation", + "MaskFormerModel", + "MaskFormerPreTrainedModel", + "MaskFormerSwinBackbone", + ] + ) + _import_structure["models.mbart"].extend( + [ + "MBartForCausalLM", + "MBartForConditionalGeneration", + "MBartForQuestionAnswering", + "MBartForSequenceClassification", + "MBartModel", + "MBartPreTrainedModel", + ] + ) + _import_structure["models.megatron_bert"].extend( + [ + "MegatronBertForCausalLM", + "MegatronBertForMaskedLM", + "MegatronBertForMultipleChoice", + "MegatronBertForNextSentencePrediction", + "MegatronBertForPreTraining", + "MegatronBertForQuestionAnswering", + "MegatronBertForSequenceClassification", + "MegatronBertForTokenClassification", + "MegatronBertModel", + "MegatronBertPreTrainedModel", + ] + ) + _import_structure["models.mgp_str"].extend( + [ + "MgpstrForSceneTextRecognition", + "MgpstrModel", + "MgpstrPreTrainedModel", + ] + ) + _import_structure["models.mimi"].extend( + [ + "MimiModel", + "MimiPreTrainedModel", + ] + ) + _import_structure["models.mistral"].extend( + [ + "MistralForCausalLM", + "MistralForQuestionAnswering", + "MistralForSequenceClassification", + "MistralForTokenClassification", + "MistralModel", + "MistralPreTrainedModel", + ] + ) + _import_structure["models.mistral3"].extend( + [ + "Mistral3ForConditionalGeneration", + "Mistral3PreTrainedModel", + ] + ) + _import_structure["models.mixtral"].extend( + [ + "MixtralForCausalLM", + "MixtralForQuestionAnswering", + "MixtralForSequenceClassification", + "MixtralForTokenClassification", + "MixtralModel", + "MixtralPreTrainedModel", + ] + ) + _import_structure["models.mllama"].extend( + [ + "MllamaForCausalLM", + "MllamaForConditionalGeneration", + "MllamaPreTrainedModel", + "MllamaProcessor", + "MllamaTextModel", + "MllamaVisionModel", + ] + ) + _import_structure["models.mobilebert"].extend( + [ + "MobileBertForMaskedLM", + "MobileBertForMultipleChoice", + "MobileBertForNextSentencePrediction", + "MobileBertForPreTraining", + "MobileBertForQuestionAnswering", + "MobileBertForSequenceClassification", + "MobileBertForTokenClassification", + "MobileBertModel", + "MobileBertPreTrainedModel", + "load_tf_weights_in_mobilebert", + ] + ) + _import_structure["models.mobilenet_v1"].extend( + [ + "MobileNetV1ForImageClassification", + "MobileNetV1Model", + "MobileNetV1PreTrainedModel", + "load_tf_weights_in_mobilenet_v1", + ] + ) + _import_structure["models.mobilenet_v2"].extend( + [ + "MobileNetV2ForImageClassification", + "MobileNetV2ForSemanticSegmentation", + "MobileNetV2Model", + "MobileNetV2PreTrainedModel", + "load_tf_weights_in_mobilenet_v2", + ] + ) + _import_structure["models.mobilevit"].extend( + [ + "MobileViTForImageClassification", + "MobileViTForSemanticSegmentation", + "MobileViTModel", + "MobileViTPreTrainedModel", + ] + ) + _import_structure["models.mobilevitv2"].extend( + [ + "MobileViTV2ForImageClassification", + "MobileViTV2ForSemanticSegmentation", + "MobileViTV2Model", + "MobileViTV2PreTrainedModel", + ] + ) + _import_structure["models.modernbert"].extend( + [ + "ModernBertForMaskedLM", + "ModernBertForSequenceClassification", + "ModernBertForTokenClassification", + "ModernBertModel", + "ModernBertPreTrainedModel", + ] + ) + _import_structure["models.moonshine"].extend( + [ + "MoonshineForConditionalGeneration", + "MoonshineModel", + "MoonshinePreTrainedModel", + ] + ) + _import_structure["models.moshi"].extend( + [ + "MoshiForCausalLM", + "MoshiForConditionalGeneration", + "MoshiModel", + "MoshiPreTrainedModel", + ] + ) + _import_structure["models.mpnet"].extend( + [ + "MPNetForMaskedLM", + "MPNetForMultipleChoice", + "MPNetForQuestionAnswering", + "MPNetForSequenceClassification", + "MPNetForTokenClassification", + "MPNetModel", + "MPNetPreTrainedModel", + ] + ) + _import_structure["models.mpt"].extend( + [ + "MptForCausalLM", + "MptForQuestionAnswering", + "MptForSequenceClassification", + "MptForTokenClassification", + "MptModel", + "MptPreTrainedModel", + ] + ) + _import_structure["models.mra"].extend( + [ + "MraForMaskedLM", + "MraForMultipleChoice", + "MraForQuestionAnswering", + "MraForSequenceClassification", + "MraForTokenClassification", + "MraModel", + "MraPreTrainedModel", + ] + ) + _import_structure["models.mt5"].extend( + [ + "MT5EncoderModel", + "MT5ForConditionalGeneration", + "MT5ForQuestionAnswering", + "MT5ForSequenceClassification", + "MT5ForTokenClassification", + "MT5Model", + "MT5PreTrainedModel", + ] + ) + _import_structure["models.musicgen"].extend( + [ + "MusicgenForCausalLM", + "MusicgenForConditionalGeneration", + "MusicgenModel", + "MusicgenPreTrainedModel", + "MusicgenProcessor", + ] + ) + _import_structure["models.musicgen_melody"].extend( + [ + "MusicgenMelodyForCausalLM", + "MusicgenMelodyForConditionalGeneration", + "MusicgenMelodyModel", + "MusicgenMelodyPreTrainedModel", + ] + ) + _import_structure["models.mvp"].extend( + [ + "MvpForCausalLM", + "MvpForConditionalGeneration", + "MvpForQuestionAnswering", + "MvpForSequenceClassification", + "MvpModel", + "MvpPreTrainedModel", + ] + ) + _import_structure["models.nemotron"].extend( + [ + "NemotronForCausalLM", + "NemotronForQuestionAnswering", + "NemotronForSequenceClassification", + "NemotronForTokenClassification", + "NemotronModel", + "NemotronPreTrainedModel", + ] + ) + _import_structure["models.nllb_moe"].extend( + [ + "NllbMoeForConditionalGeneration", + "NllbMoeModel", + "NllbMoePreTrainedModel", + "NllbMoeSparseMLP", + "NllbMoeTop2Router", + ] + ) + _import_structure["models.nystromformer"].extend( + [ + "NystromformerForMaskedLM", + "NystromformerForMultipleChoice", + "NystromformerForQuestionAnswering", + "NystromformerForSequenceClassification", + "NystromformerForTokenClassification", + "NystromformerModel", + "NystromformerPreTrainedModel", + ] + ) + _import_structure["models.olmo"].extend( + [ + "OlmoForCausalLM", + "OlmoModel", + "OlmoPreTrainedModel", + ] + ) + _import_structure["models.olmo2"].extend( + [ + "Olmo2ForCausalLM", + "Olmo2Model", + "Olmo2PreTrainedModel", + ] + ) + _import_structure["models.olmoe"].extend( + [ + "OlmoeForCausalLM", + "OlmoeModel", + "OlmoePreTrainedModel", + ] + ) + _import_structure["models.omdet_turbo"].extend( + [ + "OmDetTurboForObjectDetection", + "OmDetTurboPreTrainedModel", + ] + ) + _import_structure["models.oneformer"].extend( + [ + "OneFormerForUniversalSegmentation", + "OneFormerModel", + "OneFormerPreTrainedModel", + ] + ) + _import_structure["models.openai"].extend( + [ + "OpenAIGPTDoubleHeadsModel", + "OpenAIGPTForSequenceClassification", + "OpenAIGPTLMHeadModel", + "OpenAIGPTModel", + "OpenAIGPTPreTrainedModel", + "load_tf_weights_in_openai_gpt", + ] + ) + _import_structure["models.opt"].extend( + [ + "OPTForCausalLM", + "OPTForQuestionAnswering", + "OPTForSequenceClassification", + "OPTModel", + "OPTPreTrainedModel", + ] + ) + _import_structure["models.owlv2"].extend( + [ + "Owlv2ForObjectDetection", + "Owlv2Model", + "Owlv2PreTrainedModel", + "Owlv2TextModel", + "Owlv2VisionModel", + ] + ) + _import_structure["models.owlvit"].extend( + [ + "OwlViTForObjectDetection", + "OwlViTModel", + "OwlViTPreTrainedModel", + "OwlViTTextModel", + "OwlViTVisionModel", + ] + ) + _import_structure["models.paligemma"].extend( + [ + "PaliGemmaForConditionalGeneration", + "PaliGemmaPreTrainedModel", + "PaliGemmaProcessor", + ] + ) + _import_structure["models.patchtsmixer"].extend( + [ + "PatchTSMixerForPrediction", + "PatchTSMixerForPretraining", + "PatchTSMixerForRegression", + "PatchTSMixerForTimeSeriesClassification", + "PatchTSMixerModel", + "PatchTSMixerPreTrainedModel", + ] + ) + _import_structure["models.patchtst"].extend( + [ + "PatchTSTForClassification", + "PatchTSTForPrediction", + "PatchTSTForPretraining", + "PatchTSTForRegression", + "PatchTSTModel", + "PatchTSTPreTrainedModel", + ] + ) + _import_structure["models.pegasus"].extend( + [ + "PegasusForCausalLM", + "PegasusForConditionalGeneration", + "PegasusModel", + "PegasusPreTrainedModel", + ] + ) + _import_structure["models.pegasus_x"].extend( + [ + "PegasusXForConditionalGeneration", + "PegasusXModel", + "PegasusXPreTrainedModel", + ] + ) + _import_structure["models.perceiver"].extend( + [ + "PerceiverForImageClassificationConvProcessing", + "PerceiverForImageClassificationFourier", + "PerceiverForImageClassificationLearned", + "PerceiverForMaskedLM", + "PerceiverForMultimodalAutoencoding", + "PerceiverForOpticalFlow", + "PerceiverForSequenceClassification", + "PerceiverModel", + "PerceiverPreTrainedModel", + ] + ) + _import_structure["models.persimmon"].extend( + [ + "PersimmonForCausalLM", + "PersimmonForSequenceClassification", + "PersimmonForTokenClassification", + "PersimmonModel", + "PersimmonPreTrainedModel", + ] + ) + _import_structure["models.phi"].extend( + [ + "PhiForCausalLM", + "PhiForSequenceClassification", + "PhiForTokenClassification", + "PhiModel", + "PhiPreTrainedModel", + ] + ) + _import_structure["models.phi3"].extend( + [ + "Phi3ForCausalLM", + "Phi3ForSequenceClassification", + "Phi3ForTokenClassification", + "Phi3Model", + "Phi3PreTrainedModel", + ] + ) + _import_structure["models.phimoe"].extend( + [ + "PhimoeForCausalLM", + "PhimoeForSequenceClassification", + "PhimoeModel", + "PhimoePreTrainedModel", + ] + ) + _import_structure["models.pix2struct"].extend( + [ + "Pix2StructForConditionalGeneration", + "Pix2StructPreTrainedModel", + "Pix2StructTextModel", + "Pix2StructVisionModel", + ] + ) + _import_structure["models.pixtral"].extend(["PixtralPreTrainedModel", "PixtralVisionModel"]) + _import_structure["models.plbart"].extend( + [ + "PLBartForCausalLM", + "PLBartForConditionalGeneration", + "PLBartForSequenceClassification", + "PLBartModel", + "PLBartPreTrainedModel", + ] + ) + _import_structure["models.poolformer"].extend( + [ + "PoolFormerForImageClassification", + "PoolFormerModel", + "PoolFormerPreTrainedModel", + ] + ) + _import_structure["models.pop2piano"].extend( + [ + "Pop2PianoForConditionalGeneration", + "Pop2PianoPreTrainedModel", + ] + ) + _import_structure["models.prophetnet"].extend( + [ + "ProphetNetDecoder", + "ProphetNetEncoder", + "ProphetNetForCausalLM", + "ProphetNetForConditionalGeneration", + "ProphetNetModel", + "ProphetNetPreTrainedModel", + ] + ) + _import_structure["models.pvt"].extend( + [ + "PvtForImageClassification", + "PvtModel", + "PvtPreTrainedModel", + ] + ) + _import_structure["models.pvt_v2"].extend( + [ + "PvtV2Backbone", + "PvtV2ForImageClassification", + "PvtV2Model", + "PvtV2PreTrainedModel", + ] + ) + _import_structure["models.qwen2"].extend( + [ + "Qwen2ForCausalLM", + "Qwen2ForQuestionAnswering", + "Qwen2ForSequenceClassification", + "Qwen2ForTokenClassification", + "Qwen2Model", + "Qwen2PreTrainedModel", + ] + ) + _import_structure["models.qwen2_5_vl"].extend( + [ + "Qwen2_5_VLForConditionalGeneration", + "Qwen2_5_VLModel", + "Qwen2_5_VLPreTrainedModel", + ] + ) + _import_structure["models.qwen2_audio"].extend( + [ + "Qwen2AudioEncoder", + "Qwen2AudioForConditionalGeneration", + "Qwen2AudioPreTrainedModel", + ] + ) + _import_structure["models.qwen2_moe"].extend( + [ + "Qwen2MoeForCausalLM", + "Qwen2MoeForQuestionAnswering", + "Qwen2MoeForSequenceClassification", + "Qwen2MoeForTokenClassification", + "Qwen2MoeModel", + "Qwen2MoePreTrainedModel", + ] + ) + _import_structure["models.qwen2_vl"].extend( + [ + "Qwen2VLForConditionalGeneration", + "Qwen2VLModel", + "Qwen2VLPreTrainedModel", + ] + ) + _import_structure["models.rag"].extend( + [ + "RagModel", + "RagPreTrainedModel", + "RagSequenceForGeneration", + "RagTokenForGeneration", + ] + ) + _import_structure["models.recurrent_gemma"].extend( + [ + "RecurrentGemmaForCausalLM", + "RecurrentGemmaModel", + "RecurrentGemmaPreTrainedModel", + ] + ) + _import_structure["models.reformer"].extend( + [ + "ReformerForMaskedLM", + "ReformerForQuestionAnswering", + "ReformerForSequenceClassification", + "ReformerModel", + "ReformerModelWithLMHead", + "ReformerPreTrainedModel", + ] + ) + _import_structure["models.regnet"].extend( + [ + "RegNetForImageClassification", + "RegNetModel", + "RegNetPreTrainedModel", + ] + ) + _import_structure["models.rembert"].extend( + [ + "RemBertForCausalLM", + "RemBertForMaskedLM", + "RemBertForMultipleChoice", + "RemBertForQuestionAnswering", + "RemBertForSequenceClassification", + "RemBertForTokenClassification", + "RemBertModel", + "RemBertPreTrainedModel", + "load_tf_weights_in_rembert", + ] + ) + _import_structure["models.resnet"].extend( + [ + "ResNetBackbone", + "ResNetForImageClassification", + "ResNetModel", + "ResNetPreTrainedModel", + ] + ) + _import_structure["models.roberta"].extend( + [ + "RobertaForCausalLM", + "RobertaForMaskedLM", + "RobertaForMultipleChoice", + "RobertaForQuestionAnswering", + "RobertaForSequenceClassification", + "RobertaForTokenClassification", + "RobertaModel", + "RobertaPreTrainedModel", + ] + ) + _import_structure["models.roberta_prelayernorm"].extend( + [ + "RobertaPreLayerNormForCausalLM", + "RobertaPreLayerNormForMaskedLM", + "RobertaPreLayerNormForMultipleChoice", + "RobertaPreLayerNormForQuestionAnswering", + "RobertaPreLayerNormForSequenceClassification", + "RobertaPreLayerNormForTokenClassification", + "RobertaPreLayerNormModel", + "RobertaPreLayerNormPreTrainedModel", + ] + ) + _import_structure["models.roc_bert"].extend( + [ + "RoCBertForCausalLM", + "RoCBertForMaskedLM", + "RoCBertForMultipleChoice", + "RoCBertForPreTraining", + "RoCBertForQuestionAnswering", + "RoCBertForSequenceClassification", + "RoCBertForTokenClassification", + "RoCBertModel", + "RoCBertPreTrainedModel", + "load_tf_weights_in_roc_bert", + ] + ) + _import_structure["models.roformer"].extend( + [ + "RoFormerForCausalLM", + "RoFormerForMaskedLM", + "RoFormerForMultipleChoice", + "RoFormerForQuestionAnswering", + "RoFormerForSequenceClassification", + "RoFormerForTokenClassification", + "RoFormerModel", + "RoFormerPreTrainedModel", + "load_tf_weights_in_roformer", + ] + ) + _import_structure["models.rt_detr"].extend( + [ + "RTDetrForObjectDetection", + "RTDetrModel", + "RTDetrPreTrainedModel", + "RTDetrResNetBackbone", + "RTDetrResNetPreTrainedModel", + ] + ) + _import_structure["models.rt_detr_v2"].extend( + ["RTDetrV2ForObjectDetection", "RTDetrV2Model", "RTDetrV2PreTrainedModel"] + ) + _import_structure["models.rwkv"].extend( + [ + "RwkvForCausalLM", + "RwkvModel", + "RwkvPreTrainedModel", + ] + ) + _import_structure["models.sam"].extend( + [ + "SamModel", + "SamPreTrainedModel", + ] + ) + _import_structure["models.seamless_m4t"].extend( + [ + "SeamlessM4TCodeHifiGan", + "SeamlessM4TForSpeechToSpeech", + "SeamlessM4TForSpeechToText", + "SeamlessM4TForTextToSpeech", + "SeamlessM4TForTextToText", + "SeamlessM4THifiGan", + "SeamlessM4TModel", + "SeamlessM4TPreTrainedModel", + "SeamlessM4TTextToUnitForConditionalGeneration", + "SeamlessM4TTextToUnitModel", + ] + ) + _import_structure["models.seamless_m4t_v2"].extend( + [ + "SeamlessM4Tv2ForSpeechToSpeech", + "SeamlessM4Tv2ForSpeechToText", + "SeamlessM4Tv2ForTextToSpeech", + "SeamlessM4Tv2ForTextToText", + "SeamlessM4Tv2Model", + "SeamlessM4Tv2PreTrainedModel", + ] + ) + _import_structure["models.segformer"].extend( + [ + "SegformerDecodeHead", + "SegformerForImageClassification", + "SegformerForSemanticSegmentation", + "SegformerModel", + "SegformerPreTrainedModel", + ] + ) + _import_structure["models.seggpt"].extend( + [ + "SegGptForImageSegmentation", + "SegGptModel", + "SegGptPreTrainedModel", + ] + ) + _import_structure["models.sew"].extend( + [ + "SEWForCTC", + "SEWForSequenceClassification", + "SEWModel", + "SEWPreTrainedModel", + ] + ) + _import_structure["models.sew_d"].extend( + [ + "SEWDForCTC", + "SEWDForSequenceClassification", + "SEWDModel", + "SEWDPreTrainedModel", + ] + ) + _import_structure["models.siglip"].extend( + [ + "SiglipForImageClassification", + "SiglipModel", + "SiglipPreTrainedModel", + "SiglipTextModel", + "SiglipVisionModel", + ] + ) + _import_structure["models.siglip2"].extend( + [ + "Siglip2ForImageClassification", + "Siglip2Model", + "Siglip2PreTrainedModel", + "Siglip2TextModel", + "Siglip2VisionModel", + ] + ) + _import_structure["models.smolvlm"].extend( + [ + "SmolVLMForConditionalGeneration", + "SmolVLMModel", + "SmolVLMPreTrainedModel", + "SmolVLMProcessor", + "SmolVLMVisionConfig", + "SmolVLMVisionTransformer", + ] + ) + _import_structure["models.speech_encoder_decoder"].extend(["SpeechEncoderDecoderModel"]) + _import_structure["models.speech_to_text"].extend( + [ + "Speech2TextForConditionalGeneration", + "Speech2TextModel", + "Speech2TextPreTrainedModel", + ] + ) + _import_structure["models.speecht5"].extend( + [ + "SpeechT5ForSpeechToSpeech", + "SpeechT5ForSpeechToText", + "SpeechT5ForTextToSpeech", + "SpeechT5HifiGan", + "SpeechT5Model", + "SpeechT5PreTrainedModel", + ] + ) + _import_structure["models.splinter"].extend( + [ + "SplinterForPreTraining", + "SplinterForQuestionAnswering", + "SplinterModel", + "SplinterPreTrainedModel", + ] + ) + _import_structure["models.squeezebert"].extend( + [ + "SqueezeBertForMaskedLM", + "SqueezeBertForMultipleChoice", + "SqueezeBertForQuestionAnswering", + "SqueezeBertForSequenceClassification", + "SqueezeBertForTokenClassification", + "SqueezeBertModel", + "SqueezeBertPreTrainedModel", + ] + ) + _import_structure["models.stablelm"].extend( + [ + "StableLmForCausalLM", + "StableLmForSequenceClassification", + "StableLmForTokenClassification", + "StableLmModel", + "StableLmPreTrainedModel", + ] + ) + _import_structure["models.starcoder2"].extend( + [ + "Starcoder2ForCausalLM", + "Starcoder2ForSequenceClassification", + "Starcoder2ForTokenClassification", + "Starcoder2Model", + "Starcoder2PreTrainedModel", + ] + ) + _import_structure["models.superglue"].extend( + [ + "SuperGlueForKeypointMatching", + "SuperGluePreTrainedModel", + ] + ) + _import_structure["models.superpoint"].extend( + [ + "SuperPointForKeypointDetection", + "SuperPointPreTrainedModel", + ] + ) + _import_structure["models.swiftformer"].extend( + [ + "SwiftFormerForImageClassification", + "SwiftFormerModel", + "SwiftFormerPreTrainedModel", + ] + ) + _import_structure["models.swin"].extend( + [ + "SwinBackbone", + "SwinForImageClassification", + "SwinForMaskedImageModeling", + "SwinModel", + "SwinPreTrainedModel", + ] + ) + _import_structure["models.swin2sr"].extend( + [ + "Swin2SRForImageSuperResolution", + "Swin2SRModel", + "Swin2SRPreTrainedModel", + ] + ) + _import_structure["models.swinv2"].extend( + [ + "Swinv2Backbone", + "Swinv2ForImageClassification", + "Swinv2ForMaskedImageModeling", + "Swinv2Model", + "Swinv2PreTrainedModel", + ] + ) + _import_structure["models.switch_transformers"].extend( + [ + "SwitchTransformersEncoderModel", + "SwitchTransformersForConditionalGeneration", + "SwitchTransformersModel", + "SwitchTransformersPreTrainedModel", + "SwitchTransformersSparseMLP", + "SwitchTransformersTop1Router", + ] + ) + _import_structure["models.t5"].extend( + [ + "T5EncoderModel", + "T5ForConditionalGeneration", + "T5ForQuestionAnswering", + "T5ForSequenceClassification", + "T5ForTokenClassification", + "T5Model", + "T5PreTrainedModel", + "load_tf_weights_in_t5", + ] + ) + _import_structure["models.table_transformer"].extend( + [ + "TableTransformerForObjectDetection", + "TableTransformerModel", + "TableTransformerPreTrainedModel", + ] + ) + _import_structure["models.tapas"].extend( + [ + "TapasForMaskedLM", + "TapasForQuestionAnswering", + "TapasForSequenceClassification", + "TapasModel", + "TapasPreTrainedModel", + "load_tf_weights_in_tapas", + ] + ) + _import_structure["models.textnet"].extend( + [ + "TextNetBackbone", + "TextNetForImageClassification", + "TextNetModel", + "TextNetPreTrainedModel", + ] + ) + _import_structure["models.time_series_transformer"].extend( + [ + "TimeSeriesTransformerForPrediction", + "TimeSeriesTransformerModel", + "TimeSeriesTransformerPreTrainedModel", + ] + ) + _import_structure["models.timesformer"].extend( + [ + "TimesformerForVideoClassification", + "TimesformerModel", + "TimesformerPreTrainedModel", + ] + ) + _import_structure["models.timm_backbone"].extend(["TimmBackbone"]) + _import_structure["models.timm_wrapper"].extend( + ["TimmWrapperForImageClassification", "TimmWrapperModel", "TimmWrapperPreTrainedModel"] + ) + _import_structure["models.trocr"].extend( + [ + "TrOCRForCausalLM", + "TrOCRPreTrainedModel", + ] + ) + _import_structure["models.tvp"].extend( + [ + "TvpForVideoGrounding", + "TvpModel", + "TvpPreTrainedModel", + ] + ) + _import_structure["models.udop"].extend( + [ + "UdopEncoderModel", + "UdopForConditionalGeneration", + "UdopModel", + "UdopPreTrainedModel", + ], + ) + _import_structure["models.umt5"].extend( + [ + "UMT5EncoderModel", + "UMT5ForConditionalGeneration", + "UMT5ForQuestionAnswering", + "UMT5ForSequenceClassification", + "UMT5ForTokenClassification", + "UMT5Model", + "UMT5PreTrainedModel", + ] + ) + _import_structure["models.unispeech"].extend( + [ + "UniSpeechForCTC", + "UniSpeechForPreTraining", + "UniSpeechForSequenceClassification", + "UniSpeechModel", + "UniSpeechPreTrainedModel", + ] + ) + _import_structure["models.unispeech_sat"].extend( + [ + "UniSpeechSatForAudioFrameClassification", + "UniSpeechSatForCTC", + "UniSpeechSatForPreTraining", + "UniSpeechSatForSequenceClassification", + "UniSpeechSatForXVector", + "UniSpeechSatModel", + "UniSpeechSatPreTrainedModel", + ] + ) + _import_structure["models.univnet"].extend( + [ + "UnivNetModel", + ] + ) + _import_structure["models.upernet"].extend( + [ + "UperNetForSemanticSegmentation", + "UperNetPreTrainedModel", + ] + ) + _import_structure["models.video_llava"].extend( + [ + "VideoLlavaForConditionalGeneration", + "VideoLlavaPreTrainedModel", + "VideoLlavaProcessor", + ] + ) + _import_structure["models.videomae"].extend( + [ + "VideoMAEForPreTraining", + "VideoMAEForVideoClassification", + "VideoMAEModel", + "VideoMAEPreTrainedModel", + ] + ) + _import_structure["models.vilt"].extend( + [ + "ViltForImageAndTextRetrieval", + "ViltForImagesAndTextClassification", + "ViltForMaskedLM", + "ViltForQuestionAnswering", + "ViltForTokenClassification", + "ViltModel", + "ViltPreTrainedModel", + ] + ) + _import_structure["models.vipllava"].extend( + [ + "VipLlavaForConditionalGeneration", + "VipLlavaPreTrainedModel", + ] + ) + _import_structure["models.vision_encoder_decoder"].extend(["VisionEncoderDecoderModel"]) + _import_structure["models.vision_text_dual_encoder"].extend(["VisionTextDualEncoderModel"]) + _import_structure["models.visual_bert"].extend( + [ + "VisualBertForMultipleChoice", + "VisualBertForPreTraining", + "VisualBertForQuestionAnswering", + "VisualBertForRegionToPhraseAlignment", + "VisualBertForVisualReasoning", + "VisualBertModel", + "VisualBertPreTrainedModel", + ] + ) + _import_structure["models.vit"].extend( + [ + "ViTForImageClassification", + "ViTForMaskedImageModeling", + "ViTModel", + "ViTPreTrainedModel", + ] + ) + _import_structure["models.vit_mae"].extend( + [ + "ViTMAEForPreTraining", + "ViTMAEModel", + "ViTMAEPreTrainedModel", + ] + ) + _import_structure["models.vit_msn"].extend( + [ + "ViTMSNForImageClassification", + "ViTMSNModel", + "ViTMSNPreTrainedModel", + ] + ) + _import_structure["models.vitdet"].extend( + [ + "VitDetBackbone", + "VitDetModel", + "VitDetPreTrainedModel", + ] + ) + _import_structure["models.vitmatte"].extend( + [ + "VitMatteForImageMatting", + "VitMattePreTrainedModel", + ] + ) + _import_structure["models.vitpose"].extend( + [ + "VitPoseForPoseEstimation", + "VitPosePreTrainedModel", + ] + ) + _import_structure["models.vitpose_backbone"].extend( + [ + "VitPoseBackbone", + "VitPoseBackbonePreTrainedModel", + ] + ) + _import_structure["models.vits"].extend( + [ + "VitsModel", + "VitsPreTrainedModel", + ] + ) + _import_structure["models.vivit"].extend( + [ + "VivitForVideoClassification", + "VivitModel", + "VivitPreTrainedModel", + ] + ) + _import_structure["models.wav2vec2"].extend( + [ + "Wav2Vec2ForAudioFrameClassification", + "Wav2Vec2ForCTC", + "Wav2Vec2ForMaskedLM", + "Wav2Vec2ForPreTraining", + "Wav2Vec2ForSequenceClassification", + "Wav2Vec2ForXVector", + "Wav2Vec2Model", + "Wav2Vec2PreTrainedModel", + ] + ) + _import_structure["models.wav2vec2_bert"].extend( + [ + "Wav2Vec2BertForAudioFrameClassification", + "Wav2Vec2BertForCTC", + "Wav2Vec2BertForSequenceClassification", + "Wav2Vec2BertForXVector", + "Wav2Vec2BertModel", + "Wav2Vec2BertPreTrainedModel", + ] + ) + _import_structure["models.wav2vec2_conformer"].extend( + [ + "Wav2Vec2ConformerForAudioFrameClassification", + "Wav2Vec2ConformerForCTC", + "Wav2Vec2ConformerForPreTraining", + "Wav2Vec2ConformerForSequenceClassification", + "Wav2Vec2ConformerForXVector", + "Wav2Vec2ConformerModel", + "Wav2Vec2ConformerPreTrainedModel", + ] + ) + _import_structure["models.wavlm"].extend( + [ + "WavLMForAudioFrameClassification", + "WavLMForCTC", + "WavLMForSequenceClassification", + "WavLMForXVector", + "WavLMModel", + "WavLMPreTrainedModel", + ] + ) + _import_structure["models.whisper"].extend( + [ + "WhisperForAudioClassification", + "WhisperForCausalLM", + "WhisperForConditionalGeneration", + "WhisperModel", + "WhisperPreTrainedModel", + ] + ) + _import_structure["models.x_clip"].extend( + [ + "XCLIPModel", + "XCLIPPreTrainedModel", + "XCLIPTextModel", + "XCLIPVisionModel", + ] + ) + _import_structure["models.xglm"].extend( + [ + "XGLMForCausalLM", + "XGLMModel", + "XGLMPreTrainedModel", + ] + ) + _import_structure["models.xlm"].extend( + [ + "XLMForMultipleChoice", + "XLMForQuestionAnswering", + "XLMForQuestionAnsweringSimple", + "XLMForSequenceClassification", + "XLMForTokenClassification", + "XLMModel", + "XLMPreTrainedModel", + "XLMWithLMHeadModel", + ] + ) + _import_structure["models.xlm_roberta"].extend( + [ + "XLMRobertaForCausalLM", + "XLMRobertaForMaskedLM", + "XLMRobertaForMultipleChoice", + "XLMRobertaForQuestionAnswering", + "XLMRobertaForSequenceClassification", + "XLMRobertaForTokenClassification", + "XLMRobertaModel", + "XLMRobertaPreTrainedModel", + ] + ) + _import_structure["models.xlm_roberta_xl"].extend( + [ + "XLMRobertaXLForCausalLM", + "XLMRobertaXLForMaskedLM", + "XLMRobertaXLForMultipleChoice", + "XLMRobertaXLForQuestionAnswering", + "XLMRobertaXLForSequenceClassification", + "XLMRobertaXLForTokenClassification", + "XLMRobertaXLModel", + "XLMRobertaXLPreTrainedModel", + ] + ) + _import_structure["models.xlnet"].extend( + [ + "XLNetForMultipleChoice", + "XLNetForQuestionAnswering", + "XLNetForQuestionAnsweringSimple", + "XLNetForSequenceClassification", + "XLNetForTokenClassification", + "XLNetLMHeadModel", + "XLNetModel", + "XLNetPreTrainedModel", + "load_tf_weights_in_xlnet", + ] + ) + _import_structure["models.xmod"].extend( + [ + "XmodForCausalLM", + "XmodForMaskedLM", + "XmodForMultipleChoice", + "XmodForQuestionAnswering", + "XmodForSequenceClassification", + "XmodForTokenClassification", + "XmodModel", + "XmodPreTrainedModel", + ] + ) + _import_structure["models.yolos"].extend( + [ + "YolosForObjectDetection", + "YolosModel", + "YolosPreTrainedModel", + ] + ) + _import_structure["models.yoso"].extend( + [ + "YosoForMaskedLM", + "YosoForMultipleChoice", + "YosoForQuestionAnswering", + "YosoForSequenceClassification", + "YosoForTokenClassification", + "YosoModel", + "YosoPreTrainedModel", + ] + ) + _import_structure["models.zamba"].extend( + [ + "ZambaForCausalLM", + "ZambaForSequenceClassification", + "ZambaModel", + "ZambaPreTrainedModel", + ] + ) + _import_structure["models.zamba2"].extend( + [ + "Zamba2ForCausalLM", + "Zamba2ForSequenceClassification", + "Zamba2Model", + "Zamba2PreTrainedModel", + ] + ) + _import_structure["models.zoedepth"].extend( + [ + "ZoeDepthForDepthEstimation", + "ZoeDepthPreTrainedModel", + ] + ) + _import_structure["optimization"] = [ + "Adafactor", + "AdamW", + "get_constant_schedule", + "get_constant_schedule_with_warmup", + "get_cosine_schedule_with_warmup", + "get_cosine_with_hard_restarts_schedule_with_warmup", + "get_inverse_sqrt_schedule", + "get_linear_schedule_with_warmup", + "get_polynomial_decay_schedule_with_warmup", + "get_scheduler", + "get_wsd_schedule", + ] + _import_structure["pytorch_utils"] = [ + "Conv1D", + "apply_chunking_to_forward", + "prune_layer", + ] + _import_structure["sagemaker"] = [] + _import_structure["time_series_utils"] = [] + _import_structure["trainer"] = ["Trainer"] + _import_structure["trainer_pt_utils"] = ["torch_distributed_zero_first"] + _import_structure["trainer_seq2seq"] = ["Seq2SeqTrainer"] + +# TensorFlow-backed objects +try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_tf_objects + + _import_structure["utils.dummy_tf_objects"] = [name for name in dir(dummy_tf_objects) if not name.startswith("_")] +else: + _import_structure["activations_tf"] = [] + _import_structure["generation"].extend( + [ + "TFForcedBOSTokenLogitsProcessor", + "TFForcedEOSTokenLogitsProcessor", + "TFForceTokensLogitsProcessor", + "TFGenerationMixin", + "TFLogitsProcessor", + "TFLogitsProcessorList", + "TFLogitsWarper", + "TFMinLengthLogitsProcessor", + "TFNoBadWordsLogitsProcessor", + "TFNoRepeatNGramLogitsProcessor", + "TFRepetitionPenaltyLogitsProcessor", + "TFSuppressTokensAtBeginLogitsProcessor", + "TFSuppressTokensLogitsProcessor", + "TFTemperatureLogitsWarper", + "TFTopKLogitsWarper", + "TFTopPLogitsWarper", + ] + ) + _import_structure["keras_callbacks"] = ["KerasMetricCallback", "PushToHubCallback"] + _import_structure["modeling_tf_outputs"] = [] + _import_structure["modeling_tf_utils"] = [ + "TFPreTrainedModel", + "TFSequenceSummary", + "TFSharedEmbeddings", + "shape_list", + ] + # TensorFlow models structure + _import_structure["models.albert"].extend( + [ + "TFAlbertForMaskedLM", + "TFAlbertForMultipleChoice", + "TFAlbertForPreTraining", + "TFAlbertForQuestionAnswering", + "TFAlbertForSequenceClassification", + "TFAlbertForTokenClassification", + "TFAlbertMainLayer", + "TFAlbertModel", + "TFAlbertPreTrainedModel", + ] + ) + _import_structure["models.auto"].extend( + [ + "TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING", + "TF_MODEL_FOR_CAUSAL_LM_MAPPING", + "TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING", + "TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", + "TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING", + "TF_MODEL_FOR_MASKED_LM_MAPPING", + "TF_MODEL_FOR_MASK_GENERATION_MAPPING", + "TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING", + "TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", + "TF_MODEL_FOR_PRETRAINING_MAPPING", + "TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING", + "TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING", + "TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", + "TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", + "TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", + "TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", + "TF_MODEL_FOR_TEXT_ENCODING_MAPPING", + "TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", + "TF_MODEL_FOR_VISION_2_SEQ_MAPPING", + "TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING", + "TF_MODEL_MAPPING", + "TF_MODEL_WITH_LM_HEAD_MAPPING", + "TFAutoModel", + "TFAutoModelForAudioClassification", + "TFAutoModelForCausalLM", + "TFAutoModelForDocumentQuestionAnswering", + "TFAutoModelForImageClassification", + "TFAutoModelForMaskedImageModeling", + "TFAutoModelForMaskedLM", + "TFAutoModelForMaskGeneration", + "TFAutoModelForMultipleChoice", + "TFAutoModelForNextSentencePrediction", + "TFAutoModelForPreTraining", + "TFAutoModelForQuestionAnswering", + "TFAutoModelForSemanticSegmentation", + "TFAutoModelForSeq2SeqLM", + "TFAutoModelForSequenceClassification", + "TFAutoModelForSpeechSeq2Seq", + "TFAutoModelForTableQuestionAnswering", + "TFAutoModelForTextEncoding", + "TFAutoModelForTokenClassification", + "TFAutoModelForVision2Seq", + "TFAutoModelForZeroShotImageClassification", + "TFAutoModelWithLMHead", + ] + ) + _import_structure["models.bart"].extend( + [ + "TFBartForConditionalGeneration", + "TFBartForSequenceClassification", + "TFBartModel", + "TFBartPretrainedModel", + ] + ) + _import_structure["models.bert"].extend( + [ + "TFBertForMaskedLM", + "TFBertForMultipleChoice", + "TFBertForNextSentencePrediction", + "TFBertForPreTraining", + "TFBertForQuestionAnswering", + "TFBertForSequenceClassification", + "TFBertForTokenClassification", + "TFBertLMHeadModel", + "TFBertMainLayer", + "TFBertModel", + "TFBertPreTrainedModel", + ] + ) + _import_structure["models.blenderbot"].extend( + [ + "TFBlenderbotForConditionalGeneration", + "TFBlenderbotModel", + "TFBlenderbotPreTrainedModel", + ] + ) + _import_structure["models.blenderbot_small"].extend( + [ + "TFBlenderbotSmallForConditionalGeneration", + "TFBlenderbotSmallModel", + "TFBlenderbotSmallPreTrainedModel", + ] + ) + _import_structure["models.blip"].extend( + [ + "TFBlipForConditionalGeneration", + "TFBlipForImageTextRetrieval", + "TFBlipForQuestionAnswering", + "TFBlipModel", + "TFBlipPreTrainedModel", + "TFBlipTextModel", + "TFBlipVisionModel", + ] + ) + _import_structure["models.camembert"].extend( + [ + "TFCamembertForCausalLM", + "TFCamembertForMaskedLM", + "TFCamembertForMultipleChoice", + "TFCamembertForQuestionAnswering", + "TFCamembertForSequenceClassification", + "TFCamembertForTokenClassification", + "TFCamembertModel", + "TFCamembertPreTrainedModel", + ] + ) + _import_structure["models.clip"].extend( + [ + "TFCLIPModel", + "TFCLIPPreTrainedModel", + "TFCLIPTextModel", + "TFCLIPVisionModel", + ] + ) + _import_structure["models.convbert"].extend( + [ + "TFConvBertForMaskedLM", + "TFConvBertForMultipleChoice", + "TFConvBertForQuestionAnswering", + "TFConvBertForSequenceClassification", + "TFConvBertForTokenClassification", + "TFConvBertModel", + "TFConvBertPreTrainedModel", + ] + ) + _import_structure["models.convnext"].extend( + [ + "TFConvNextForImageClassification", + "TFConvNextModel", + "TFConvNextPreTrainedModel", + ] + ) + _import_structure["models.convnextv2"].extend( + [ + "TFConvNextV2ForImageClassification", + "TFConvNextV2Model", + "TFConvNextV2PreTrainedModel", + ] + ) + _import_structure["models.ctrl"].extend( + [ + "TFCTRLForSequenceClassification", + "TFCTRLLMHeadModel", + "TFCTRLModel", + "TFCTRLPreTrainedModel", + ] + ) + _import_structure["models.cvt"].extend( + [ + "TFCvtForImageClassification", + "TFCvtModel", + "TFCvtPreTrainedModel", + ] + ) + _import_structure["models.data2vec"].extend( + [ + "TFData2VecVisionForImageClassification", + "TFData2VecVisionForSemanticSegmentation", + "TFData2VecVisionModel", + "TFData2VecVisionPreTrainedModel", + ] + ) + _import_structure["models.deberta"].extend( + [ + "TFDebertaForMaskedLM", + "TFDebertaForQuestionAnswering", + "TFDebertaForSequenceClassification", + "TFDebertaForTokenClassification", + "TFDebertaModel", + "TFDebertaPreTrainedModel", + ] + ) + _import_structure["models.deberta_v2"].extend( + [ + "TFDebertaV2ForMaskedLM", + "TFDebertaV2ForMultipleChoice", + "TFDebertaV2ForQuestionAnswering", + "TFDebertaV2ForSequenceClassification", + "TFDebertaV2ForTokenClassification", + "TFDebertaV2Model", + "TFDebertaV2PreTrainedModel", + ] + ) + _import_structure["models.deit"].extend( + [ + "TFDeiTForImageClassification", + "TFDeiTForImageClassificationWithTeacher", + "TFDeiTForMaskedImageModeling", + "TFDeiTModel", + "TFDeiTPreTrainedModel", + ] + ) + _import_structure["models.deprecated.efficientformer"].extend( + [ + "TFEfficientFormerForImageClassification", + "TFEfficientFormerForImageClassificationWithTeacher", + "TFEfficientFormerModel", + "TFEfficientFormerPreTrainedModel", + ] + ) + _import_structure["models.deprecated.transfo_xl"].extend( + [ + "TFAdaptiveEmbedding", + "TFTransfoXLForSequenceClassification", + "TFTransfoXLLMHeadModel", + "TFTransfoXLMainLayer", + "TFTransfoXLModel", + "TFTransfoXLPreTrainedModel", + ] + ) + _import_structure["models.distilbert"].extend( + [ + "TFDistilBertForMaskedLM", + "TFDistilBertForMultipleChoice", + "TFDistilBertForQuestionAnswering", + "TFDistilBertForSequenceClassification", + "TFDistilBertForTokenClassification", + "TFDistilBertMainLayer", + "TFDistilBertModel", + "TFDistilBertPreTrainedModel", + ] + ) + _import_structure["models.dpr"].extend( + [ + "TFDPRContextEncoder", + "TFDPRPretrainedContextEncoder", + "TFDPRPretrainedQuestionEncoder", + "TFDPRPretrainedReader", + "TFDPRQuestionEncoder", + "TFDPRReader", + ] + ) + _import_structure["models.electra"].extend( + [ + "TFElectraForMaskedLM", + "TFElectraForMultipleChoice", + "TFElectraForPreTraining", + "TFElectraForQuestionAnswering", + "TFElectraForSequenceClassification", + "TFElectraForTokenClassification", + "TFElectraModel", + "TFElectraPreTrainedModel", + ] + ) + _import_structure["models.encoder_decoder"].append("TFEncoderDecoderModel") + _import_structure["models.esm"].extend( + [ + "TFEsmForMaskedLM", + "TFEsmForSequenceClassification", + "TFEsmForTokenClassification", + "TFEsmModel", + "TFEsmPreTrainedModel", + ] + ) + _import_structure["models.flaubert"].extend( + [ + "TFFlaubertForMultipleChoice", + "TFFlaubertForQuestionAnsweringSimple", + "TFFlaubertForSequenceClassification", + "TFFlaubertForTokenClassification", + "TFFlaubertModel", + "TFFlaubertPreTrainedModel", + "TFFlaubertWithLMHeadModel", + ] + ) + _import_structure["models.funnel"].extend( + [ + "TFFunnelBaseModel", + "TFFunnelForMaskedLM", + "TFFunnelForMultipleChoice", + "TFFunnelForPreTraining", + "TFFunnelForQuestionAnswering", + "TFFunnelForSequenceClassification", + "TFFunnelForTokenClassification", + "TFFunnelModel", + "TFFunnelPreTrainedModel", + ] + ) + _import_structure["models.gpt2"].extend( + [ + "TFGPT2DoubleHeadsModel", + "TFGPT2ForSequenceClassification", + "TFGPT2LMHeadModel", + "TFGPT2MainLayer", + "TFGPT2Model", + "TFGPT2PreTrainedModel", + ] + ) + _import_structure["models.gptj"].extend( + [ + "TFGPTJForCausalLM", + "TFGPTJForQuestionAnswering", + "TFGPTJForSequenceClassification", + "TFGPTJModel", + "TFGPTJPreTrainedModel", + ] + ) + _import_structure["models.groupvit"].extend( + [ + "TFGroupViTModel", + "TFGroupViTPreTrainedModel", + "TFGroupViTTextModel", + "TFGroupViTVisionModel", + ] + ) + _import_structure["models.hubert"].extend( + [ + "TFHubertForCTC", + "TFHubertModel", + "TFHubertPreTrainedModel", + ] + ) + + _import_structure["models.idefics"].extend( + [ + "TFIdeficsForVisionText2Text", + "TFIdeficsModel", + "TFIdeficsPreTrainedModel", + ] + ) + + _import_structure["models.layoutlm"].extend( + [ + "TFLayoutLMForMaskedLM", + "TFLayoutLMForQuestionAnswering", + "TFLayoutLMForSequenceClassification", + "TFLayoutLMForTokenClassification", + "TFLayoutLMMainLayer", + "TFLayoutLMModel", + "TFLayoutLMPreTrainedModel", + ] + ) + _import_structure["models.layoutlmv3"].extend( + [ + "TFLayoutLMv3ForQuestionAnswering", + "TFLayoutLMv3ForSequenceClassification", + "TFLayoutLMv3ForTokenClassification", + "TFLayoutLMv3Model", + "TFLayoutLMv3PreTrainedModel", + ] + ) + _import_structure["models.led"].extend(["TFLEDForConditionalGeneration", "TFLEDModel", "TFLEDPreTrainedModel"]) + _import_structure["models.longformer"].extend( + [ + "TFLongformerForMaskedLM", + "TFLongformerForMultipleChoice", + "TFLongformerForQuestionAnswering", + "TFLongformerForSequenceClassification", + "TFLongformerForTokenClassification", + "TFLongformerModel", + "TFLongformerPreTrainedModel", + ] + ) + _import_structure["models.lxmert"].extend( + [ + "TFLxmertForPreTraining", + "TFLxmertMainLayer", + "TFLxmertModel", + "TFLxmertPreTrainedModel", + "TFLxmertVisualFeatureEncoder", + ] + ) + _import_structure["models.marian"].extend(["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"]) + _import_structure["models.mbart"].extend( + ["TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel"] + ) + _import_structure["models.mistral"].extend( + ["TFMistralForCausalLM", "TFMistralForSequenceClassification", "TFMistralModel", "TFMistralPreTrainedModel"] + ) + _import_structure["models.mobilebert"].extend( + [ + "TFMobileBertForMaskedLM", + "TFMobileBertForMultipleChoice", + "TFMobileBertForNextSentencePrediction", + "TFMobileBertForPreTraining", + "TFMobileBertForQuestionAnswering", + "TFMobileBertForSequenceClassification", + "TFMobileBertForTokenClassification", + "TFMobileBertMainLayer", + "TFMobileBertModel", + "TFMobileBertPreTrainedModel", + ] + ) + _import_structure["models.mobilevit"].extend( + [ + "TFMobileViTForImageClassification", + "TFMobileViTForSemanticSegmentation", + "TFMobileViTModel", + "TFMobileViTPreTrainedModel", + ] + ) + _import_structure["models.mpnet"].extend( + [ + "TFMPNetForMaskedLM", + "TFMPNetForMultipleChoice", + "TFMPNetForQuestionAnswering", + "TFMPNetForSequenceClassification", + "TFMPNetForTokenClassification", + "TFMPNetMainLayer", + "TFMPNetModel", + "TFMPNetPreTrainedModel", + ] + ) + _import_structure["models.mt5"].extend(["TFMT5EncoderModel", "TFMT5ForConditionalGeneration", "TFMT5Model"]) + _import_structure["models.openai"].extend( + [ + "TFOpenAIGPTDoubleHeadsModel", + "TFOpenAIGPTForSequenceClassification", + "TFOpenAIGPTLMHeadModel", + "TFOpenAIGPTMainLayer", + "TFOpenAIGPTModel", + "TFOpenAIGPTPreTrainedModel", + ] + ) + _import_structure["models.opt"].extend( + [ + "TFOPTForCausalLM", + "TFOPTModel", + "TFOPTPreTrainedModel", + ] + ) + _import_structure["models.pegasus"].extend( + [ + "TFPegasusForConditionalGeneration", + "TFPegasusModel", + "TFPegasusPreTrainedModel", + ] + ) + _import_structure["models.rag"].extend( + [ + "TFRagModel", + "TFRagPreTrainedModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + ] + ) + _import_structure["models.regnet"].extend( + [ + "TFRegNetForImageClassification", + "TFRegNetModel", + "TFRegNetPreTrainedModel", + ] + ) + _import_structure["models.rembert"].extend( + [ + "TFRemBertForCausalLM", + "TFRemBertForMaskedLM", + "TFRemBertForMultipleChoice", + "TFRemBertForQuestionAnswering", + "TFRemBertForSequenceClassification", + "TFRemBertForTokenClassification", + "TFRemBertModel", + "TFRemBertPreTrainedModel", + ] + ) + _import_structure["models.resnet"].extend( + [ + "TFResNetForImageClassification", + "TFResNetModel", + "TFResNetPreTrainedModel", + ] + ) + _import_structure["models.roberta"].extend( + [ + "TFRobertaForCausalLM", + "TFRobertaForMaskedLM", + "TFRobertaForMultipleChoice", + "TFRobertaForQuestionAnswering", + "TFRobertaForSequenceClassification", + "TFRobertaForTokenClassification", + "TFRobertaMainLayer", + "TFRobertaModel", + "TFRobertaPreTrainedModel", + ] + ) + _import_structure["models.roberta_prelayernorm"].extend( + [ + "TFRobertaPreLayerNormForCausalLM", + "TFRobertaPreLayerNormForMaskedLM", + "TFRobertaPreLayerNormForMultipleChoice", + "TFRobertaPreLayerNormForQuestionAnswering", + "TFRobertaPreLayerNormForSequenceClassification", + "TFRobertaPreLayerNormForTokenClassification", + "TFRobertaPreLayerNormMainLayer", + "TFRobertaPreLayerNormModel", + "TFRobertaPreLayerNormPreTrainedModel", + ] + ) + _import_structure["models.roformer"].extend( + [ + "TFRoFormerForCausalLM", + "TFRoFormerForMaskedLM", + "TFRoFormerForMultipleChoice", + "TFRoFormerForQuestionAnswering", + "TFRoFormerForSequenceClassification", + "TFRoFormerForTokenClassification", + "TFRoFormerModel", + "TFRoFormerPreTrainedModel", + ] + ) + _import_structure["models.sam"].extend( + [ + "TFSamModel", + "TFSamPreTrainedModel", + ] + ) + _import_structure["models.segformer"].extend( + [ + "TFSegformerDecodeHead", + "TFSegformerForImageClassification", + "TFSegformerForSemanticSegmentation", + "TFSegformerModel", + "TFSegformerPreTrainedModel", + ] + ) + _import_structure["models.speech_to_text"].extend( + [ + "TFSpeech2TextForConditionalGeneration", + "TFSpeech2TextModel", + "TFSpeech2TextPreTrainedModel", + ] + ) + _import_structure["models.swiftformer"].extend( + [ + "TFSwiftFormerForImageClassification", + "TFSwiftFormerModel", + "TFSwiftFormerPreTrainedModel", + ] + ) + _import_structure["models.swin"].extend( + [ + "TFSwinForImageClassification", + "TFSwinForMaskedImageModeling", + "TFSwinModel", + "TFSwinPreTrainedModel", + ] + ) + _import_structure["models.t5"].extend( + [ + "TFT5EncoderModel", + "TFT5ForConditionalGeneration", + "TFT5Model", + "TFT5PreTrainedModel", + ] + ) + _import_structure["models.tapas"].extend( + [ + "TFTapasForMaskedLM", + "TFTapasForQuestionAnswering", + "TFTapasForSequenceClassification", + "TFTapasModel", + "TFTapasPreTrainedModel", + ] + ) + _import_structure["models.vision_encoder_decoder"].extend(["TFVisionEncoderDecoderModel"]) + _import_structure["models.vision_text_dual_encoder"].extend(["TFVisionTextDualEncoderModel"]) + _import_structure["models.vit"].extend( + [ + "TFViTForImageClassification", + "TFViTModel", + "TFViTPreTrainedModel", + ] + ) + _import_structure["models.vit_mae"].extend( + [ + "TFViTMAEForPreTraining", + "TFViTMAEModel", + "TFViTMAEPreTrainedModel", + ] + ) + _import_structure["models.wav2vec2"].extend( + [ + "TFWav2Vec2ForCTC", + "TFWav2Vec2ForSequenceClassification", + "TFWav2Vec2Model", + "TFWav2Vec2PreTrainedModel", + ] + ) + _import_structure["models.whisper"].extend( + [ + "TFWhisperForConditionalGeneration", + "TFWhisperModel", + "TFWhisperPreTrainedModel", + ] + ) + _import_structure["models.xglm"].extend( + [ + "TFXGLMForCausalLM", + "TFXGLMModel", + "TFXGLMPreTrainedModel", + ] + ) + _import_structure["models.xlm"].extend( + [ + "TFXLMForMultipleChoice", + "TFXLMForQuestionAnsweringSimple", + "TFXLMForSequenceClassification", + "TFXLMForTokenClassification", + "TFXLMMainLayer", + "TFXLMModel", + "TFXLMPreTrainedModel", + "TFXLMWithLMHeadModel", + ] + ) + _import_structure["models.xlm_roberta"].extend( + [ + "TFXLMRobertaForCausalLM", + "TFXLMRobertaForMaskedLM", + "TFXLMRobertaForMultipleChoice", + "TFXLMRobertaForQuestionAnswering", + "TFXLMRobertaForSequenceClassification", + "TFXLMRobertaForTokenClassification", + "TFXLMRobertaModel", + "TFXLMRobertaPreTrainedModel", + ] + ) + _import_structure["models.xlnet"].extend( + [ + "TFXLNetForMultipleChoice", + "TFXLNetForQuestionAnsweringSimple", + "TFXLNetForSequenceClassification", + "TFXLNetForTokenClassification", + "TFXLNetLMHeadModel", + "TFXLNetMainLayer", + "TFXLNetModel", + "TFXLNetPreTrainedModel", + ] + ) + _import_structure["optimization_tf"] = [ + "AdamWeightDecay", + "GradientAccumulator", + "WarmUp", + "create_optimizer", + ] + _import_structure["tf_utils"] = [] + + +try: + if not ( + is_librosa_available() + and is_essentia_available() + and is_scipy_available() + and is_torch_available() + and is_pretty_midi_available() + ): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import ( + dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects, + ) + + _import_structure["utils.dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects"] = [ + name + for name in dir(dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects) + if not name.startswith("_") + ] +else: + _import_structure["models.pop2piano"].append("Pop2PianoFeatureExtractor") + _import_structure["models.pop2piano"].append("Pop2PianoTokenizer") + _import_structure["models.pop2piano"].append("Pop2PianoProcessor") + +try: + if not is_torchaudio_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import ( + dummy_torchaudio_objects, + ) + + _import_structure["utils.dummy_torchaudio_objects"] = [ + name for name in dir(dummy_torchaudio_objects) if not name.startswith("_") + ] +else: + _import_structure["models.musicgen_melody"].append("MusicgenMelodyFeatureExtractor") + _import_structure["models.musicgen_melody"].append("MusicgenMelodyProcessor") + + +# FLAX-backed objects +try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from .utils import dummy_flax_objects + + _import_structure["utils.dummy_flax_objects"] = [ + name for name in dir(dummy_flax_objects) if not name.startswith("_") + ] +else: + _import_structure["generation"].extend( + [ + "FlaxForcedBOSTokenLogitsProcessor", + "FlaxForcedEOSTokenLogitsProcessor", + "FlaxForceTokensLogitsProcessor", + "FlaxGenerationMixin", + "FlaxLogitsProcessor", + "FlaxLogitsProcessorList", + "FlaxLogitsWarper", + "FlaxMinLengthLogitsProcessor", + "FlaxTemperatureLogitsWarper", + "FlaxSuppressTokensAtBeginLogitsProcessor", + "FlaxSuppressTokensLogitsProcessor", + "FlaxTopKLogitsWarper", + "FlaxTopPLogitsWarper", + "FlaxWhisperTimeStampLogitsProcessor", + ] + ) + _import_structure["modeling_flax_outputs"] = [] + _import_structure["modeling_flax_utils"] = ["FlaxPreTrainedModel"] + _import_structure["models.albert"].extend( + [ + "FlaxAlbertForMaskedLM", + "FlaxAlbertForMultipleChoice", + "FlaxAlbertForPreTraining", + "FlaxAlbertForQuestionAnswering", + "FlaxAlbertForSequenceClassification", + "FlaxAlbertForTokenClassification", + "FlaxAlbertModel", + "FlaxAlbertPreTrainedModel", + ] + ) + _import_structure["models.auto"].extend( + [ + "FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING", + "FLAX_MODEL_FOR_CAUSAL_LM_MAPPING", + "FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", + "FLAX_MODEL_FOR_MASKED_LM_MAPPING", + "FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING", + "FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", + "FLAX_MODEL_FOR_PRETRAINING_MAPPING", + "FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING", + "FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", + "FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", + "FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", + "FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", + "FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING", + "FLAX_MODEL_MAPPING", + "FlaxAutoModel", + "FlaxAutoModelForCausalLM", + "FlaxAutoModelForImageClassification", + "FlaxAutoModelForMaskedLM", + "FlaxAutoModelForMultipleChoice", + "FlaxAutoModelForNextSentencePrediction", + "FlaxAutoModelForPreTraining", + "FlaxAutoModelForQuestionAnswering", + "FlaxAutoModelForSeq2SeqLM", + "FlaxAutoModelForSequenceClassification", + "FlaxAutoModelForSpeechSeq2Seq", + "FlaxAutoModelForTokenClassification", + "FlaxAutoModelForVision2Seq", + ] + ) + + # Flax models structure + + _import_structure["models.bart"].extend( + [ + "FlaxBartDecoderPreTrainedModel", + "FlaxBartForCausalLM", + "FlaxBartForConditionalGeneration", + "FlaxBartForQuestionAnswering", + "FlaxBartForSequenceClassification", + "FlaxBartModel", + "FlaxBartPreTrainedModel", + ] + ) + _import_structure["models.beit"].extend( + [ + "FlaxBeitForImageClassification", + "FlaxBeitForMaskedImageModeling", + "FlaxBeitModel", + "FlaxBeitPreTrainedModel", + ] + ) + + _import_structure["models.bert"].extend( + [ + "FlaxBertForCausalLM", + "FlaxBertForMaskedLM", + "FlaxBertForMultipleChoice", + "FlaxBertForNextSentencePrediction", + "FlaxBertForPreTraining", + "FlaxBertForQuestionAnswering", + "FlaxBertForSequenceClassification", + "FlaxBertForTokenClassification", + "FlaxBertModel", + "FlaxBertPreTrainedModel", + ] + ) + _import_structure["models.big_bird"].extend( + [ + "FlaxBigBirdForCausalLM", + "FlaxBigBirdForMaskedLM", + "FlaxBigBirdForMultipleChoice", + "FlaxBigBirdForPreTraining", + "FlaxBigBirdForQuestionAnswering", + "FlaxBigBirdForSequenceClassification", + "FlaxBigBirdForTokenClassification", + "FlaxBigBirdModel", + "FlaxBigBirdPreTrainedModel", + ] + ) + _import_structure["models.blenderbot"].extend( + [ + "FlaxBlenderbotForConditionalGeneration", + "FlaxBlenderbotModel", + "FlaxBlenderbotPreTrainedModel", + ] + ) + _import_structure["models.blenderbot_small"].extend( + [ + "FlaxBlenderbotSmallForConditionalGeneration", + "FlaxBlenderbotSmallModel", + "FlaxBlenderbotSmallPreTrainedModel", + ] + ) + _import_structure["models.bloom"].extend( + [ + "FlaxBloomForCausalLM", + "FlaxBloomModel", + "FlaxBloomPreTrainedModel", + ] + ) + _import_structure["models.clip"].extend( + [ + "FlaxCLIPModel", + "FlaxCLIPPreTrainedModel", + "FlaxCLIPTextModel", + "FlaxCLIPTextPreTrainedModel", + "FlaxCLIPTextModelWithProjection", + "FlaxCLIPVisionModel", + "FlaxCLIPVisionPreTrainedModel", + ] + ) + _import_structure["models.dinov2"].extend( + [ + "FlaxDinov2Model", + "FlaxDinov2ForImageClassification", + "FlaxDinov2PreTrainedModel", + ] + ) + _import_structure["models.distilbert"].extend( + [ + "FlaxDistilBertForMaskedLM", + "FlaxDistilBertForMultipleChoice", + "FlaxDistilBertForQuestionAnswering", + "FlaxDistilBertForSequenceClassification", + "FlaxDistilBertForTokenClassification", + "FlaxDistilBertModel", + "FlaxDistilBertPreTrainedModel", + ] + ) + _import_structure["models.electra"].extend( + [ + "FlaxElectraForCausalLM", + "FlaxElectraForMaskedLM", + "FlaxElectraForMultipleChoice", + "FlaxElectraForPreTraining", + "FlaxElectraForQuestionAnswering", + "FlaxElectraForSequenceClassification", + "FlaxElectraForTokenClassification", + "FlaxElectraModel", + "FlaxElectraPreTrainedModel", + ] + ) + _import_structure["models.encoder_decoder"].append("FlaxEncoderDecoderModel") + _import_structure["models.gpt2"].extend(["FlaxGPT2LMHeadModel", "FlaxGPT2Model", "FlaxGPT2PreTrainedModel"]) + _import_structure["models.gpt_neo"].extend( + ["FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel"] + ) + _import_structure["models.gptj"].extend(["FlaxGPTJForCausalLM", "FlaxGPTJModel", "FlaxGPTJPreTrainedModel"]) + _import_structure["models.llama"].extend(["FlaxLlamaForCausalLM", "FlaxLlamaModel", "FlaxLlamaPreTrainedModel"]) + _import_structure["models.gemma"].extend(["FlaxGemmaForCausalLM", "FlaxGemmaModel", "FlaxGemmaPreTrainedModel"]) + _import_structure["models.longt5"].extend( + [ + "FlaxLongT5ForConditionalGeneration", + "FlaxLongT5Model", + "FlaxLongT5PreTrainedModel", + ] + ) + _import_structure["models.marian"].extend( + [ + "FlaxMarianModel", + "FlaxMarianMTModel", + "FlaxMarianPreTrainedModel", + ] + ) + _import_structure["models.mbart"].extend( + [ + "FlaxMBartForConditionalGeneration", + "FlaxMBartForQuestionAnswering", + "FlaxMBartForSequenceClassification", + "FlaxMBartModel", + "FlaxMBartPreTrainedModel", + ] + ) + _import_structure["models.mistral"].extend( + [ + "FlaxMistralForCausalLM", + "FlaxMistralModel", + "FlaxMistralPreTrainedModel", + ] + ) + _import_structure["models.mt5"].extend(["FlaxMT5EncoderModel", "FlaxMT5ForConditionalGeneration", "FlaxMT5Model"]) + _import_structure["models.opt"].extend( + [ + "FlaxOPTForCausalLM", + "FlaxOPTModel", + "FlaxOPTPreTrainedModel", + ] + ) + _import_structure["models.pegasus"].extend( + [ + "FlaxPegasusForConditionalGeneration", + "FlaxPegasusModel", + "FlaxPegasusPreTrainedModel", + ] + ) + _import_structure["models.regnet"].extend( + [ + "FlaxRegNetForImageClassification", + "FlaxRegNetModel", + "FlaxRegNetPreTrainedModel", + ] + ) + _import_structure["models.resnet"].extend( + [ + "FlaxResNetForImageClassification", + "FlaxResNetModel", + "FlaxResNetPreTrainedModel", + ] + ) + _import_structure["models.roberta"].extend( + [ + "FlaxRobertaForCausalLM", + "FlaxRobertaForMaskedLM", + "FlaxRobertaForMultipleChoice", + "FlaxRobertaForQuestionAnswering", + "FlaxRobertaForSequenceClassification", + "FlaxRobertaForTokenClassification", + "FlaxRobertaModel", + "FlaxRobertaPreTrainedModel", + ] + ) + _import_structure["models.roberta_prelayernorm"].extend( + [ + "FlaxRobertaPreLayerNormForCausalLM", + "FlaxRobertaPreLayerNormForMaskedLM", + "FlaxRobertaPreLayerNormForMultipleChoice", + "FlaxRobertaPreLayerNormForQuestionAnswering", + "FlaxRobertaPreLayerNormForSequenceClassification", + "FlaxRobertaPreLayerNormForTokenClassification", + "FlaxRobertaPreLayerNormModel", + "FlaxRobertaPreLayerNormPreTrainedModel", + ] + ) + _import_structure["models.roformer"].extend( + [ + "FlaxRoFormerForMaskedLM", + "FlaxRoFormerForMultipleChoice", + "FlaxRoFormerForQuestionAnswering", + "FlaxRoFormerForSequenceClassification", + "FlaxRoFormerForTokenClassification", + "FlaxRoFormerModel", + "FlaxRoFormerPreTrainedModel", + ] + ) + _import_structure["models.speech_encoder_decoder"].append("FlaxSpeechEncoderDecoderModel") + _import_structure["models.t5"].extend( + [ + "FlaxT5EncoderModel", + "FlaxT5ForConditionalGeneration", + "FlaxT5Model", + "FlaxT5PreTrainedModel", + ] + ) + _import_structure["models.vision_encoder_decoder"].append("FlaxVisionEncoderDecoderModel") + _import_structure["models.vision_text_dual_encoder"].extend(["FlaxVisionTextDualEncoderModel"]) + _import_structure["models.vit"].extend(["FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel"]) + _import_structure["models.wav2vec2"].extend( + [ + "FlaxWav2Vec2ForCTC", + "FlaxWav2Vec2ForPreTraining", + "FlaxWav2Vec2Model", + "FlaxWav2Vec2PreTrainedModel", + ] + ) + _import_structure["models.whisper"].extend( + [ + "FlaxWhisperForConditionalGeneration", + "FlaxWhisperModel", + "FlaxWhisperPreTrainedModel", + "FlaxWhisperForAudioClassification", + ] + ) + _import_structure["models.xglm"].extend( + [ + "FlaxXGLMForCausalLM", + "FlaxXGLMModel", + "FlaxXGLMPreTrainedModel", + ] + ) + _import_structure["models.xlm_roberta"].extend( + [ + "FlaxXLMRobertaForMaskedLM", + "FlaxXLMRobertaForMultipleChoice", + "FlaxXLMRobertaForQuestionAnswering", + "FlaxXLMRobertaForSequenceClassification", + "FlaxXLMRobertaForTokenClassification", + "FlaxXLMRobertaModel", + "FlaxXLMRobertaForCausalLM", + "FlaxXLMRobertaPreTrainedModel", + ] + ) + + +# Direct imports for type-checking +if TYPE_CHECKING: + # Configuration + # Agents + from .agents import ( + Agent, + CodeAgent, + HfApiEngine, + ManagedAgent, + PipelineTool, + ReactAgent, + ReactCodeAgent, + ReactJsonAgent, + Tool, + Toolbox, + ToolCollection, + TransformersEngine, + launch_gradio_demo, + load_tool, + stream_to_gradio, + tool, + ) + from .configuration_utils import PretrainedConfig + + # Data + from .data import ( + DataProcessor, + InputExample, + InputFeatures, + SingleSentenceClassificationProcessor, + SquadExample, + SquadFeatures, + SquadV1Processor, + SquadV2Processor, + glue_compute_metrics, + glue_convert_examples_to_features, + glue_output_modes, + glue_processors, + glue_tasks_num_labels, + squad_convert_examples_to_features, + xnli_compute_metrics, + xnli_output_modes, + xnli_processors, + xnli_tasks_num_labels, + ) + from .data.data_collator import ( + DataCollator, + DataCollatorForLanguageModeling, + DataCollatorForMultipleChoice, + DataCollatorForPermutationLanguageModeling, + DataCollatorForSeq2Seq, + DataCollatorForSOP, + DataCollatorForTokenClassification, + DataCollatorForWholeWordMask, + DataCollatorWithFlattening, + DataCollatorWithPadding, + DefaultDataCollator, + default_data_collator, + ) + from .feature_extraction_sequence_utils import SequenceFeatureExtractor + + # Feature Extractor + from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin + + # Generation + from .generation import ( + AsyncTextIteratorStreamer, + CompileConfig, + GenerationConfig, + TextIteratorStreamer, + TextStreamer, + WatermarkingConfig, + ) + from .hf_argparser import HfArgumentParser + + # Integrations + from .integrations import ( + is_clearml_available, + is_comet_available, + is_dvclive_available, + is_neptune_available, + is_optuna_available, + is_ray_available, + is_ray_tune_available, + is_sigopt_available, + is_swanlab_available, + is_tensorboard_available, + is_wandb_available, + ) + + # Model Cards + from .modelcard import ModelCard + + # TF 2.0 <=> PyTorch conversion utilities + from .modeling_tf_pytorch_utils import ( + convert_tf_weight_name_to_pt_weight_name, + load_pytorch_checkpoint_in_tf2_model, + load_pytorch_model_in_tf2_model, + load_pytorch_weights_in_tf2_model, + load_tf2_checkpoint_in_pytorch_model, + load_tf2_model_in_pytorch_model, + load_tf2_weights_in_pytorch_model, + ) + from .models.albert import AlbertConfig + from .models.align import ( + AlignConfig, + AlignProcessor, + AlignTextConfig, + AlignVisionConfig, + ) + from .models.altclip import ( + AltCLIPConfig, + AltCLIPProcessor, + AltCLIPTextConfig, + AltCLIPVisionConfig, + ) + from .models.aria import ( + AriaConfig, + AriaProcessor, + AriaTextConfig, + ) + from .models.audio_spectrogram_transformer import ( + ASTConfig, + ASTFeatureExtractor, + ) + from .models.auto import ( + CONFIG_MAPPING, + FEATURE_EXTRACTOR_MAPPING, + IMAGE_PROCESSOR_MAPPING, + MODEL_NAMES_MAPPING, + PROCESSOR_MAPPING, + TOKENIZER_MAPPING, + AutoConfig, + AutoFeatureExtractor, + AutoImageProcessor, + AutoProcessor, + AutoTokenizer, + ) + from .models.autoformer import ( + AutoformerConfig, + ) + from .models.aya_vision import ( + AyaVisionConfig, + AyaVisionProcessor, + ) + from .models.bamba import BambaConfig + from .models.bark import ( + BarkCoarseConfig, + BarkConfig, + BarkFineConfig, + BarkProcessor, + BarkSemanticConfig, + ) + from .models.bart import BartConfig, BartTokenizer + from .models.beit import BeitConfig + from .models.bert import ( + BasicTokenizer, + BertConfig, + BertTokenizer, + WordpieceTokenizer, + ) + from .models.bert_generation import BertGenerationConfig + from .models.bert_japanese import ( + BertJapaneseTokenizer, + CharacterTokenizer, + MecabTokenizer, + ) + from .models.bertweet import BertweetTokenizer + from .models.big_bird import BigBirdConfig + from .models.bigbird_pegasus import ( + BigBirdPegasusConfig, + ) + from .models.biogpt import ( + BioGptConfig, + BioGptTokenizer, + ) + from .models.bit import BitConfig + from .models.blenderbot import ( + BlenderbotConfig, + BlenderbotTokenizer, + ) + from .models.blenderbot_small import ( + BlenderbotSmallConfig, + BlenderbotSmallTokenizer, + ) + from .models.blip import ( + BlipConfig, + BlipProcessor, + BlipTextConfig, + BlipVisionConfig, + ) + from .models.blip_2 import ( + Blip2Config, + Blip2Processor, + Blip2QFormerConfig, + Blip2VisionConfig, + ) + from .models.bloom import BloomConfig + from .models.bridgetower import ( + BridgeTowerConfig, + BridgeTowerProcessor, + BridgeTowerTextConfig, + BridgeTowerVisionConfig, + ) + from .models.bros import ( + BrosConfig, + BrosProcessor, + ) + from .models.byt5 import ByT5Tokenizer + from .models.camembert import ( + CamembertConfig, + ) + from .models.canine import ( + CanineConfig, + CanineTokenizer, + ) + from .models.chameleon import ( + ChameleonConfig, + ChameleonProcessor, + ChameleonVQVAEConfig, + ) + from .models.chinese_clip import ( + ChineseCLIPConfig, + ChineseCLIPProcessor, + ChineseCLIPTextConfig, + ChineseCLIPVisionConfig, + ) + from .models.clap import ( + ClapAudioConfig, + ClapConfig, + ClapProcessor, + ClapTextConfig, + ) + from .models.clip import ( + CLIPConfig, + CLIPProcessor, + CLIPTextConfig, + CLIPTokenizer, + CLIPVisionConfig, + ) + from .models.clipseg import ( + CLIPSegConfig, + CLIPSegProcessor, + CLIPSegTextConfig, + CLIPSegVisionConfig, + ) + from .models.clvp import ( + ClvpConfig, + ClvpDecoderConfig, + ClvpEncoderConfig, + ClvpFeatureExtractor, + ClvpProcessor, + ClvpTokenizer, + ) + from .models.codegen import ( + CodeGenConfig, + CodeGenTokenizer, + ) + from .models.cohere import CohereConfig + from .models.cohere2 import Cohere2Config + from .models.colpali import ( + ColPaliConfig, + ColPaliProcessor, + ) + from .models.conditional_detr import ( + ConditionalDetrConfig, + ) + from .models.convbert import ( + ConvBertConfig, + ConvBertTokenizer, + ) + from .models.convnext import ConvNextConfig + from .models.convnextv2 import ( + ConvNextV2Config, + ) + from .models.cpmant import ( + CpmAntConfig, + CpmAntTokenizer, + ) + from .models.ctrl import ( + CTRLConfig, + CTRLTokenizer, + ) + from .models.cvt import CvtConfig + from .models.dab_detr import ( + DabDetrConfig, + ) + from .models.dac import ( + DacConfig, + DacFeatureExtractor, + ) + from .models.data2vec import ( + Data2VecAudioConfig, + Data2VecTextConfig, + Data2VecVisionConfig, + ) + from .models.dbrx import DbrxConfig + from .models.deberta import ( + DebertaConfig, + DebertaTokenizer, + ) + from .models.deberta_v2 import ( + DebertaV2Config, + ) + from .models.decision_transformer import ( + DecisionTransformerConfig, + ) + from .models.deformable_detr import ( + DeformableDetrConfig, + ) + from .models.deit import DeiTConfig + from .models.deprecated.deta import DetaConfig + from .models.deprecated.efficientformer import ( + EfficientFormerConfig, + ) + from .models.deprecated.ernie_m import ErnieMConfig + from .models.deprecated.gptsan_japanese import ( + GPTSanJapaneseConfig, + GPTSanJapaneseTokenizer, + ) + from .models.deprecated.graphormer import GraphormerConfig + from .models.deprecated.jukebox import ( + JukeboxConfig, + JukeboxPriorConfig, + JukeboxTokenizer, + JukeboxVQVAEConfig, + ) + from .models.deprecated.mctct import ( + MCTCTConfig, + MCTCTFeatureExtractor, + MCTCTProcessor, + ) + from .models.deprecated.mega import MegaConfig + from .models.deprecated.mmbt import MMBTConfig + from .models.deprecated.nat import NatConfig + from .models.deprecated.nezha import NezhaConfig + from .models.deprecated.open_llama import ( + OpenLlamaConfig, + ) + from .models.deprecated.qdqbert import QDQBertConfig + from .models.deprecated.realm import ( + RealmConfig, + RealmTokenizer, + ) + from .models.deprecated.retribert import ( + RetriBertConfig, + RetriBertTokenizer, + ) + from .models.deprecated.speech_to_text_2 import ( + Speech2Text2Config, + Speech2Text2Processor, + Speech2Text2Tokenizer, + ) + from .models.deprecated.tapex import TapexTokenizer + from .models.deprecated.trajectory_transformer import ( + TrajectoryTransformerConfig, + ) + from .models.deprecated.transfo_xl import ( + TransfoXLConfig, + TransfoXLCorpus, + TransfoXLTokenizer, + ) + from .models.deprecated.tvlt import ( + TvltConfig, + TvltFeatureExtractor, + TvltProcessor, + ) + from .models.deprecated.van import VanConfig + from .models.deprecated.vit_hybrid import ( + ViTHybridConfig, + ) + from .models.deprecated.xlm_prophetnet import ( + XLMProphetNetConfig, + ) + from .models.depth_anything import DepthAnythingConfig + from .models.depth_pro import DepthProConfig + from .models.detr import DetrConfig + from .models.diffllama import DiffLlamaConfig + from .models.dinat import DinatConfig + from .models.dinov2 import Dinov2Config + from .models.dinov2_with_registers import Dinov2WithRegistersConfig + from .models.distilbert import ( + DistilBertConfig, + DistilBertTokenizer, + ) + from .models.donut import ( + DonutProcessor, + DonutSwinConfig, + ) + from .models.dpr import ( + DPRConfig, + DPRContextEncoderTokenizer, + DPRQuestionEncoderTokenizer, + DPRReaderOutput, + DPRReaderTokenizer, + ) + from .models.dpt import DPTConfig + from .models.efficientnet import ( + EfficientNetConfig, + ) + from .models.electra import ( + ElectraConfig, + ElectraTokenizer, + ) + from .models.emu3 import ( + Emu3Config, + Emu3Processor, + Emu3TextConfig, + Emu3VQVAEConfig, + ) + from .models.encodec import ( + EncodecConfig, + EncodecFeatureExtractor, + ) + from .models.encoder_decoder import EncoderDecoderConfig + from .models.ernie import ErnieConfig + from .models.esm import EsmConfig, EsmTokenizer + from .models.falcon import FalconConfig + from .models.falcon_mamba import FalconMambaConfig + from .models.fastspeech2_conformer import ( + FastSpeech2ConformerConfig, + FastSpeech2ConformerHifiGanConfig, + FastSpeech2ConformerTokenizer, + FastSpeech2ConformerWithHifiGanConfig, + ) + from .models.flaubert import FlaubertConfig, FlaubertTokenizer + from .models.flava import ( + FlavaConfig, + FlavaImageCodebookConfig, + FlavaImageConfig, + FlavaMultimodalConfig, + FlavaTextConfig, + ) + from .models.fnet import FNetConfig + from .models.focalnet import FocalNetConfig + from .models.fsmt import ( + FSMTConfig, + FSMTTokenizer, + ) + from .models.funnel import ( + FunnelConfig, + FunnelTokenizer, + ) + from .models.fuyu import FuyuConfig + from .models.gemma import GemmaConfig + from .models.gemma2 import Gemma2Config + from .models.gemma3 import Gemma3Config, Gemma3Processor, Gemma3TextConfig + from .models.git import ( + GitConfig, + GitProcessor, + GitVisionConfig, + ) + from .models.glm import GlmConfig + from .models.glpn import GLPNConfig + from .models.got_ocr2 import GotOcr2Config, GotOcr2Processor, GotOcr2VisionConfig + from .models.gpt2 import ( + GPT2Config, + GPT2Tokenizer, + ) + from .models.gpt_bigcode import ( + GPTBigCodeConfig, + ) + from .models.gpt_neo import GPTNeoConfig + from .models.gpt_neox import GPTNeoXConfig + from .models.gpt_neox_japanese import ( + GPTNeoXJapaneseConfig, + ) + from .models.gptj import GPTJConfig + from .models.granite import GraniteConfig + from .models.granitemoe import GraniteMoeConfig + from .models.granitemoeshared import GraniteMoeSharedConfig + from .models.grounding_dino import ( + GroundingDinoConfig, + GroundingDinoProcessor, + ) + from .models.groupvit import ( + GroupViTConfig, + GroupViTTextConfig, + GroupViTVisionConfig, + ) + from .models.helium import HeliumConfig + from .models.herbert import HerbertTokenizer + from .models.hiera import HieraConfig + from .models.hubert import HubertConfig + from .models.ibert import IBertConfig + from .models.idefics import ( + IdeficsConfig, + ) + from .models.idefics2 import Idefics2Config + from .models.idefics3 import Idefics3Config + from .models.ijepa import IJepaConfig + from .models.imagegpt import ImageGPTConfig + from .models.informer import InformerConfig + from .models.instructblip import ( + InstructBlipConfig, + InstructBlipProcessor, + InstructBlipQFormerConfig, + InstructBlipVisionConfig, + ) + from .models.instructblipvideo import ( + InstructBlipVideoConfig, + InstructBlipVideoProcessor, + InstructBlipVideoQFormerConfig, + InstructBlipVideoVisionConfig, + ) + from .models.jamba import JambaConfig + from .models.jetmoe import JetMoeConfig + from .models.kosmos2 import ( + Kosmos2Config, + Kosmos2Processor, + ) + from .models.layoutlm import ( + LayoutLMConfig, + LayoutLMTokenizer, + ) + from .models.layoutlmv2 import ( + LayoutLMv2Config, + LayoutLMv2FeatureExtractor, + LayoutLMv2ImageProcessor, + LayoutLMv2Processor, + LayoutLMv2Tokenizer, + ) + from .models.layoutlmv3 import ( + LayoutLMv3Config, + LayoutLMv3FeatureExtractor, + LayoutLMv3ImageProcessor, + LayoutLMv3Processor, + LayoutLMv3Tokenizer, + ) + from .models.layoutxlm import LayoutXLMProcessor + from .models.led import LEDConfig, LEDTokenizer + from .models.levit import LevitConfig + from .models.lilt import LiltConfig + from .models.llama import LlamaConfig + from .models.llava import ( + LlavaConfig, + LlavaProcessor, + ) + from .models.llava_next import ( + LlavaNextConfig, + LlavaNextProcessor, + ) + from .models.llava_next_video import ( + LlavaNextVideoConfig, + LlavaNextVideoProcessor, + ) + from .models.llava_onevision import ( + LlavaOnevisionConfig, + LlavaOnevisionProcessor, + ) + from .models.longformer import ( + LongformerConfig, + LongformerTokenizer, + ) + from .models.longt5 import LongT5Config + from .models.luke import ( + LukeConfig, + LukeTokenizer, + ) + from .models.lxmert import ( + LxmertConfig, + LxmertTokenizer, + ) + from .models.m2m_100 import M2M100Config + from .models.mamba import MambaConfig + from .models.mamba2 import Mamba2Config + from .models.marian import MarianConfig + from .models.markuplm import ( + MarkupLMConfig, + MarkupLMFeatureExtractor, + MarkupLMProcessor, + MarkupLMTokenizer, + ) + from .models.mask2former import ( + Mask2FormerConfig, + ) + from .models.maskformer import ( + MaskFormerConfig, + MaskFormerSwinConfig, + ) + from .models.mbart import MBartConfig + from .models.megatron_bert import ( + MegatronBertConfig, + ) + from .models.mgp_str import ( + MgpstrConfig, + MgpstrProcessor, + MgpstrTokenizer, + ) + from .models.mimi import ( + MimiConfig, + ) + from .models.mistral import MistralConfig + from .models.mistral3 import Mistral3Config + from .models.mixtral import MixtralConfig + from .models.mllama import ( + MllamaConfig, + MllamaProcessor, + ) + from .models.mobilebert import ( + MobileBertConfig, + MobileBertTokenizer, + ) + from .models.mobilenet_v1 import ( + MobileNetV1Config, + ) + from .models.mobilenet_v2 import ( + MobileNetV2Config, + ) + from .models.mobilevit import ( + MobileViTConfig, + ) + from .models.mobilevitv2 import ( + MobileViTV2Config, + ) + from .models.modernbert import ModernBertConfig + from .models.moonshine import MoonshineConfig + from .models.moshi import ( + MoshiConfig, + MoshiDepthConfig, + ) + from .models.mpnet import ( + MPNetConfig, + MPNetTokenizer, + ) + from .models.mpt import MptConfig + from .models.mra import MraConfig + from .models.mt5 import MT5Config + from .models.musicgen import ( + MusicgenConfig, + MusicgenDecoderConfig, + ) + from .models.musicgen_melody import ( + MusicgenMelodyConfig, + MusicgenMelodyDecoderConfig, + ) + from .models.mvp import MvpConfig, MvpTokenizer + from .models.myt5 import MyT5Tokenizer + from .models.nemotron import NemotronConfig + from .models.nllb_moe import NllbMoeConfig + from .models.nougat import NougatProcessor + from .models.nystromformer import ( + NystromformerConfig, + ) + from .models.olmo import OlmoConfig + from .models.olmo2 import Olmo2Config + from .models.olmoe import OlmoeConfig + from .models.omdet_turbo import ( + OmDetTurboConfig, + OmDetTurboProcessor, + ) + from .models.oneformer import ( + OneFormerConfig, + OneFormerProcessor, + ) + from .models.openai import ( + OpenAIGPTConfig, + OpenAIGPTTokenizer, + ) + from .models.opt import OPTConfig + from .models.owlv2 import ( + Owlv2Config, + Owlv2Processor, + Owlv2TextConfig, + Owlv2VisionConfig, + ) + from .models.owlvit import ( + OwlViTConfig, + OwlViTProcessor, + OwlViTTextConfig, + OwlViTVisionConfig, + ) + from .models.paligemma import ( + PaliGemmaConfig, + ) + from .models.patchtsmixer import ( + PatchTSMixerConfig, + ) + from .models.patchtst import PatchTSTConfig + from .models.pegasus import ( + PegasusConfig, + PegasusTokenizer, + ) + from .models.pegasus_x import ( + PegasusXConfig, + ) + from .models.perceiver import ( + PerceiverConfig, + PerceiverTokenizer, + ) + from .models.persimmon import ( + PersimmonConfig, + ) + from .models.phi import PhiConfig + from .models.phi3 import Phi3Config + from .models.phimoe import PhimoeConfig + from .models.phobert import PhobertTokenizer + from .models.pix2struct import ( + Pix2StructConfig, + Pix2StructProcessor, + Pix2StructTextConfig, + Pix2StructVisionConfig, + ) + from .models.pixtral import ( + PixtralProcessor, + PixtralVisionConfig, + ) + from .models.plbart import PLBartConfig + from .models.poolformer import ( + PoolFormerConfig, + ) + from .models.pop2piano import ( + Pop2PianoConfig, + ) + from .models.prophetnet import ( + ProphetNetConfig, + ProphetNetTokenizer, + ) + from .models.pvt import PvtConfig + from .models.pvt_v2 import PvtV2Config + from .models.qwen2 import Qwen2Config, Qwen2Tokenizer + from .models.qwen2_5_vl import ( + Qwen2_5_VLConfig, + Qwen2_5_VLProcessor, + ) + from .models.qwen2_audio import ( + Qwen2AudioConfig, + Qwen2AudioEncoderConfig, + Qwen2AudioProcessor, + ) + from .models.qwen2_moe import Qwen2MoeConfig + from .models.qwen2_vl import ( + Qwen2VLConfig, + Qwen2VLProcessor, + ) + from .models.rag import RagConfig, RagRetriever, RagTokenizer + from .models.recurrent_gemma import RecurrentGemmaConfig + from .models.reformer import ReformerConfig + from .models.regnet import RegNetConfig + from .models.rembert import RemBertConfig + from .models.resnet import ResNetConfig + from .models.roberta import ( + RobertaConfig, + RobertaTokenizer, + ) + from .models.roberta_prelayernorm import ( + RobertaPreLayerNormConfig, + ) + from .models.roc_bert import ( + RoCBertConfig, + RoCBertTokenizer, + ) + from .models.roformer import ( + RoFormerConfig, + RoFormerTokenizer, + ) + from .models.rt_detr import ( + RTDetrConfig, + RTDetrResNetConfig, + ) + from .models.rt_detr_v2 import RTDetrV2Config + from .models.rwkv import RwkvConfig + from .models.sam import ( + SamConfig, + SamMaskDecoderConfig, + SamProcessor, + SamPromptEncoderConfig, + SamVisionConfig, + ) + from .models.seamless_m4t import ( + SeamlessM4TConfig, + SeamlessM4TFeatureExtractor, + SeamlessM4TProcessor, + ) + from .models.seamless_m4t_v2 import ( + SeamlessM4Tv2Config, + ) + from .models.segformer import SegformerConfig + from .models.seggpt import SegGptConfig + from .models.sew import SEWConfig + from .models.sew_d import SEWDConfig + from .models.siglip import ( + SiglipConfig, + SiglipProcessor, + SiglipTextConfig, + SiglipVisionConfig, + ) + from .models.siglip2 import ( + Siglip2Config, + Siglip2Processor, + Siglip2TextConfig, + Siglip2VisionConfig, + ) + from .models.smolvlm import SmolVLMConfig + from .models.speech_encoder_decoder import SpeechEncoderDecoderConfig + from .models.speech_to_text import ( + Speech2TextConfig, + Speech2TextFeatureExtractor, + Speech2TextProcessor, + ) + from .models.speecht5 import ( + SpeechT5Config, + SpeechT5FeatureExtractor, + SpeechT5HifiGanConfig, + SpeechT5Processor, + ) + from .models.splinter import ( + SplinterConfig, + SplinterTokenizer, + ) + from .models.squeezebert import ( + SqueezeBertConfig, + SqueezeBertTokenizer, + ) + from .models.stablelm import StableLmConfig + from .models.starcoder2 import Starcoder2Config + from .models.superglue import SuperGlueConfig + from .models.superpoint import SuperPointConfig + from .models.swiftformer import ( + SwiftFormerConfig, + ) + from .models.swin import SwinConfig + from .models.swin2sr import Swin2SRConfig + from .models.swinv2 import Swinv2Config + from .models.switch_transformers import ( + SwitchTransformersConfig, + ) + from .models.t5 import T5Config + from .models.table_transformer import ( + TableTransformerConfig, + ) + from .models.tapas import ( + TapasConfig, + TapasTokenizer, + ) + from .models.textnet import TextNetConfig + from .models.time_series_transformer import ( + TimeSeriesTransformerConfig, + ) + from .models.timesformer import ( + TimesformerConfig, + ) + from .models.timm_backbone import TimmBackboneConfig + from .models.timm_wrapper import TimmWrapperConfig + from .models.trocr import ( + TrOCRConfig, + TrOCRProcessor, + ) + from .models.tvp import ( + TvpConfig, + TvpProcessor, + ) + from .models.udop import UdopConfig, UdopProcessor + from .models.umt5 import UMT5Config + from .models.unispeech import ( + UniSpeechConfig, + ) + from .models.unispeech_sat import ( + UniSpeechSatConfig, + ) + from .models.univnet import ( + UnivNetConfig, + UnivNetFeatureExtractor, + ) + from .models.upernet import UperNetConfig + from .models.video_llava import VideoLlavaConfig + from .models.videomae import VideoMAEConfig + from .models.vilt import ( + ViltConfig, + ViltFeatureExtractor, + ViltImageProcessor, + ViltProcessor, + ) + from .models.vipllava import ( + VipLlavaConfig, + ) + from .models.vision_encoder_decoder import VisionEncoderDecoderConfig + from .models.vision_text_dual_encoder import ( + VisionTextDualEncoderConfig, + VisionTextDualEncoderProcessor, + ) + from .models.visual_bert import ( + VisualBertConfig, + ) + from .models.vit import ViTConfig + from .models.vit_mae import ViTMAEConfig + from .models.vit_msn import ViTMSNConfig + from .models.vitdet import VitDetConfig + from .models.vitmatte import VitMatteConfig + from .models.vitpose import VitPoseConfig + from .models.vitpose_backbone import VitPoseBackboneConfig + from .models.vits import ( + VitsConfig, + VitsTokenizer, + ) + from .models.vivit import VivitConfig + from .models.wav2vec2 import ( + Wav2Vec2Config, + Wav2Vec2CTCTokenizer, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + Wav2Vec2Tokenizer, + ) + from .models.wav2vec2_bert import ( + Wav2Vec2BertConfig, + Wav2Vec2BertProcessor, + ) + from .models.wav2vec2_conformer import ( + Wav2Vec2ConformerConfig, + ) + from .models.wav2vec2_phoneme import Wav2Vec2PhonemeCTCTokenizer + from .models.wav2vec2_with_lm import Wav2Vec2ProcessorWithLM + from .models.wavlm import WavLMConfig + from .models.whisper import ( + WhisperConfig, + WhisperFeatureExtractor, + WhisperProcessor, + WhisperTokenizer, + ) + from .models.x_clip import ( + XCLIPConfig, + XCLIPProcessor, + XCLIPTextConfig, + XCLIPVisionConfig, + ) + from .models.xglm import XGLMConfig + from .models.xlm import XLMConfig, XLMTokenizer + from .models.xlm_roberta import ( + XLMRobertaConfig, + ) + from .models.xlm_roberta_xl import ( + XLMRobertaXLConfig, + ) + from .models.xlnet import XLNetConfig + from .models.xmod import XmodConfig + from .models.yolos import YolosConfig + from .models.yoso import YosoConfig + from .models.zamba import ZambaConfig + from .models.zamba2 import Zamba2Config + from .models.zoedepth import ZoeDepthConfig + + # Pipelines + from .pipelines import ( + AudioClassificationPipeline, + AutomaticSpeechRecognitionPipeline, + CsvPipelineDataFormat, + DepthEstimationPipeline, + DocumentQuestionAnsweringPipeline, + FeatureExtractionPipeline, + FillMaskPipeline, + ImageClassificationPipeline, + ImageFeatureExtractionPipeline, + ImageSegmentationPipeline, + ImageTextToTextPipeline, + ImageToImagePipeline, + ImageToTextPipeline, + JsonPipelineDataFormat, + MaskGenerationPipeline, + NerPipeline, + ObjectDetectionPipeline, + PipedPipelineDataFormat, + Pipeline, + PipelineDataFormat, + QuestionAnsweringPipeline, + SummarizationPipeline, + TableQuestionAnsweringPipeline, + Text2TextGenerationPipeline, + TextClassificationPipeline, + TextGenerationPipeline, + TextToAudioPipeline, + TokenClassificationPipeline, + TranslationPipeline, + VideoClassificationPipeline, + VisualQuestionAnsweringPipeline, + ZeroShotAudioClassificationPipeline, + ZeroShotClassificationPipeline, + ZeroShotImageClassificationPipeline, + ZeroShotObjectDetectionPipeline, + pipeline, + ) + from .processing_utils import ProcessorMixin + + # Tokenization + from .tokenization_utils import PreTrainedTokenizer + from .tokenization_utils_base import ( + AddedToken, + BatchEncoding, + CharSpan, + PreTrainedTokenizerBase, + SpecialTokensMixin, + TokenSpan, + ) + + # Trainer + from .trainer_callback import ( + DefaultFlowCallback, + EarlyStoppingCallback, + PrinterCallback, + ProgressCallback, + TrainerCallback, + TrainerControl, + TrainerState, + ) + from .trainer_utils import ( + EvalPrediction, + IntervalStrategy, + SchedulerType, + enable_full_determinism, + set_seed, + ) + from .training_args import TrainingArguments + from .training_args_seq2seq import Seq2SeqTrainingArguments + from .training_args_tf import TFTrainingArguments + + # Files and general utilities + from .utils import ( + CONFIG_NAME, + MODEL_CARD_NAME, + PYTORCH_PRETRAINED_BERT_CACHE, + PYTORCH_TRANSFORMERS_CACHE, + SPIECE_UNDERLINE, + TF2_WEIGHTS_NAME, + TF_WEIGHTS_NAME, + TRANSFORMERS_CACHE, + WEIGHTS_NAME, + TensorType, + add_end_docstrings, + add_start_docstrings, + is_apex_available, + is_av_available, + is_bitsandbytes_available, + is_datasets_available, + is_faiss_available, + is_flax_available, + is_keras_nlp_available, + is_phonemizer_available, + is_psutil_available, + is_py3nvml_available, + is_pyctcdecode_available, + is_sacremoses_available, + is_safetensors_available, + is_scipy_available, + is_sentencepiece_available, + is_sklearn_available, + is_speech_available, + is_tensorflow_text_available, + is_tf_available, + is_timm_available, + is_tokenizers_available, + is_torch_available, + is_torch_hpu_available, + is_torch_mlu_available, + is_torch_musa_available, + is_torch_neuroncore_available, + is_torch_npu_available, + is_torch_tpu_available, + is_torch_xla_available, + is_torch_xpu_available, + is_torchvision_available, + is_vision_available, + logging, + ) + + # bitsandbytes config + from .utils.quantization_config import ( + AqlmConfig, + AwqConfig, + BitNetConfig, + BitsAndBytesConfig, + CompressedTensorsConfig, + EetqConfig, + FbgemmFp8Config, + FineGrainedFP8Config, + GPTQConfig, + HiggsConfig, + HqqConfig, + QuantoConfig, + SpQRConfig, + TorchAoConfig, + VptqConfig, + ) + + try: + if not is_sentencepiece_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_sentencepiece_objects import * + else: + from .models.albert import AlbertTokenizer + from .models.barthez import BarthezTokenizer + from .models.bartpho import BartphoTokenizer + from .models.bert_generation import BertGenerationTokenizer + from .models.big_bird import BigBirdTokenizer + from .models.camembert import CamembertTokenizer + from .models.code_llama import CodeLlamaTokenizer + from .models.cpm import CpmTokenizer + from .models.deberta_v2 import DebertaV2Tokenizer + from .models.deprecated.ernie_m import ErnieMTokenizer + from .models.deprecated.xlm_prophetnet import XLMProphetNetTokenizer + from .models.fnet import FNetTokenizer + from .models.gemma import GemmaTokenizer + from .models.gpt_sw3 import GPTSw3Tokenizer + from .models.layoutxlm import LayoutXLMTokenizer + from .models.llama import LlamaTokenizer + from .models.m2m_100 import M2M100Tokenizer + from .models.marian import MarianTokenizer + from .models.mbart import MBartTokenizer + from .models.mbart50 import MBart50Tokenizer + from .models.mluke import MLukeTokenizer + from .models.mt5 import MT5Tokenizer + from .models.nllb import NllbTokenizer + from .models.pegasus import PegasusTokenizer + from .models.plbart import PLBartTokenizer + from .models.reformer import ReformerTokenizer + from .models.rembert import RemBertTokenizer + from .models.seamless_m4t import SeamlessM4TTokenizer + from .models.siglip import SiglipTokenizer + from .models.speech_to_text import Speech2TextTokenizer + from .models.speecht5 import SpeechT5Tokenizer + from .models.t5 import T5Tokenizer + from .models.udop import UdopTokenizer + from .models.xglm import XGLMTokenizer + from .models.xlm_roberta import XLMRobertaTokenizer + from .models.xlnet import XLNetTokenizer + + try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_tokenizers_objects import * + else: + # Fast tokenizers imports + from .models.albert import AlbertTokenizerFast + from .models.bart import BartTokenizerFast + from .models.barthez import BarthezTokenizerFast + from .models.bert import BertTokenizerFast + from .models.big_bird import BigBirdTokenizerFast + from .models.blenderbot import BlenderbotTokenizerFast + from .models.blenderbot_small import BlenderbotSmallTokenizerFast + from .models.bloom import BloomTokenizerFast + from .models.camembert import CamembertTokenizerFast + from .models.clip import CLIPTokenizerFast + from .models.code_llama import CodeLlamaTokenizerFast + from .models.codegen import CodeGenTokenizerFast + from .models.cohere import CohereTokenizerFast + from .models.convbert import ConvBertTokenizerFast + from .models.cpm import CpmTokenizerFast + from .models.deberta import DebertaTokenizerFast + from .models.deberta_v2 import DebertaV2TokenizerFast + from .models.deprecated.realm import RealmTokenizerFast + from .models.deprecated.retribert import RetriBertTokenizerFast + from .models.distilbert import DistilBertTokenizerFast + from .models.dpr import ( + DPRContextEncoderTokenizerFast, + DPRQuestionEncoderTokenizerFast, + DPRReaderTokenizerFast, + ) + from .models.electra import ElectraTokenizerFast + from .models.fnet import FNetTokenizerFast + from .models.funnel import FunnelTokenizerFast + from .models.gemma import GemmaTokenizerFast + from .models.gpt2 import GPT2TokenizerFast + from .models.gpt_neox import GPTNeoXTokenizerFast + from .models.gpt_neox_japanese import GPTNeoXJapaneseTokenizer + from .models.herbert import HerbertTokenizerFast + from .models.layoutlm import LayoutLMTokenizerFast + from .models.layoutlmv2 import LayoutLMv2TokenizerFast + from .models.layoutlmv3 import LayoutLMv3TokenizerFast + from .models.layoutxlm import LayoutXLMTokenizerFast + from .models.led import LEDTokenizerFast + from .models.llama import LlamaTokenizerFast + from .models.longformer import LongformerTokenizerFast + from .models.lxmert import LxmertTokenizerFast + from .models.markuplm import MarkupLMTokenizerFast + from .models.mbart import MBartTokenizerFast + from .models.mbart50 import MBart50TokenizerFast + from .models.mobilebert import MobileBertTokenizerFast + from .models.mpnet import MPNetTokenizerFast + from .models.mt5 import MT5TokenizerFast + from .models.mvp import MvpTokenizerFast + from .models.nllb import NllbTokenizerFast + from .models.nougat import NougatTokenizerFast + from .models.openai import OpenAIGPTTokenizerFast + from .models.pegasus import PegasusTokenizerFast + from .models.qwen2 import Qwen2TokenizerFast + from .models.reformer import ReformerTokenizerFast + from .models.rembert import RemBertTokenizerFast + from .models.roberta import RobertaTokenizerFast + from .models.roformer import RoFormerTokenizerFast + from .models.seamless_m4t import SeamlessM4TTokenizerFast + from .models.splinter import SplinterTokenizerFast + from .models.squeezebert import SqueezeBertTokenizerFast + from .models.t5 import T5TokenizerFast + from .models.udop import UdopTokenizerFast + from .models.whisper import WhisperTokenizerFast + from .models.xglm import XGLMTokenizerFast + from .models.xlm_roberta import XLMRobertaTokenizerFast + from .models.xlnet import XLNetTokenizerFast + from .tokenization_utils_fast import PreTrainedTokenizerFast + + try: + if not (is_sentencepiece_available() and is_tokenizers_available()): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummies_sentencepiece_and_tokenizers_objects import * + else: + from .convert_slow_tokenizer import ( + SLOW_TO_FAST_CONVERTERS, + convert_slow_tokenizer, + ) + + try: + if not is_tensorflow_text_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_tensorflow_text_objects import * + else: + from .models.bert import TFBertTokenizer + + try: + if not is_keras_nlp_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_keras_nlp_objects import * + else: + from .models.gpt2 import TFGPT2Tokenizer + + try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_vision_objects import * + else: + from .image_processing_base import ImageProcessingMixin + from .image_processing_utils import BaseImageProcessor + from .image_utils import ImageFeatureExtractionMixin + from .models.aria import AriaImageProcessor + from .models.beit import BeitFeatureExtractor, BeitImageProcessor + from .models.bit import BitImageProcessor + from .models.blip import BlipImageProcessor + from .models.bridgetower import BridgeTowerImageProcessor + from .models.chameleon import ChameleonImageProcessor + from .models.chinese_clip import ( + ChineseCLIPFeatureExtractor, + ChineseCLIPImageProcessor, + ) + from .models.clip import CLIPFeatureExtractor, CLIPImageProcessor + from .models.conditional_detr import ( + ConditionalDetrFeatureExtractor, + ConditionalDetrImageProcessor, + ) + from .models.convnext import ConvNextFeatureExtractor, ConvNextImageProcessor + from .models.deformable_detr import DeformableDetrFeatureExtractor, DeformableDetrImageProcessor + from .models.deit import DeiTFeatureExtractor, DeiTImageProcessor + from .models.deprecated.deta import DetaImageProcessor + from .models.deprecated.efficientformer import EfficientFormerImageProcessor + from .models.deprecated.tvlt import TvltImageProcessor + from .models.deprecated.vit_hybrid import ViTHybridImageProcessor + from .models.depth_pro import DepthProImageProcessor, DepthProImageProcessorFast + from .models.detr import DetrFeatureExtractor, DetrImageProcessor + from .models.donut import DonutFeatureExtractor, DonutImageProcessor + from .models.dpt import DPTFeatureExtractor, DPTImageProcessor + from .models.efficientnet import EfficientNetImageProcessor + from .models.emu3 import Emu3ImageProcessor + from .models.flava import ( + FlavaFeatureExtractor, + FlavaImageProcessor, + FlavaProcessor, + ) + from .models.fuyu import FuyuImageProcessor, FuyuProcessor + from .models.gemma3 import Gemma3ImageProcessor + from .models.glpn import GLPNFeatureExtractor, GLPNImageProcessor + from .models.got_ocr2 import GotOcr2ImageProcessor + from .models.grounding_dino import GroundingDinoImageProcessor + from .models.idefics import IdeficsImageProcessor + from .models.idefics2 import Idefics2ImageProcessor + from .models.idefics3 import Idefics3ImageProcessor + from .models.imagegpt import ImageGPTFeatureExtractor, ImageGPTImageProcessor + from .models.instructblipvideo import InstructBlipVideoImageProcessor + from .models.layoutlmv2 import ( + LayoutLMv2FeatureExtractor, + LayoutLMv2ImageProcessor, + ) + from .models.layoutlmv3 import ( + LayoutLMv3FeatureExtractor, + LayoutLMv3ImageProcessor, + ) + from .models.levit import LevitFeatureExtractor, LevitImageProcessor + from .models.llava import LlavaImageProcessor + from .models.llava_next import LlavaNextImageProcessor + from .models.llava_next_video import LlavaNextVideoImageProcessor + from .models.llava_onevision import LlavaOnevisionImageProcessor, LlavaOnevisionVideoProcessor + from .models.mask2former import Mask2FormerImageProcessor + from .models.maskformer import ( + MaskFormerFeatureExtractor, + MaskFormerImageProcessor, + ) + from .models.mllama import MllamaImageProcessor + from .models.mobilenet_v1 import ( + MobileNetV1FeatureExtractor, + MobileNetV1ImageProcessor, + ) + from .models.mobilenet_v2 import ( + MobileNetV2FeatureExtractor, + MobileNetV2ImageProcessor, + ) + from .models.mobilevit import MobileViTFeatureExtractor, MobileViTImageProcessor + from .models.nougat import NougatImageProcessor + from .models.oneformer import OneFormerImageProcessor + from .models.owlv2 import Owlv2ImageProcessor + from .models.owlvit import OwlViTFeatureExtractor, OwlViTImageProcessor + from .models.perceiver import PerceiverFeatureExtractor, PerceiverImageProcessor + from .models.pix2struct import Pix2StructImageProcessor + from .models.pixtral import PixtralImageProcessor + from .models.poolformer import ( + PoolFormerFeatureExtractor, + PoolFormerImageProcessor, + ) + from .models.pvt import PvtImageProcessor + from .models.qwen2_vl import Qwen2VLImageProcessor + from .models.rt_detr import RTDetrImageProcessor + from .models.sam import SamImageProcessor + from .models.segformer import SegformerFeatureExtractor, SegformerImageProcessor + from .models.seggpt import SegGptImageProcessor + from .models.siglip import SiglipImageProcessor + from .models.siglip2 import Siglip2ImageProcessor + from .models.smolvlm import SmolVLMImageProcessor + from .models.superglue import SuperGlueImageProcessor + from .models.superpoint import SuperPointImageProcessor + from .models.swin2sr import Swin2SRImageProcessor + from .models.textnet import TextNetImageProcessor + from .models.tvp import TvpImageProcessor + from .models.video_llava import VideoLlavaImageProcessor + from .models.videomae import VideoMAEFeatureExtractor, VideoMAEImageProcessor + from .models.vilt import ViltFeatureExtractor, ViltImageProcessor, ViltProcessor + from .models.vit import ViTFeatureExtractor, ViTImageProcessor + from .models.vitmatte import VitMatteImageProcessor + from .models.vitpose import VitPoseImageProcessor + from .models.vivit import VivitImageProcessor + from .models.yolos import YolosFeatureExtractor, YolosImageProcessor + from .models.zoedepth import ZoeDepthImageProcessor + + try: + if not is_torchvision_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_torchvision_objects import * + else: + from .image_processing_utils_fast import BaseImageProcessorFast + from .models.blip import BlipImageProcessorFast + from .models.clip import CLIPImageProcessorFast + from .models.convnext import ConvNextImageProcessorFast + from .models.deformable_detr import DeformableDetrImageProcessorFast + from .models.deit import DeiTImageProcessorFast + from .models.depth_pro import DepthProImageProcessorFast + from .models.detr import DetrImageProcessorFast + from .models.gemma3 import Gemma3ImageProcessorFast + from .models.got_ocr2 import GotOcr2ImageProcessorFast + from .models.llava import LlavaImageProcessorFast + from .models.llava_next import LlavaNextImageProcessorFast + from .models.llava_onevision import LlavaOnevisionImageProcessorFast + from .models.pixtral import PixtralImageProcessorFast + from .models.qwen2_vl import Qwen2VLImageProcessorFast + from .models.rt_detr import RTDetrImageProcessorFast + from .models.siglip import SiglipImageProcessorFast + from .models.siglip2 import Siglip2ImageProcessorFast + from .models.vit import ViTImageProcessorFast + + try: + if not (is_torchvision_available() and is_timm_available()): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_timm_and_torchvision_objects import * + else: + from .models.timm_wrapper import TimmWrapperImageProcessor + + # Modeling + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_pt_objects import * + else: + from .cache_utils import ( + Cache, + CacheConfig, + DynamicCache, + EncoderDecoderCache, + HQQQuantizedCache, + HybridCache, + MambaCache, + OffloadedCache, + OffloadedStaticCache, + QuantizedCache, + QuantizedCacheConfig, + QuantoQuantizedCache, + SinkCache, + SlidingWindowCache, + StaticCache, + ) + from .data.datasets import ( + GlueDataset, + GlueDataTrainingArguments, + LineByLineTextDataset, + LineByLineWithRefDataset, + LineByLineWithSOPTextDataset, + SquadDataset, + SquadDataTrainingArguments, + TextDataset, + TextDatasetForNextSentencePrediction, + ) + from .generation import ( + AlternatingCodebooksLogitsProcessor, + BayesianDetectorConfig, + BayesianDetectorModel, + BeamScorer, + BeamSearchScorer, + ClassifierFreeGuidanceLogitsProcessor, + ConstrainedBeamSearchScorer, + Constraint, + ConstraintListState, + DisjunctiveConstraint, + EncoderNoRepeatNGramLogitsProcessor, + EncoderRepetitionPenaltyLogitsProcessor, + EosTokenCriteria, + EpsilonLogitsWarper, + EtaLogitsWarper, + ExponentialDecayLengthPenalty, + ForcedBOSTokenLogitsProcessor, + ForcedEOSTokenLogitsProcessor, + GenerationMixin, + HammingDiversityLogitsProcessor, + InfNanRemoveLogitsProcessor, + LogitNormalization, + LogitsProcessor, + LogitsProcessorList, + MaxLengthCriteria, + MaxTimeCriteria, + MinLengthLogitsProcessor, + MinNewTokensLengthLogitsProcessor, + MinPLogitsWarper, + NoBadWordsLogitsProcessor, + NoRepeatNGramLogitsProcessor, + PhrasalConstraint, + PrefixConstrainedLogitsProcessor, + RepetitionPenaltyLogitsProcessor, + SequenceBiasLogitsProcessor, + StoppingCriteria, + StoppingCriteriaList, + StopStringCriteria, + SuppressTokensAtBeginLogitsProcessor, + SuppressTokensLogitsProcessor, + SynthIDTextWatermarkDetector, + SynthIDTextWatermarkingConfig, + SynthIDTextWatermarkLogitsProcessor, + TemperatureLogitsWarper, + TopKLogitsWarper, + TopPLogitsWarper, + TypicalLogitsWarper, + UnbatchedClassifierFreeGuidanceLogitsProcessor, + WatermarkDetector, + WatermarkLogitsProcessor, + WhisperTimeStampLogitsProcessor, + ) + from .integrations.executorch import ( + TorchExportableModuleWithStaticCache, + convert_and_export_with_cache, + ) + from .modeling_rope_utils import ROPE_INIT_FUNCTIONS + from .modeling_utils import PreTrainedModel + from .models.albert import ( + AlbertForMaskedLM, + AlbertForMultipleChoice, + AlbertForPreTraining, + AlbertForQuestionAnswering, + AlbertForSequenceClassification, + AlbertForTokenClassification, + AlbertModel, + AlbertPreTrainedModel, + load_tf_weights_in_albert, + ) + from .models.align import ( + AlignModel, + AlignPreTrainedModel, + AlignTextModel, + AlignVisionModel, + ) + from .models.altclip import ( + AltCLIPModel, + AltCLIPPreTrainedModel, + AltCLIPTextModel, + AltCLIPVisionModel, + ) + from .models.aria import ( + AriaForConditionalGeneration, + AriaPreTrainedModel, + AriaTextForCausalLM, + AriaTextModel, + AriaTextPreTrainedModel, + ) + from .models.audio_spectrogram_transformer import ( + ASTForAudioClassification, + ASTModel, + ASTPreTrainedModel, + ) + from .models.auto import ( + MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, + MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING, + MODEL_FOR_AUDIO_XVECTOR_MAPPING, + MODEL_FOR_BACKBONE_MAPPING, + MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, + MODEL_FOR_CAUSAL_LM_MAPPING, + MODEL_FOR_CTC_MAPPING, + MODEL_FOR_DEPTH_ESTIMATION_MAPPING, + MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + MODEL_FOR_IMAGE_MAPPING, + MODEL_FOR_IMAGE_SEGMENTATION_MAPPING, + MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING, + MODEL_FOR_IMAGE_TO_IMAGE_MAPPING, + MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING, + MODEL_FOR_KEYPOINT_DETECTION_MAPPING, + MODEL_FOR_MASK_GENERATION_MAPPING, + MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, + MODEL_FOR_MASKED_LM_MAPPING, + MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + MODEL_FOR_OBJECT_DETECTION_MAPPING, + MODEL_FOR_PRETRAINING_MAPPING, + MODEL_FOR_QUESTION_ANSWERING_MAPPING, + MODEL_FOR_RETRIEVAL_MAPPING, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, + MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, + MODEL_FOR_TEXT_ENCODING_MAPPING, + MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING, + MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING, + MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING, + MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING, + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, + MODEL_FOR_VISION_2_SEQ_MAPPING, + MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, + MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING, + MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, + MODEL_MAPPING, + MODEL_WITH_LM_HEAD_MAPPING, + AutoBackbone, + AutoModel, + AutoModelForAudioClassification, + AutoModelForAudioFrameClassification, + AutoModelForAudioXVector, + AutoModelForCausalLM, + AutoModelForCTC, + AutoModelForDepthEstimation, + AutoModelForDocumentQuestionAnswering, + AutoModelForImageClassification, + AutoModelForImageSegmentation, + AutoModelForImageTextToText, + AutoModelForImageToImage, + AutoModelForInstanceSegmentation, + AutoModelForKeypointDetection, + AutoModelForMaskedImageModeling, + AutoModelForMaskedLM, + AutoModelForMaskGeneration, + AutoModelForMultipleChoice, + AutoModelForNextSentencePrediction, + AutoModelForObjectDetection, + AutoModelForPreTraining, + AutoModelForQuestionAnswering, + AutoModelForSemanticSegmentation, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForSpeechSeq2Seq, + AutoModelForTableQuestionAnswering, + AutoModelForTextEncoding, + AutoModelForTextToSpectrogram, + AutoModelForTextToWaveform, + AutoModelForTokenClassification, + AutoModelForUniversalSegmentation, + AutoModelForVideoClassification, + AutoModelForVision2Seq, + AutoModelForVisualQuestionAnswering, + AutoModelForZeroShotImageClassification, + AutoModelForZeroShotObjectDetection, + AutoModelWithLMHead, + ) + from .models.autoformer import ( + AutoformerForPrediction, + AutoformerModel, + AutoformerPreTrainedModel, + ) + from .models.aya_vision import AyaVisionForConditionalGeneration, AyaVisionPreTrainedModel + from .models.bamba import BambaForCausalLM, BambaModel, BambaPreTrainedModel + from .models.bark import ( + BarkCausalModel, + BarkCoarseModel, + BarkFineModel, + BarkModel, + BarkPreTrainedModel, + BarkSemanticModel, + ) + from .models.bart import ( + BartForCausalLM, + BartForConditionalGeneration, + BartForQuestionAnswering, + BartForSequenceClassification, + BartModel, + BartPreTrainedModel, + BartPretrainedModel, + PretrainedBartModel, + ) + from .models.beit import ( + BeitBackbone, + BeitForImageClassification, + BeitForMaskedImageModeling, + BeitForSemanticSegmentation, + BeitModel, + BeitPreTrainedModel, + ) + from .models.bert import ( + BertForMaskedLM, + BertForMultipleChoice, + BertForNextSentencePrediction, + BertForPreTraining, + BertForQuestionAnswering, + BertForSequenceClassification, + BertForTokenClassification, + BertLMHeadModel, + BertModel, + BertPreTrainedModel, + load_tf_weights_in_bert, + ) + from .models.bert_generation import ( + BertGenerationDecoder, + BertGenerationEncoder, + BertGenerationPreTrainedModel, + load_tf_weights_in_bert_generation, + ) + from .models.big_bird import ( + BigBirdForCausalLM, + BigBirdForMaskedLM, + BigBirdForMultipleChoice, + BigBirdForPreTraining, + BigBirdForQuestionAnswering, + BigBirdForSequenceClassification, + BigBirdForTokenClassification, + BigBirdModel, + BigBirdPreTrainedModel, + load_tf_weights_in_big_bird, + ) + from .models.bigbird_pegasus import ( + BigBirdPegasusForCausalLM, + BigBirdPegasusForConditionalGeneration, + BigBirdPegasusForQuestionAnswering, + BigBirdPegasusForSequenceClassification, + BigBirdPegasusModel, + BigBirdPegasusPreTrainedModel, + ) + from .models.biogpt import ( + BioGptForCausalLM, + BioGptForSequenceClassification, + BioGptForTokenClassification, + BioGptModel, + BioGptPreTrainedModel, + ) + from .models.bit import ( + BitBackbone, + BitForImageClassification, + BitModel, + BitPreTrainedModel, + ) + from .models.blenderbot import ( + BlenderbotForCausalLM, + BlenderbotForConditionalGeneration, + BlenderbotModel, + BlenderbotPreTrainedModel, + ) + from .models.blenderbot_small import ( + BlenderbotSmallForCausalLM, + BlenderbotSmallForConditionalGeneration, + BlenderbotSmallModel, + BlenderbotSmallPreTrainedModel, + ) + from .models.blip import ( + BlipForConditionalGeneration, + BlipForImageTextRetrieval, + BlipForQuestionAnswering, + BlipModel, + BlipPreTrainedModel, + BlipTextModel, + BlipVisionModel, + ) + from .models.blip_2 import ( + Blip2ForConditionalGeneration, + Blip2ForImageTextRetrieval, + Blip2Model, + Blip2PreTrainedModel, + Blip2QFormerModel, + Blip2TextModelWithProjection, + Blip2VisionModel, + Blip2VisionModelWithProjection, + ) + from .models.bloom import ( + BloomForCausalLM, + BloomForQuestionAnswering, + BloomForSequenceClassification, + BloomForTokenClassification, + BloomModel, + BloomPreTrainedModel, + ) + from .models.bridgetower import ( + BridgeTowerForContrastiveLearning, + BridgeTowerForImageAndTextRetrieval, + BridgeTowerForMaskedLM, + BridgeTowerModel, + BridgeTowerPreTrainedModel, + ) + from .models.bros import ( + BrosForTokenClassification, + BrosModel, + BrosPreTrainedModel, + BrosProcessor, + BrosSpadeEEForTokenClassification, + BrosSpadeELForTokenClassification, + ) + from .models.camembert import ( + CamembertForCausalLM, + CamembertForMaskedLM, + CamembertForMultipleChoice, + CamembertForQuestionAnswering, + CamembertForSequenceClassification, + CamembertForTokenClassification, + CamembertModel, + CamembertPreTrainedModel, + ) + from .models.canine import ( + CanineForMultipleChoice, + CanineForQuestionAnswering, + CanineForSequenceClassification, + CanineForTokenClassification, + CanineModel, + CaninePreTrainedModel, + load_tf_weights_in_canine, + ) + from .models.chameleon import ( + ChameleonForConditionalGeneration, + ChameleonModel, + ChameleonPreTrainedModel, + ChameleonProcessor, + ChameleonVQVAE, + ) + from .models.chinese_clip import ( + ChineseCLIPModel, + ChineseCLIPPreTrainedModel, + ChineseCLIPTextModel, + ChineseCLIPVisionModel, + ) + from .models.clap import ( + ClapAudioModel, + ClapAudioModelWithProjection, + ClapFeatureExtractor, + ClapModel, + ClapPreTrainedModel, + ClapTextModel, + ClapTextModelWithProjection, + ) + from .models.clip import ( + CLIPForImageClassification, + CLIPModel, + CLIPPreTrainedModel, + CLIPTextModel, + CLIPTextModelWithProjection, + CLIPVisionModel, + CLIPVisionModelWithProjection, + ) + from .models.clipseg import ( + CLIPSegForImageSegmentation, + CLIPSegModel, + CLIPSegPreTrainedModel, + CLIPSegTextModel, + CLIPSegVisionModel, + ) + from .models.clvp import ( + ClvpDecoder, + ClvpEncoder, + ClvpForCausalLM, + ClvpModel, + ClvpModelForConditionalGeneration, + ClvpPreTrainedModel, + ) + from .models.codegen import ( + CodeGenForCausalLM, + CodeGenModel, + CodeGenPreTrainedModel, + ) + from .models.cohere import ( + CohereForCausalLM, + CohereModel, + CoherePreTrainedModel, + ) + from .models.cohere2 import ( + Cohere2ForCausalLM, + Cohere2Model, + Cohere2PreTrainedModel, + ) + from .models.colpali import ( + ColPaliForRetrieval, + ColPaliPreTrainedModel, + ) + from .models.conditional_detr import ( + ConditionalDetrForObjectDetection, + ConditionalDetrForSegmentation, + ConditionalDetrModel, + ConditionalDetrPreTrainedModel, + ) + from .models.convbert import ( + ConvBertForMaskedLM, + ConvBertForMultipleChoice, + ConvBertForQuestionAnswering, + ConvBertForSequenceClassification, + ConvBertForTokenClassification, + ConvBertModel, + ConvBertPreTrainedModel, + load_tf_weights_in_convbert, + ) + from .models.convnext import ( + ConvNextBackbone, + ConvNextForImageClassification, + ConvNextModel, + ConvNextPreTrainedModel, + ) + from .models.convnextv2 import ( + ConvNextV2Backbone, + ConvNextV2ForImageClassification, + ConvNextV2Model, + ConvNextV2PreTrainedModel, + ) + from .models.cpmant import ( + CpmAntForCausalLM, + CpmAntModel, + CpmAntPreTrainedModel, + ) + from .models.ctrl import ( + CTRLForSequenceClassification, + CTRLLMHeadModel, + CTRLModel, + CTRLPreTrainedModel, + ) + from .models.cvt import ( + CvtForImageClassification, + CvtModel, + CvtPreTrainedModel, + ) + from .models.dab_detr import ( + DabDetrForObjectDetection, + DabDetrModel, + DabDetrPreTrainedModel, + ) + from .models.dac import ( + DacModel, + DacPreTrainedModel, + ) + from .models.data2vec import ( + Data2VecAudioForAudioFrameClassification, + Data2VecAudioForCTC, + Data2VecAudioForSequenceClassification, + Data2VecAudioForXVector, + Data2VecAudioModel, + Data2VecAudioPreTrainedModel, + Data2VecTextForCausalLM, + Data2VecTextForMaskedLM, + Data2VecTextForMultipleChoice, + Data2VecTextForQuestionAnswering, + Data2VecTextForSequenceClassification, + Data2VecTextForTokenClassification, + Data2VecTextModel, + Data2VecTextPreTrainedModel, + Data2VecVisionForImageClassification, + Data2VecVisionForSemanticSegmentation, + Data2VecVisionModel, + Data2VecVisionPreTrainedModel, + ) + + # PyTorch model imports + from .models.dbrx import ( + DbrxForCausalLM, + DbrxModel, + DbrxPreTrainedModel, + ) + from .models.deberta import ( + DebertaForMaskedLM, + DebertaForQuestionAnswering, + DebertaForSequenceClassification, + DebertaForTokenClassification, + DebertaModel, + DebertaPreTrainedModel, + ) + from .models.deberta_v2 import ( + DebertaV2ForMaskedLM, + DebertaV2ForMultipleChoice, + DebertaV2ForQuestionAnswering, + DebertaV2ForSequenceClassification, + DebertaV2ForTokenClassification, + DebertaV2Model, + DebertaV2PreTrainedModel, + ) + from .models.decision_transformer import ( + DecisionTransformerGPT2Model, + DecisionTransformerGPT2PreTrainedModel, + DecisionTransformerModel, + DecisionTransformerPreTrainedModel, + ) + from .models.deformable_detr import ( + DeformableDetrForObjectDetection, + DeformableDetrModel, + DeformableDetrPreTrainedModel, + ) + from .models.deit import ( + DeiTForImageClassification, + DeiTForImageClassificationWithTeacher, + DeiTForMaskedImageModeling, + DeiTModel, + DeiTPreTrainedModel, + ) + from .models.deprecated.deta import ( + DetaForObjectDetection, + DetaModel, + DetaPreTrainedModel, + ) + from .models.deprecated.efficientformer import ( + EfficientFormerForImageClassification, + EfficientFormerForImageClassificationWithTeacher, + EfficientFormerModel, + EfficientFormerPreTrainedModel, + ) + from .models.deprecated.ernie_m import ( + ErnieMForInformationExtraction, + ErnieMForMultipleChoice, + ErnieMForQuestionAnswering, + ErnieMForSequenceClassification, + ErnieMForTokenClassification, + ErnieMModel, + ErnieMPreTrainedModel, + ) + from .models.deprecated.gptsan_japanese import ( + GPTSanJapaneseForConditionalGeneration, + GPTSanJapaneseModel, + GPTSanJapanesePreTrainedModel, + ) + from .models.deprecated.graphormer import ( + GraphormerForGraphClassification, + GraphormerModel, + GraphormerPreTrainedModel, + ) + from .models.deprecated.jukebox import ( + JukeboxModel, + JukeboxPreTrainedModel, + JukeboxPrior, + JukeboxVQVAE, + ) + from .models.deprecated.mctct import ( + MCTCTForCTC, + MCTCTModel, + MCTCTPreTrainedModel, + ) + from .models.deprecated.mega import ( + MegaForCausalLM, + MegaForMaskedLM, + MegaForMultipleChoice, + MegaForQuestionAnswering, + MegaForSequenceClassification, + MegaForTokenClassification, + MegaModel, + MegaPreTrainedModel, + ) + from .models.deprecated.mmbt import ( + MMBTForClassification, + MMBTModel, + ModalEmbeddings, + ) + from .models.deprecated.nat import ( + NatBackbone, + NatForImageClassification, + NatModel, + NatPreTrainedModel, + ) + from .models.deprecated.nezha import ( + NezhaForMaskedLM, + NezhaForMultipleChoice, + NezhaForNextSentencePrediction, + NezhaForPreTraining, + NezhaForQuestionAnswering, + NezhaForSequenceClassification, + NezhaForTokenClassification, + NezhaModel, + NezhaPreTrainedModel, + ) + from .models.deprecated.open_llama import ( + OpenLlamaForCausalLM, + OpenLlamaForSequenceClassification, + OpenLlamaModel, + OpenLlamaPreTrainedModel, + ) + from .models.deprecated.qdqbert import ( + QDQBertForMaskedLM, + QDQBertForMultipleChoice, + QDQBertForNextSentencePrediction, + QDQBertForQuestionAnswering, + QDQBertForSequenceClassification, + QDQBertForTokenClassification, + QDQBertLMHeadModel, + QDQBertModel, + QDQBertPreTrainedModel, + load_tf_weights_in_qdqbert, + ) + from .models.deprecated.realm import ( + RealmEmbedder, + RealmForOpenQA, + RealmKnowledgeAugEncoder, + RealmPreTrainedModel, + RealmReader, + RealmRetriever, + RealmScorer, + load_tf_weights_in_realm, + ) + from .models.deprecated.retribert import ( + RetriBertModel, + RetriBertPreTrainedModel, + ) + from .models.deprecated.speech_to_text_2 import ( + Speech2Text2ForCausalLM, + Speech2Text2PreTrainedModel, + ) + from .models.deprecated.trajectory_transformer import ( + TrajectoryTransformerModel, + TrajectoryTransformerPreTrainedModel, + ) + from .models.deprecated.transfo_xl import ( + AdaptiveEmbedding, + TransfoXLForSequenceClassification, + TransfoXLLMHeadModel, + TransfoXLModel, + TransfoXLPreTrainedModel, + load_tf_weights_in_transfo_xl, + ) + from .models.deprecated.tvlt import ( + TvltForAudioVisualClassification, + TvltForPreTraining, + TvltModel, + TvltPreTrainedModel, + ) + from .models.deprecated.van import ( + VanForImageClassification, + VanModel, + VanPreTrainedModel, + ) + from .models.deprecated.vit_hybrid import ( + ViTHybridForImageClassification, + ViTHybridModel, + ViTHybridPreTrainedModel, + ) + from .models.deprecated.xlm_prophetnet import ( + XLMProphetNetDecoder, + XLMProphetNetEncoder, + XLMProphetNetForCausalLM, + XLMProphetNetForConditionalGeneration, + XLMProphetNetModel, + XLMProphetNetPreTrainedModel, + ) + from .models.depth_anything import ( + DepthAnythingForDepthEstimation, + DepthAnythingPreTrainedModel, + ) + from .models.depth_pro import ( + DepthProForDepthEstimation, + DepthProModel, + DepthProPreTrainedModel, + ) + from .models.detr import ( + DetrForObjectDetection, + DetrForSegmentation, + DetrModel, + DetrPreTrainedModel, + ) + from .models.diffllama import ( + DiffLlamaForCausalLM, + DiffLlamaForQuestionAnswering, + DiffLlamaForSequenceClassification, + DiffLlamaForTokenClassification, + DiffLlamaModel, + DiffLlamaPreTrainedModel, + ) + from .models.dinat import ( + DinatBackbone, + DinatForImageClassification, + DinatModel, + DinatPreTrainedModel, + ) + from .models.dinov2 import ( + Dinov2Backbone, + Dinov2ForImageClassification, + Dinov2Model, + Dinov2PreTrainedModel, + ) + from .models.dinov2_with_registers import ( + Dinov2WithRegistersBackbone, + Dinov2WithRegistersForImageClassification, + Dinov2WithRegistersModel, + Dinov2WithRegistersPreTrainedModel, + ) + from .models.distilbert import ( + DistilBertForMaskedLM, + DistilBertForMultipleChoice, + DistilBertForQuestionAnswering, + DistilBertForSequenceClassification, + DistilBertForTokenClassification, + DistilBertModel, + DistilBertPreTrainedModel, + ) + from .models.donut import ( + DonutSwinModel, + DonutSwinPreTrainedModel, + ) + from .models.dpr import ( + DPRContextEncoder, + DPRPretrainedContextEncoder, + DPRPreTrainedModel, + DPRPretrainedQuestionEncoder, + DPRPretrainedReader, + DPRQuestionEncoder, + DPRReader, + ) + from .models.dpt import ( + DPTForDepthEstimation, + DPTForSemanticSegmentation, + DPTModel, + DPTPreTrainedModel, + ) + from .models.efficientnet import ( + EfficientNetForImageClassification, + EfficientNetModel, + EfficientNetPreTrainedModel, + ) + from .models.electra import ( + ElectraForCausalLM, + ElectraForMaskedLM, + ElectraForMultipleChoice, + ElectraForPreTraining, + ElectraForQuestionAnswering, + ElectraForSequenceClassification, + ElectraForTokenClassification, + ElectraModel, + ElectraPreTrainedModel, + load_tf_weights_in_electra, + ) + from .models.emu3 import ( + Emu3ForCausalLM, + Emu3ForConditionalGeneration, + Emu3PreTrainedModel, + Emu3TextModel, + Emu3VQVAE, + ) + from .models.encodec import ( + EncodecModel, + EncodecPreTrainedModel, + ) + from .models.encoder_decoder import EncoderDecoderModel + from .models.ernie import ( + ErnieForCausalLM, + ErnieForMaskedLM, + ErnieForMultipleChoice, + ErnieForNextSentencePrediction, + ErnieForPreTraining, + ErnieForQuestionAnswering, + ErnieForSequenceClassification, + ErnieForTokenClassification, + ErnieModel, + ErniePreTrainedModel, + ) + from .models.esm import ( + EsmFoldPreTrainedModel, + EsmForMaskedLM, + EsmForProteinFolding, + EsmForSequenceClassification, + EsmForTokenClassification, + EsmModel, + EsmPreTrainedModel, + ) + from .models.falcon import ( + FalconForCausalLM, + FalconForQuestionAnswering, + FalconForSequenceClassification, + FalconForTokenClassification, + FalconModel, + FalconPreTrainedModel, + ) + from .models.falcon_mamba import ( + FalconMambaForCausalLM, + FalconMambaModel, + FalconMambaPreTrainedModel, + ) + from .models.fastspeech2_conformer import ( + FastSpeech2ConformerHifiGan, + FastSpeech2ConformerModel, + FastSpeech2ConformerPreTrainedModel, + FastSpeech2ConformerWithHifiGan, + ) + from .models.flaubert import ( + FlaubertForMultipleChoice, + FlaubertForQuestionAnswering, + FlaubertForQuestionAnsweringSimple, + FlaubertForSequenceClassification, + FlaubertForTokenClassification, + FlaubertModel, + FlaubertPreTrainedModel, + FlaubertWithLMHeadModel, + ) + from .models.flava import ( + FlavaForPreTraining, + FlavaImageCodebook, + FlavaImageModel, + FlavaModel, + FlavaMultimodalModel, + FlavaPreTrainedModel, + FlavaTextModel, + ) + from .models.fnet import ( + FNetForMaskedLM, + FNetForMultipleChoice, + FNetForNextSentencePrediction, + FNetForPreTraining, + FNetForQuestionAnswering, + FNetForSequenceClassification, + FNetForTokenClassification, + FNetModel, + FNetPreTrainedModel, + ) + from .models.focalnet import ( + FocalNetBackbone, + FocalNetForImageClassification, + FocalNetForMaskedImageModeling, + FocalNetModel, + FocalNetPreTrainedModel, + ) + from .models.fsmt import ( + FSMTForConditionalGeneration, + FSMTModel, + PretrainedFSMTModel, + ) + from .models.funnel import ( + FunnelBaseModel, + FunnelForMaskedLM, + FunnelForMultipleChoice, + FunnelForPreTraining, + FunnelForQuestionAnswering, + FunnelForSequenceClassification, + FunnelForTokenClassification, + FunnelModel, + FunnelPreTrainedModel, + load_tf_weights_in_funnel, + ) + from .models.fuyu import ( + FuyuForCausalLM, + FuyuPreTrainedModel, + ) + from .models.gemma import ( + GemmaForCausalLM, + GemmaForSequenceClassification, + GemmaForTokenClassification, + GemmaModel, + GemmaPreTrainedModel, + ) + from .models.gemma2 import ( + Gemma2ForCausalLM, + Gemma2ForSequenceClassification, + Gemma2ForTokenClassification, + Gemma2Model, + Gemma2PreTrainedModel, + ) + from .models.gemma3 import ( + Gemma3ForCausalLM, + Gemma3ForConditionalGeneration, + Gemma3PreTrainedModel, + Gemma3TextModel, + ) + from .models.git import ( + GitForCausalLM, + GitModel, + GitPreTrainedModel, + GitVisionModel, + ) + from .models.glm import ( + GlmForCausalLM, + GlmForSequenceClassification, + GlmForTokenClassification, + GlmModel, + GlmPreTrainedModel, + ) + from .models.glpn import ( + GLPNForDepthEstimation, + GLPNModel, + GLPNPreTrainedModel, + ) + from .models.got_ocr2 import ( + GotOcr2ForConditionalGeneration, + GotOcr2PreTrainedModel, + ) + from .models.gpt2 import ( + GPT2DoubleHeadsModel, + GPT2ForQuestionAnswering, + GPT2ForSequenceClassification, + GPT2ForTokenClassification, + GPT2LMHeadModel, + GPT2Model, + GPT2PreTrainedModel, + load_tf_weights_in_gpt2, + ) + from .models.gpt_bigcode import ( + GPTBigCodeForCausalLM, + GPTBigCodeForSequenceClassification, + GPTBigCodeForTokenClassification, + GPTBigCodeModel, + GPTBigCodePreTrainedModel, + ) + from .models.gpt_neo import ( + GPTNeoForCausalLM, + GPTNeoForQuestionAnswering, + GPTNeoForSequenceClassification, + GPTNeoForTokenClassification, + GPTNeoModel, + GPTNeoPreTrainedModel, + load_tf_weights_in_gpt_neo, + ) + from .models.gpt_neox import ( + GPTNeoXForCausalLM, + GPTNeoXForQuestionAnswering, + GPTNeoXForSequenceClassification, + GPTNeoXForTokenClassification, + GPTNeoXModel, + GPTNeoXPreTrainedModel, + ) + from .models.gpt_neox_japanese import ( + GPTNeoXJapaneseForCausalLM, + GPTNeoXJapaneseModel, + GPTNeoXJapanesePreTrainedModel, + ) + from .models.gptj import ( + GPTJForCausalLM, + GPTJForQuestionAnswering, + GPTJForSequenceClassification, + GPTJModel, + GPTJPreTrainedModel, + ) + from .models.granite import ( + GraniteForCausalLM, + GraniteModel, + GranitePreTrainedModel, + ) + from .models.granitemoe import ( + GraniteMoeForCausalLM, + GraniteMoeModel, + GraniteMoePreTrainedModel, + ) + from .models.granitemoeshared import ( + GraniteMoeSharedForCausalLM, + GraniteMoeSharedModel, + GraniteMoeSharedPreTrainedModel, + ) + from .models.grounding_dino import ( + GroundingDinoForObjectDetection, + GroundingDinoModel, + GroundingDinoPreTrainedModel, + ) + from .models.groupvit import ( + GroupViTModel, + GroupViTPreTrainedModel, + GroupViTTextModel, + GroupViTVisionModel, + ) + from .models.helium import ( + HeliumForCausalLM, + HeliumForSequenceClassification, + HeliumForTokenClassification, + HeliumModel, + HeliumPreTrainedModel, + ) + from .models.hiera import ( + HieraBackbone, + HieraForImageClassification, + HieraForPreTraining, + HieraModel, + HieraPreTrainedModel, + ) + from .models.hubert import ( + HubertForCTC, + HubertForSequenceClassification, + HubertModel, + HubertPreTrainedModel, + ) + from .models.ibert import ( + IBertForMaskedLM, + IBertForMultipleChoice, + IBertForQuestionAnswering, + IBertForSequenceClassification, + IBertForTokenClassification, + IBertModel, + IBertPreTrainedModel, + ) + from .models.idefics import ( + IdeficsForVisionText2Text, + IdeficsModel, + IdeficsPreTrainedModel, + IdeficsProcessor, + ) + from .models.idefics2 import ( + Idefics2ForConditionalGeneration, + Idefics2Model, + Idefics2PreTrainedModel, + Idefics2Processor, + ) + from .models.idefics3 import ( + Idefics3ForConditionalGeneration, + Idefics3Model, + Idefics3PreTrainedModel, + Idefics3Processor, + Idefics3VisionConfig, + Idefics3VisionTransformer, + ) + from .models.ijepa import ( + IJepaForImageClassification, + IJepaModel, + IJepaPreTrainedModel, + ) + from .models.imagegpt import ( + ImageGPTForCausalImageModeling, + ImageGPTForImageClassification, + ImageGPTModel, + ImageGPTPreTrainedModel, + load_tf_weights_in_imagegpt, + ) + from .models.informer import ( + InformerForPrediction, + InformerModel, + InformerPreTrainedModel, + ) + from .models.instructblip import ( + InstructBlipForConditionalGeneration, + InstructBlipPreTrainedModel, + InstructBlipQFormerModel, + InstructBlipVisionModel, + ) + from .models.instructblipvideo import ( + InstructBlipVideoForConditionalGeneration, + InstructBlipVideoPreTrainedModel, + InstructBlipVideoQFormerModel, + InstructBlipVideoVisionModel, + ) + from .models.jamba import ( + JambaForCausalLM, + JambaForSequenceClassification, + JambaModel, + JambaPreTrainedModel, + ) + from .models.jetmoe import ( + JetMoeForCausalLM, + JetMoeForSequenceClassification, + JetMoeModel, + JetMoePreTrainedModel, + ) + from .models.kosmos2 import ( + Kosmos2ForConditionalGeneration, + Kosmos2Model, + Kosmos2PreTrainedModel, + ) + from .models.layoutlm import ( + LayoutLMForMaskedLM, + LayoutLMForQuestionAnswering, + LayoutLMForSequenceClassification, + LayoutLMForTokenClassification, + LayoutLMModel, + LayoutLMPreTrainedModel, + ) + from .models.layoutlmv2 import ( + LayoutLMv2ForQuestionAnswering, + LayoutLMv2ForSequenceClassification, + LayoutLMv2ForTokenClassification, + LayoutLMv2Model, + LayoutLMv2PreTrainedModel, + ) + from .models.layoutlmv3 import ( + LayoutLMv3ForQuestionAnswering, + LayoutLMv3ForSequenceClassification, + LayoutLMv3ForTokenClassification, + LayoutLMv3Model, + LayoutLMv3PreTrainedModel, + ) + from .models.led import ( + LEDForConditionalGeneration, + LEDForQuestionAnswering, + LEDForSequenceClassification, + LEDModel, + LEDPreTrainedModel, + ) + from .models.levit import ( + LevitForImageClassification, + LevitForImageClassificationWithTeacher, + LevitModel, + LevitPreTrainedModel, + ) + from .models.lilt import ( + LiltForQuestionAnswering, + LiltForSequenceClassification, + LiltForTokenClassification, + LiltModel, + LiltPreTrainedModel, + ) + from .models.llama import ( + LlamaForCausalLM, + LlamaForQuestionAnswering, + LlamaForSequenceClassification, + LlamaForTokenClassification, + LlamaModel, + LlamaPreTrainedModel, + ) + from .models.llava import ( + LlavaForConditionalGeneration, + LlavaPreTrainedModel, + ) + from .models.llava_next import ( + LlavaNextForConditionalGeneration, + LlavaNextPreTrainedModel, + ) + from .models.llava_next_video import ( + LlavaNextVideoForConditionalGeneration, + LlavaNextVideoPreTrainedModel, + ) + from .models.llava_onevision import ( + LlavaOnevisionForConditionalGeneration, + LlavaOnevisionPreTrainedModel, + ) + from .models.longformer import ( + LongformerForMaskedLM, + LongformerForMultipleChoice, + LongformerForQuestionAnswering, + LongformerForSequenceClassification, + LongformerForTokenClassification, + LongformerModel, + LongformerPreTrainedModel, + ) + from .models.longt5 import ( + LongT5EncoderModel, + LongT5ForConditionalGeneration, + LongT5Model, + LongT5PreTrainedModel, + ) + from .models.luke import ( + LukeForEntityClassification, + LukeForEntityPairClassification, + LukeForEntitySpanClassification, + LukeForMaskedLM, + LukeForMultipleChoice, + LukeForQuestionAnswering, + LukeForSequenceClassification, + LukeForTokenClassification, + LukeModel, + LukePreTrainedModel, + ) + from .models.lxmert import ( + LxmertEncoder, + LxmertForPreTraining, + LxmertForQuestionAnswering, + LxmertModel, + LxmertPreTrainedModel, + LxmertVisualFeatureEncoder, + ) + from .models.m2m_100 import ( + M2M100ForConditionalGeneration, + M2M100Model, + M2M100PreTrainedModel, + ) + from .models.mamba import ( + MambaForCausalLM, + MambaModel, + MambaPreTrainedModel, + ) + from .models.mamba2 import ( + Mamba2ForCausalLM, + Mamba2Model, + Mamba2PreTrainedModel, + ) + from .models.marian import MarianForCausalLM, MarianModel, MarianMTModel, MarianPreTrainedModel + from .models.markuplm import ( + MarkupLMForQuestionAnswering, + MarkupLMForSequenceClassification, + MarkupLMForTokenClassification, + MarkupLMModel, + MarkupLMPreTrainedModel, + ) + from .models.mask2former import ( + Mask2FormerForUniversalSegmentation, + Mask2FormerModel, + Mask2FormerPreTrainedModel, + ) + from .models.maskformer import ( + MaskFormerForInstanceSegmentation, + MaskFormerModel, + MaskFormerPreTrainedModel, + MaskFormerSwinBackbone, + ) + from .models.mbart import ( + MBartForCausalLM, + MBartForConditionalGeneration, + MBartForQuestionAnswering, + MBartForSequenceClassification, + MBartModel, + MBartPreTrainedModel, + ) + from .models.megatron_bert import ( + MegatronBertForCausalLM, + MegatronBertForMaskedLM, + MegatronBertForMultipleChoice, + MegatronBertForNextSentencePrediction, + MegatronBertForPreTraining, + MegatronBertForQuestionAnswering, + MegatronBertForSequenceClassification, + MegatronBertForTokenClassification, + MegatronBertModel, + MegatronBertPreTrainedModel, + ) + from .models.mgp_str import ( + MgpstrForSceneTextRecognition, + MgpstrModel, + MgpstrPreTrainedModel, + ) + from .models.mimi import ( + MimiModel, + MimiPreTrainedModel, + ) + from .models.mistral import ( + MistralForCausalLM, + MistralForQuestionAnswering, + MistralForSequenceClassification, + MistralForTokenClassification, + MistralModel, + MistralPreTrainedModel, + ) + from .models.mistral3 import ( + Mistral3ForConditionalGeneration, + Mistral3PreTrainedModel, + ) + from .models.mixtral import ( + MixtralForCausalLM, + MixtralForQuestionAnswering, + MixtralForSequenceClassification, + MixtralForTokenClassification, + MixtralModel, + MixtralPreTrainedModel, + ) + from .models.mllama import ( + MllamaForCausalLM, + MllamaForConditionalGeneration, + MllamaPreTrainedModel, + MllamaProcessor, + MllamaTextModel, + MllamaVisionModel, + ) + from .models.mobilebert import ( + MobileBertForMaskedLM, + MobileBertForMultipleChoice, + MobileBertForNextSentencePrediction, + MobileBertForPreTraining, + MobileBertForQuestionAnswering, + MobileBertForSequenceClassification, + MobileBertForTokenClassification, + MobileBertModel, + MobileBertPreTrainedModel, + load_tf_weights_in_mobilebert, + ) + from .models.mobilenet_v1 import ( + MobileNetV1ForImageClassification, + MobileNetV1Model, + MobileNetV1PreTrainedModel, + load_tf_weights_in_mobilenet_v1, + ) + from .models.mobilenet_v2 import ( + MobileNetV2ForImageClassification, + MobileNetV2ForSemanticSegmentation, + MobileNetV2Model, + MobileNetV2PreTrainedModel, + load_tf_weights_in_mobilenet_v2, + ) + from .models.mobilevit import ( + MobileViTForImageClassification, + MobileViTForSemanticSegmentation, + MobileViTModel, + MobileViTPreTrainedModel, + ) + from .models.mobilevitv2 import ( + MobileViTV2ForImageClassification, + MobileViTV2ForSemanticSegmentation, + MobileViTV2Model, + MobileViTV2PreTrainedModel, + ) + from .models.modernbert import ( + ModernBertForMaskedLM, + ModernBertForSequenceClassification, + ModernBertForTokenClassification, + ModernBertModel, + ModernBertPreTrainedModel, + ) + from .models.moonshine import ( + MoonshineForConditionalGeneration, + MoonshineModel, + MoonshinePreTrainedModel, + ) + from .models.moshi import ( + MoshiForCausalLM, + MoshiForConditionalGeneration, + MoshiModel, + MoshiPreTrainedModel, + ) + from .models.mpnet import ( + MPNetForMaskedLM, + MPNetForMultipleChoice, + MPNetForQuestionAnswering, + MPNetForSequenceClassification, + MPNetForTokenClassification, + MPNetModel, + MPNetPreTrainedModel, + ) + from .models.mpt import ( + MptForCausalLM, + MptForQuestionAnswering, + MptForSequenceClassification, + MptForTokenClassification, + MptModel, + MptPreTrainedModel, + ) + from .models.mra import ( + MraForMaskedLM, + MraForMultipleChoice, + MraForQuestionAnswering, + MraForSequenceClassification, + MraForTokenClassification, + MraModel, + MraPreTrainedModel, + ) + from .models.mt5 import ( + MT5EncoderModel, + MT5ForConditionalGeneration, + MT5ForQuestionAnswering, + MT5ForSequenceClassification, + MT5ForTokenClassification, + MT5Model, + MT5PreTrainedModel, + ) + from .models.musicgen import ( + MusicgenForCausalLM, + MusicgenForConditionalGeneration, + MusicgenModel, + MusicgenPreTrainedModel, + MusicgenProcessor, + ) + from .models.musicgen_melody import ( + MusicgenMelodyForCausalLM, + MusicgenMelodyForConditionalGeneration, + MusicgenMelodyModel, + MusicgenMelodyPreTrainedModel, + ) + from .models.mvp import ( + MvpForCausalLM, + MvpForConditionalGeneration, + MvpForQuestionAnswering, + MvpForSequenceClassification, + MvpModel, + MvpPreTrainedModel, + ) + from .models.nemotron import ( + NemotronForCausalLM, + NemotronForQuestionAnswering, + NemotronForSequenceClassification, + NemotronForTokenClassification, + NemotronModel, + NemotronPreTrainedModel, + ) + from .models.nllb_moe import ( + NllbMoeForConditionalGeneration, + NllbMoeModel, + NllbMoePreTrainedModel, + NllbMoeSparseMLP, + NllbMoeTop2Router, + ) + from .models.nystromformer import ( + NystromformerForMaskedLM, + NystromformerForMultipleChoice, + NystromformerForQuestionAnswering, + NystromformerForSequenceClassification, + NystromformerForTokenClassification, + NystromformerModel, + NystromformerPreTrainedModel, + ) + from .models.olmo import ( + OlmoForCausalLM, + OlmoModel, + OlmoPreTrainedModel, + ) + from .models.olmo2 import ( + Olmo2ForCausalLM, + Olmo2Model, + Olmo2PreTrainedModel, + ) + from .models.olmoe import ( + OlmoeForCausalLM, + OlmoeModel, + OlmoePreTrainedModel, + ) + from .models.omdet_turbo import ( + OmDetTurboForObjectDetection, + OmDetTurboPreTrainedModel, + ) + from .models.oneformer import ( + OneFormerForUniversalSegmentation, + OneFormerModel, + OneFormerPreTrainedModel, + ) + from .models.openai import ( + OpenAIGPTDoubleHeadsModel, + OpenAIGPTForSequenceClassification, + OpenAIGPTLMHeadModel, + OpenAIGPTModel, + OpenAIGPTPreTrainedModel, + load_tf_weights_in_openai_gpt, + ) + from .models.opt import ( + OPTForCausalLM, + OPTForQuestionAnswering, + OPTForSequenceClassification, + OPTModel, + OPTPreTrainedModel, + ) + from .models.owlv2 import ( + Owlv2ForObjectDetection, + Owlv2Model, + Owlv2PreTrainedModel, + Owlv2TextModel, + Owlv2VisionModel, + ) + from .models.owlvit import ( + OwlViTForObjectDetection, + OwlViTModel, + OwlViTPreTrainedModel, + OwlViTTextModel, + OwlViTVisionModel, + ) + from .models.paligemma import ( + PaliGemmaForConditionalGeneration, + PaliGemmaPreTrainedModel, + PaliGemmaProcessor, + ) + from .models.patchtsmixer import ( + PatchTSMixerForPrediction, + PatchTSMixerForPretraining, + PatchTSMixerForRegression, + PatchTSMixerForTimeSeriesClassification, + PatchTSMixerModel, + PatchTSMixerPreTrainedModel, + ) + from .models.patchtst import ( + PatchTSTForClassification, + PatchTSTForPrediction, + PatchTSTForPretraining, + PatchTSTForRegression, + PatchTSTModel, + PatchTSTPreTrainedModel, + ) + from .models.pegasus import ( + PegasusForCausalLM, + PegasusForConditionalGeneration, + PegasusModel, + PegasusPreTrainedModel, + ) + from .models.pegasus_x import ( + PegasusXForConditionalGeneration, + PegasusXModel, + PegasusXPreTrainedModel, + ) + from .models.perceiver import ( + PerceiverForImageClassificationConvProcessing, + PerceiverForImageClassificationFourier, + PerceiverForImageClassificationLearned, + PerceiverForMaskedLM, + PerceiverForMultimodalAutoencoding, + PerceiverForOpticalFlow, + PerceiverForSequenceClassification, + PerceiverModel, + PerceiverPreTrainedModel, + ) + from .models.persimmon import ( + PersimmonForCausalLM, + PersimmonForSequenceClassification, + PersimmonForTokenClassification, + PersimmonModel, + PersimmonPreTrainedModel, + ) + from .models.phi import ( + PhiForCausalLM, + PhiForSequenceClassification, + PhiForTokenClassification, + PhiModel, + PhiPreTrainedModel, + ) + from .models.phi3 import ( + Phi3ForCausalLM, + Phi3ForSequenceClassification, + Phi3ForTokenClassification, + Phi3Model, + Phi3PreTrainedModel, + ) + from .models.phimoe import ( + PhimoeForCausalLM, + PhimoeForSequenceClassification, + PhimoeModel, + PhimoePreTrainedModel, + ) + from .models.pix2struct import ( + Pix2StructForConditionalGeneration, + Pix2StructPreTrainedModel, + Pix2StructTextModel, + Pix2StructVisionModel, + ) + from .models.pixtral import ( + PixtralPreTrainedModel, + PixtralVisionModel, + ) + from .models.plbart import ( + PLBartForCausalLM, + PLBartForConditionalGeneration, + PLBartForSequenceClassification, + PLBartModel, + PLBartPreTrainedModel, + ) + from .models.poolformer import ( + PoolFormerForImageClassification, + PoolFormerModel, + PoolFormerPreTrainedModel, + ) + from .models.pop2piano import ( + Pop2PianoForConditionalGeneration, + Pop2PianoPreTrainedModel, + ) + from .models.prophetnet import ( + ProphetNetDecoder, + ProphetNetEncoder, + ProphetNetForCausalLM, + ProphetNetForConditionalGeneration, + ProphetNetModel, + ProphetNetPreTrainedModel, + ) + from .models.pvt import ( + PvtForImageClassification, + PvtModel, + PvtPreTrainedModel, + ) + from .models.pvt_v2 import ( + PvtV2Backbone, + PvtV2ForImageClassification, + PvtV2Model, + PvtV2PreTrainedModel, + ) + from .models.qwen2 import ( + Qwen2ForCausalLM, + Qwen2ForQuestionAnswering, + Qwen2ForSequenceClassification, + Qwen2ForTokenClassification, + Qwen2Model, + Qwen2PreTrainedModel, + ) + from .models.qwen2_5_vl import ( + Qwen2_5_VLForConditionalGeneration, + Qwen2_5_VLModel, + Qwen2_5_VLPreTrainedModel, + ) + from .models.qwen2_audio import ( + Qwen2AudioEncoder, + Qwen2AudioForConditionalGeneration, + Qwen2AudioPreTrainedModel, + ) + from .models.qwen2_moe import ( + Qwen2MoeForCausalLM, + Qwen2MoeForQuestionAnswering, + Qwen2MoeForSequenceClassification, + Qwen2MoeForTokenClassification, + Qwen2MoeModel, + Qwen2MoePreTrainedModel, + ) + from .models.qwen2_vl import ( + Qwen2VLForConditionalGeneration, + Qwen2VLModel, + Qwen2VLPreTrainedModel, + ) + from .models.rag import ( + RagModel, + RagPreTrainedModel, + RagSequenceForGeneration, + RagTokenForGeneration, + ) + from .models.recurrent_gemma import ( + RecurrentGemmaForCausalLM, + RecurrentGemmaModel, + RecurrentGemmaPreTrainedModel, + ) + from .models.reformer import ( + ReformerForMaskedLM, + ReformerForQuestionAnswering, + ReformerForSequenceClassification, + ReformerModel, + ReformerModelWithLMHead, + ReformerPreTrainedModel, + ) + from .models.regnet import ( + RegNetForImageClassification, + RegNetModel, + RegNetPreTrainedModel, + ) + from .models.rembert import ( + RemBertForCausalLM, + RemBertForMaskedLM, + RemBertForMultipleChoice, + RemBertForQuestionAnswering, + RemBertForSequenceClassification, + RemBertForTokenClassification, + RemBertModel, + RemBertPreTrainedModel, + load_tf_weights_in_rembert, + ) + from .models.resnet import ( + ResNetBackbone, + ResNetForImageClassification, + ResNetModel, + ResNetPreTrainedModel, + ) + from .models.roberta import ( + RobertaForCausalLM, + RobertaForMaskedLM, + RobertaForMultipleChoice, + RobertaForQuestionAnswering, + RobertaForSequenceClassification, + RobertaForTokenClassification, + RobertaModel, + RobertaPreTrainedModel, + ) + from .models.roberta_prelayernorm import ( + RobertaPreLayerNormForCausalLM, + RobertaPreLayerNormForMaskedLM, + RobertaPreLayerNormForMultipleChoice, + RobertaPreLayerNormForQuestionAnswering, + RobertaPreLayerNormForSequenceClassification, + RobertaPreLayerNormForTokenClassification, + RobertaPreLayerNormModel, + RobertaPreLayerNormPreTrainedModel, + ) + from .models.roc_bert import ( + RoCBertForCausalLM, + RoCBertForMaskedLM, + RoCBertForMultipleChoice, + RoCBertForPreTraining, + RoCBertForQuestionAnswering, + RoCBertForSequenceClassification, + RoCBertForTokenClassification, + RoCBertModel, + RoCBertPreTrainedModel, + load_tf_weights_in_roc_bert, + ) + from .models.roformer import ( + RoFormerForCausalLM, + RoFormerForMaskedLM, + RoFormerForMultipleChoice, + RoFormerForQuestionAnswering, + RoFormerForSequenceClassification, + RoFormerForTokenClassification, + RoFormerModel, + RoFormerPreTrainedModel, + load_tf_weights_in_roformer, + ) + from .models.rt_detr import ( + RTDetrForObjectDetection, + RTDetrModel, + RTDetrPreTrainedModel, + RTDetrResNetBackbone, + RTDetrResNetPreTrainedModel, + ) + from .models.rt_detr_v2 import RTDetrV2ForObjectDetection, RTDetrV2Model, RTDetrV2PreTrainedModel + from .models.rwkv import ( + RwkvForCausalLM, + RwkvModel, + RwkvPreTrainedModel, + ) + from .models.sam import ( + SamModel, + SamPreTrainedModel, + ) + from .models.seamless_m4t import ( + SeamlessM4TCodeHifiGan, + SeamlessM4TForSpeechToSpeech, + SeamlessM4TForSpeechToText, + SeamlessM4TForTextToSpeech, + SeamlessM4TForTextToText, + SeamlessM4THifiGan, + SeamlessM4TModel, + SeamlessM4TPreTrainedModel, + SeamlessM4TTextToUnitForConditionalGeneration, + SeamlessM4TTextToUnitModel, + ) + from .models.seamless_m4t_v2 import ( + SeamlessM4Tv2ForSpeechToSpeech, + SeamlessM4Tv2ForSpeechToText, + SeamlessM4Tv2ForTextToSpeech, + SeamlessM4Tv2ForTextToText, + SeamlessM4Tv2Model, + SeamlessM4Tv2PreTrainedModel, + ) + from .models.segformer import ( + SegformerDecodeHead, + SegformerForImageClassification, + SegformerForSemanticSegmentation, + SegformerModel, + SegformerPreTrainedModel, + ) + from .models.seggpt import ( + SegGptForImageSegmentation, + SegGptModel, + SegGptPreTrainedModel, + ) + from .models.sew import ( + SEWForCTC, + SEWForSequenceClassification, + SEWModel, + SEWPreTrainedModel, + ) + from .models.sew_d import ( + SEWDForCTC, + SEWDForSequenceClassification, + SEWDModel, + SEWDPreTrainedModel, + ) + from .models.siglip import ( + SiglipForImageClassification, + SiglipModel, + SiglipPreTrainedModel, + SiglipTextModel, + SiglipVisionModel, + ) + from .models.siglip2 import ( + Siglip2ForImageClassification, + Siglip2Model, + Siglip2PreTrainedModel, + Siglip2TextModel, + Siglip2VisionModel, + ) + from .models.smolvlm import ( + SmolVLMForConditionalGeneration, + SmolVLMModel, + SmolVLMPreTrainedModel, + SmolVLMProcessor, + SmolVLMVisionConfig, + SmolVLMVisionTransformer, + ) + from .models.speech_encoder_decoder import SpeechEncoderDecoderModel + from .models.speech_to_text import ( + Speech2TextForConditionalGeneration, + Speech2TextModel, + Speech2TextPreTrainedModel, + ) + from .models.speecht5 import ( + SpeechT5ForSpeechToSpeech, + SpeechT5ForSpeechToText, + SpeechT5ForTextToSpeech, + SpeechT5HifiGan, + SpeechT5Model, + SpeechT5PreTrainedModel, + ) + from .models.splinter import ( + SplinterForPreTraining, + SplinterForQuestionAnswering, + SplinterModel, + SplinterPreTrainedModel, + ) + from .models.squeezebert import ( + SqueezeBertForMaskedLM, + SqueezeBertForMultipleChoice, + SqueezeBertForQuestionAnswering, + SqueezeBertForSequenceClassification, + SqueezeBertForTokenClassification, + SqueezeBertModel, + SqueezeBertPreTrainedModel, + ) + from .models.stablelm import ( + StableLmForCausalLM, + StableLmForSequenceClassification, + StableLmForTokenClassification, + StableLmModel, + StableLmPreTrainedModel, + ) + from .models.starcoder2 import ( + Starcoder2ForCausalLM, + Starcoder2ForSequenceClassification, + Starcoder2ForTokenClassification, + Starcoder2Model, + Starcoder2PreTrainedModel, + ) + from .models.superglue import ( + SuperGlueForKeypointMatching, + SuperGluePreTrainedModel, + ) + from .models.superpoint import ( + SuperPointForKeypointDetection, + SuperPointPreTrainedModel, + ) + from .models.swiftformer import ( + SwiftFormerForImageClassification, + SwiftFormerModel, + SwiftFormerPreTrainedModel, + ) + from .models.swin import ( + SwinBackbone, + SwinForImageClassification, + SwinForMaskedImageModeling, + SwinModel, + SwinPreTrainedModel, + ) + from .models.swin2sr import ( + Swin2SRForImageSuperResolution, + Swin2SRModel, + Swin2SRPreTrainedModel, + ) + from .models.swinv2 import ( + Swinv2Backbone, + Swinv2ForImageClassification, + Swinv2ForMaskedImageModeling, + Swinv2Model, + Swinv2PreTrainedModel, + ) + from .models.switch_transformers import ( + SwitchTransformersEncoderModel, + SwitchTransformersForConditionalGeneration, + SwitchTransformersModel, + SwitchTransformersPreTrainedModel, + SwitchTransformersSparseMLP, + SwitchTransformersTop1Router, + ) + from .models.t5 import ( + T5EncoderModel, + T5ForConditionalGeneration, + T5ForQuestionAnswering, + T5ForSequenceClassification, + T5ForTokenClassification, + T5Model, + T5PreTrainedModel, + load_tf_weights_in_t5, + ) + from .models.table_transformer import ( + TableTransformerForObjectDetection, + TableTransformerModel, + TableTransformerPreTrainedModel, + ) + from .models.tapas import ( + TapasForMaskedLM, + TapasForQuestionAnswering, + TapasForSequenceClassification, + TapasModel, + TapasPreTrainedModel, + load_tf_weights_in_tapas, + ) + from .models.textnet import ( + TextNetBackbone, + TextNetForImageClassification, + TextNetModel, + TextNetPreTrainedModel, + ) + from .models.time_series_transformer import ( + TimeSeriesTransformerForPrediction, + TimeSeriesTransformerModel, + TimeSeriesTransformerPreTrainedModel, + ) + from .models.timesformer import ( + TimesformerForVideoClassification, + TimesformerModel, + TimesformerPreTrainedModel, + ) + from .models.timm_backbone import TimmBackbone + from .models.timm_wrapper import ( + TimmWrapperForImageClassification, + TimmWrapperModel, + TimmWrapperPreTrainedModel, + ) + from .models.trocr import ( + TrOCRForCausalLM, + TrOCRPreTrainedModel, + ) + from .models.tvp import ( + TvpForVideoGrounding, + TvpModel, + TvpPreTrainedModel, + ) + from .models.udop import ( + UdopEncoderModel, + UdopForConditionalGeneration, + UdopModel, + UdopPreTrainedModel, + ) + from .models.umt5 import ( + UMT5EncoderModel, + UMT5ForConditionalGeneration, + UMT5ForQuestionAnswering, + UMT5ForSequenceClassification, + UMT5ForTokenClassification, + UMT5Model, + UMT5PreTrainedModel, + ) + from .models.unispeech import ( + UniSpeechForCTC, + UniSpeechForPreTraining, + UniSpeechForSequenceClassification, + UniSpeechModel, + UniSpeechPreTrainedModel, + ) + from .models.unispeech_sat import ( + UniSpeechSatForAudioFrameClassification, + UniSpeechSatForCTC, + UniSpeechSatForPreTraining, + UniSpeechSatForSequenceClassification, + UniSpeechSatForXVector, + UniSpeechSatModel, + UniSpeechSatPreTrainedModel, + ) + from .models.univnet import UnivNetModel + from .models.upernet import ( + UperNetForSemanticSegmentation, + UperNetPreTrainedModel, + ) + from .models.video_llava import ( + VideoLlavaForConditionalGeneration, + VideoLlavaPreTrainedModel, + VideoLlavaProcessor, + ) + from .models.videomae import ( + VideoMAEForPreTraining, + VideoMAEForVideoClassification, + VideoMAEModel, + VideoMAEPreTrainedModel, + ) + from .models.vilt import ( + ViltForImageAndTextRetrieval, + ViltForImagesAndTextClassification, + ViltForMaskedLM, + ViltForQuestionAnswering, + ViltForTokenClassification, + ViltModel, + ViltPreTrainedModel, + ) + from .models.vipllava import ( + VipLlavaForConditionalGeneration, + VipLlavaPreTrainedModel, + ) + from .models.vision_encoder_decoder import VisionEncoderDecoderModel + from .models.vision_text_dual_encoder import VisionTextDualEncoderModel + from .models.visual_bert import ( + VisualBertForMultipleChoice, + VisualBertForPreTraining, + VisualBertForQuestionAnswering, + VisualBertForRegionToPhraseAlignment, + VisualBertForVisualReasoning, + VisualBertModel, + VisualBertPreTrainedModel, + ) + from .models.vit import ( + ViTForImageClassification, + ViTForMaskedImageModeling, + ViTModel, + ViTPreTrainedModel, + ) + from .models.vit_mae import ( + ViTMAEForPreTraining, + ViTMAEModel, + ViTMAEPreTrainedModel, + ) + from .models.vit_msn import ( + ViTMSNForImageClassification, + ViTMSNModel, + ViTMSNPreTrainedModel, + ) + from .models.vitdet import ( + VitDetBackbone, + VitDetModel, + VitDetPreTrainedModel, + ) + from .models.vitmatte import ( + VitMatteForImageMatting, + VitMattePreTrainedModel, + ) + from .models.vitpose import ( + VitPoseForPoseEstimation, + VitPosePreTrainedModel, + ) + from .models.vitpose_backbone import VitPoseBackbone, VitPoseBackbonePreTrainedModel + from .models.vits import ( + VitsModel, + VitsPreTrainedModel, + ) + from .models.vivit import ( + VivitForVideoClassification, + VivitModel, + VivitPreTrainedModel, + ) + from .models.wav2vec2 import ( + Wav2Vec2ForAudioFrameClassification, + Wav2Vec2ForCTC, + Wav2Vec2ForMaskedLM, + Wav2Vec2ForPreTraining, + Wav2Vec2ForSequenceClassification, + Wav2Vec2ForXVector, + Wav2Vec2Model, + Wav2Vec2PreTrainedModel, + ) + from .models.wav2vec2_bert import ( + Wav2Vec2BertForAudioFrameClassification, + Wav2Vec2BertForCTC, + Wav2Vec2BertForSequenceClassification, + Wav2Vec2BertForXVector, + Wav2Vec2BertModel, + Wav2Vec2BertPreTrainedModel, + ) + from .models.wav2vec2_conformer import ( + Wav2Vec2ConformerForAudioFrameClassification, + Wav2Vec2ConformerForCTC, + Wav2Vec2ConformerForPreTraining, + Wav2Vec2ConformerForSequenceClassification, + Wav2Vec2ConformerForXVector, + Wav2Vec2ConformerModel, + Wav2Vec2ConformerPreTrainedModel, + ) + from .models.wavlm import ( + WavLMForAudioFrameClassification, + WavLMForCTC, + WavLMForSequenceClassification, + WavLMForXVector, + WavLMModel, + WavLMPreTrainedModel, + ) + from .models.whisper import ( + WhisperForAudioClassification, + WhisperForCausalLM, + WhisperForConditionalGeneration, + WhisperModel, + WhisperPreTrainedModel, + ) + from .models.x_clip import ( + XCLIPModel, + XCLIPPreTrainedModel, + XCLIPTextModel, + XCLIPVisionModel, + ) + from .models.xglm import ( + XGLMForCausalLM, + XGLMModel, + XGLMPreTrainedModel, + ) + from .models.xlm import ( + XLMForMultipleChoice, + XLMForQuestionAnswering, + XLMForQuestionAnsweringSimple, + XLMForSequenceClassification, + XLMForTokenClassification, + XLMModel, + XLMPreTrainedModel, + XLMWithLMHeadModel, + ) + from .models.xlm_roberta import ( + XLMRobertaForCausalLM, + XLMRobertaForMaskedLM, + XLMRobertaForMultipleChoice, + XLMRobertaForQuestionAnswering, + XLMRobertaForSequenceClassification, + XLMRobertaForTokenClassification, + XLMRobertaModel, + XLMRobertaPreTrainedModel, + ) + from .models.xlm_roberta_xl import ( + XLMRobertaXLForCausalLM, + XLMRobertaXLForMaskedLM, + XLMRobertaXLForMultipleChoice, + XLMRobertaXLForQuestionAnswering, + XLMRobertaXLForSequenceClassification, + XLMRobertaXLForTokenClassification, + XLMRobertaXLModel, + XLMRobertaXLPreTrainedModel, + ) + from .models.xlnet import ( + XLNetForMultipleChoice, + XLNetForQuestionAnswering, + XLNetForQuestionAnsweringSimple, + XLNetForSequenceClassification, + XLNetForTokenClassification, + XLNetLMHeadModel, + XLNetModel, + XLNetPreTrainedModel, + load_tf_weights_in_xlnet, + ) + from .models.xmod import ( + XmodForCausalLM, + XmodForMaskedLM, + XmodForMultipleChoice, + XmodForQuestionAnswering, + XmodForSequenceClassification, + XmodForTokenClassification, + XmodModel, + XmodPreTrainedModel, + ) + from .models.yolos import ( + YolosForObjectDetection, + YolosModel, + YolosPreTrainedModel, + ) + from .models.yoso import ( + YosoForMaskedLM, + YosoForMultipleChoice, + YosoForQuestionAnswering, + YosoForSequenceClassification, + YosoForTokenClassification, + YosoModel, + YosoPreTrainedModel, + ) + from .models.zamba import ( + ZambaForCausalLM, + ZambaForSequenceClassification, + ZambaModel, + ZambaPreTrainedModel, + ) + from .models.zamba2 import ( + Zamba2ForCausalLM, + Zamba2ForSequenceClassification, + Zamba2Model, + Zamba2PreTrainedModel, + ) + from .models.zoedepth import ( + ZoeDepthForDepthEstimation, + ZoeDepthPreTrainedModel, + ) + + # Optimization + from .optimization import ( + Adafactor, + AdamW, + get_constant_schedule, + get_constant_schedule_with_warmup, + get_cosine_schedule_with_warmup, + get_cosine_with_hard_restarts_schedule_with_warmup, + get_inverse_sqrt_schedule, + get_linear_schedule_with_warmup, + get_polynomial_decay_schedule_with_warmup, + get_scheduler, + get_wsd_schedule, + ) + from .pytorch_utils import Conv1D, apply_chunking_to_forward, prune_layer + + # Trainer + from .trainer import Trainer + from .trainer_pt_utils import torch_distributed_zero_first + from .trainer_seq2seq import Seq2SeqTrainer + + # TensorFlow + try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + # Import the same objects as dummies to get them in the namespace. + # They will raise an import error if the user tries to instantiate / use them. + from .utils.dummy_tf_objects import * + else: + from .generation import ( + TFForcedBOSTokenLogitsProcessor, + TFForcedEOSTokenLogitsProcessor, + TFForceTokensLogitsProcessor, + TFGenerationMixin, + TFLogitsProcessor, + TFLogitsProcessorList, + TFLogitsWarper, + TFMinLengthLogitsProcessor, + TFNoBadWordsLogitsProcessor, + TFNoRepeatNGramLogitsProcessor, + TFRepetitionPenaltyLogitsProcessor, + TFSuppressTokensAtBeginLogitsProcessor, + TFSuppressTokensLogitsProcessor, + TFTemperatureLogitsWarper, + TFTopKLogitsWarper, + TFTopPLogitsWarper, + ) + from .keras_callbacks import KerasMetricCallback, PushToHubCallback + from .modeling_tf_utils import ( + TFPreTrainedModel, + TFSequenceSummary, + TFSharedEmbeddings, + shape_list, + ) + + # TensorFlow model imports + from .models.albert import ( + TFAlbertForMaskedLM, + TFAlbertForMultipleChoice, + TFAlbertForPreTraining, + TFAlbertForQuestionAnswering, + TFAlbertForSequenceClassification, + TFAlbertForTokenClassification, + TFAlbertMainLayer, + TFAlbertModel, + TFAlbertPreTrainedModel, + ) + from .models.auto import ( + TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_MASK_GENERATION_MAPPING, + TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, + TF_MODEL_FOR_MASKED_LM_MAPPING, + TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + TF_MODEL_FOR_PRETRAINING_MAPPING, + TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, + TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_TEXT_ENCODING_MAPPING, + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_VISION_2_SEQ_MAPPING, + TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING, + TF_MODEL_MAPPING, + TF_MODEL_WITH_LM_HEAD_MAPPING, + TFAutoModel, + TFAutoModelForAudioClassification, + TFAutoModelForCausalLM, + TFAutoModelForDocumentQuestionAnswering, + TFAutoModelForImageClassification, + TFAutoModelForMaskedImageModeling, + TFAutoModelForMaskedLM, + TFAutoModelForMaskGeneration, + TFAutoModelForMultipleChoice, + TFAutoModelForNextSentencePrediction, + TFAutoModelForPreTraining, + TFAutoModelForQuestionAnswering, + TFAutoModelForSemanticSegmentation, + TFAutoModelForSeq2SeqLM, + TFAutoModelForSequenceClassification, + TFAutoModelForSpeechSeq2Seq, + TFAutoModelForTableQuestionAnswering, + TFAutoModelForTextEncoding, + TFAutoModelForTokenClassification, + TFAutoModelForVision2Seq, + TFAutoModelForZeroShotImageClassification, + TFAutoModelWithLMHead, + ) + from .models.bart import ( + TFBartForConditionalGeneration, + TFBartForSequenceClassification, + TFBartModel, + TFBartPretrainedModel, + ) + from .models.bert import ( + TFBertForMaskedLM, + TFBertForMultipleChoice, + TFBertForNextSentencePrediction, + TFBertForPreTraining, + TFBertForQuestionAnswering, + TFBertForSequenceClassification, + TFBertForTokenClassification, + TFBertLMHeadModel, + TFBertMainLayer, + TFBertModel, + TFBertPreTrainedModel, + ) + from .models.blenderbot import ( + TFBlenderbotForConditionalGeneration, + TFBlenderbotModel, + TFBlenderbotPreTrainedModel, + ) + from .models.blenderbot_small import ( + TFBlenderbotSmallForConditionalGeneration, + TFBlenderbotSmallModel, + TFBlenderbotSmallPreTrainedModel, + ) + from .models.blip import ( + TFBlipForConditionalGeneration, + TFBlipForImageTextRetrieval, + TFBlipForQuestionAnswering, + TFBlipModel, + TFBlipPreTrainedModel, + TFBlipTextModel, + TFBlipVisionModel, + ) + from .models.camembert import ( + TFCamembertForCausalLM, + TFCamembertForMaskedLM, + TFCamembertForMultipleChoice, + TFCamembertForQuestionAnswering, + TFCamembertForSequenceClassification, + TFCamembertForTokenClassification, + TFCamembertModel, + TFCamembertPreTrainedModel, + ) + from .models.clip import ( + TFCLIPModel, + TFCLIPPreTrainedModel, + TFCLIPTextModel, + TFCLIPVisionModel, + ) + from .models.convbert import ( + TFConvBertForMaskedLM, + TFConvBertForMultipleChoice, + TFConvBertForQuestionAnswering, + TFConvBertForSequenceClassification, + TFConvBertForTokenClassification, + TFConvBertModel, + TFConvBertPreTrainedModel, + ) + from .models.convnext import ( + TFConvNextForImageClassification, + TFConvNextModel, + TFConvNextPreTrainedModel, + ) + from .models.convnextv2 import ( + TFConvNextV2ForImageClassification, + TFConvNextV2Model, + TFConvNextV2PreTrainedModel, + ) + from .models.ctrl import ( + TFCTRLForSequenceClassification, + TFCTRLLMHeadModel, + TFCTRLModel, + TFCTRLPreTrainedModel, + ) + from .models.cvt import ( + TFCvtForImageClassification, + TFCvtModel, + TFCvtPreTrainedModel, + ) + from .models.data2vec import ( + TFData2VecVisionForImageClassification, + TFData2VecVisionForSemanticSegmentation, + TFData2VecVisionModel, + TFData2VecVisionPreTrainedModel, + ) + from .models.deberta import ( + TFDebertaForMaskedLM, + TFDebertaForQuestionAnswering, + TFDebertaForSequenceClassification, + TFDebertaForTokenClassification, + TFDebertaModel, + TFDebertaPreTrainedModel, + ) + from .models.deberta_v2 import ( + TFDebertaV2ForMaskedLM, + TFDebertaV2ForMultipleChoice, + TFDebertaV2ForQuestionAnswering, + TFDebertaV2ForSequenceClassification, + TFDebertaV2ForTokenClassification, + TFDebertaV2Model, + TFDebertaV2PreTrainedModel, + ) + from .models.deit import ( + TFDeiTForImageClassification, + TFDeiTForImageClassificationWithTeacher, + TFDeiTForMaskedImageModeling, + TFDeiTModel, + TFDeiTPreTrainedModel, + ) + from .models.deprecated.efficientformer import ( + TFEfficientFormerForImageClassification, + TFEfficientFormerForImageClassificationWithTeacher, + TFEfficientFormerModel, + TFEfficientFormerPreTrainedModel, + ) + from .models.deprecated.transfo_xl import ( + TFAdaptiveEmbedding, + TFTransfoXLForSequenceClassification, + TFTransfoXLLMHeadModel, + TFTransfoXLMainLayer, + TFTransfoXLModel, + TFTransfoXLPreTrainedModel, + ) + from .models.distilbert import ( + TFDistilBertForMaskedLM, + TFDistilBertForMultipleChoice, + TFDistilBertForQuestionAnswering, + TFDistilBertForSequenceClassification, + TFDistilBertForTokenClassification, + TFDistilBertMainLayer, + TFDistilBertModel, + TFDistilBertPreTrainedModel, + ) + from .models.dpr import ( + TFDPRContextEncoder, + TFDPRPretrainedContextEncoder, + TFDPRPretrainedQuestionEncoder, + TFDPRPretrainedReader, + TFDPRQuestionEncoder, + TFDPRReader, + ) + from .models.electra import ( + TFElectraForMaskedLM, + TFElectraForMultipleChoice, + TFElectraForPreTraining, + TFElectraForQuestionAnswering, + TFElectraForSequenceClassification, + TFElectraForTokenClassification, + TFElectraModel, + TFElectraPreTrainedModel, + ) + from .models.encoder_decoder import TFEncoderDecoderModel + from .models.esm import ( + TFEsmForMaskedLM, + TFEsmForSequenceClassification, + TFEsmForTokenClassification, + TFEsmModel, + TFEsmPreTrainedModel, + ) + from .models.flaubert import ( + TFFlaubertForMultipleChoice, + TFFlaubertForQuestionAnsweringSimple, + TFFlaubertForSequenceClassification, + TFFlaubertForTokenClassification, + TFFlaubertModel, + TFFlaubertPreTrainedModel, + TFFlaubertWithLMHeadModel, + ) + from .models.funnel import ( + TFFunnelBaseModel, + TFFunnelForMaskedLM, + TFFunnelForMultipleChoice, + TFFunnelForPreTraining, + TFFunnelForQuestionAnswering, + TFFunnelForSequenceClassification, + TFFunnelForTokenClassification, + TFFunnelModel, + TFFunnelPreTrainedModel, + ) + from .models.gpt2 import ( + TFGPT2DoubleHeadsModel, + TFGPT2ForSequenceClassification, + TFGPT2LMHeadModel, + TFGPT2MainLayer, + TFGPT2Model, + TFGPT2PreTrainedModel, + ) + from .models.gptj import ( + TFGPTJForCausalLM, + TFGPTJForQuestionAnswering, + TFGPTJForSequenceClassification, + TFGPTJModel, + TFGPTJPreTrainedModel, + ) + from .models.groupvit import ( + TFGroupViTModel, + TFGroupViTPreTrainedModel, + TFGroupViTTextModel, + TFGroupViTVisionModel, + ) + from .models.hubert import ( + TFHubertForCTC, + TFHubertModel, + TFHubertPreTrainedModel, + ) + from .models.idefics import ( + TFIdeficsForVisionText2Text, + TFIdeficsModel, + TFIdeficsPreTrainedModel, + ) + from .models.layoutlm import ( + TFLayoutLMForMaskedLM, + TFLayoutLMForQuestionAnswering, + TFLayoutLMForSequenceClassification, + TFLayoutLMForTokenClassification, + TFLayoutLMMainLayer, + TFLayoutLMModel, + TFLayoutLMPreTrainedModel, + ) + from .models.layoutlmv3 import ( + TFLayoutLMv3ForQuestionAnswering, + TFLayoutLMv3ForSequenceClassification, + TFLayoutLMv3ForTokenClassification, + TFLayoutLMv3Model, + TFLayoutLMv3PreTrainedModel, + ) + from .models.led import ( + TFLEDForConditionalGeneration, + TFLEDModel, + TFLEDPreTrainedModel, + ) + from .models.longformer import ( + TFLongformerForMaskedLM, + TFLongformerForMultipleChoice, + TFLongformerForQuestionAnswering, + TFLongformerForSequenceClassification, + TFLongformerForTokenClassification, + TFLongformerModel, + TFLongformerPreTrainedModel, + ) + from .models.lxmert import ( + TFLxmertForPreTraining, + TFLxmertMainLayer, + TFLxmertModel, + TFLxmertPreTrainedModel, + TFLxmertVisualFeatureEncoder, + ) + from .models.marian import ( + TFMarianModel, + TFMarianMTModel, + TFMarianPreTrainedModel, + ) + from .models.mbart import ( + TFMBartForConditionalGeneration, + TFMBartModel, + TFMBartPreTrainedModel, + ) + from .models.mistral import ( + TFMistralForCausalLM, + TFMistralForSequenceClassification, + TFMistralModel, + TFMistralPreTrainedModel, + ) + from .models.mobilebert import ( + TFMobileBertForMaskedLM, + TFMobileBertForMultipleChoice, + TFMobileBertForNextSentencePrediction, + TFMobileBertForPreTraining, + TFMobileBertForQuestionAnswering, + TFMobileBertForSequenceClassification, + TFMobileBertForTokenClassification, + TFMobileBertMainLayer, + TFMobileBertModel, + TFMobileBertPreTrainedModel, + ) + from .models.mobilevit import ( + TFMobileViTForImageClassification, + TFMobileViTForSemanticSegmentation, + TFMobileViTModel, + TFMobileViTPreTrainedModel, + ) + from .models.mpnet import ( + TFMPNetForMaskedLM, + TFMPNetForMultipleChoice, + TFMPNetForQuestionAnswering, + TFMPNetForSequenceClassification, + TFMPNetForTokenClassification, + TFMPNetMainLayer, + TFMPNetModel, + TFMPNetPreTrainedModel, + ) + from .models.mt5 import ( + TFMT5EncoderModel, + TFMT5ForConditionalGeneration, + TFMT5Model, + ) + from .models.openai import ( + TFOpenAIGPTDoubleHeadsModel, + TFOpenAIGPTForSequenceClassification, + TFOpenAIGPTLMHeadModel, + TFOpenAIGPTMainLayer, + TFOpenAIGPTModel, + TFOpenAIGPTPreTrainedModel, + ) + from .models.opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel + from .models.pegasus import ( + TFPegasusForConditionalGeneration, + TFPegasusModel, + TFPegasusPreTrainedModel, + ) + from .models.rag import ( + TFRagModel, + TFRagPreTrainedModel, + TFRagSequenceForGeneration, + TFRagTokenForGeneration, + ) + from .models.regnet import ( + TFRegNetForImageClassification, + TFRegNetModel, + TFRegNetPreTrainedModel, + ) + from .models.rembert import ( + TFRemBertForCausalLM, + TFRemBertForMaskedLM, + TFRemBertForMultipleChoice, + TFRemBertForQuestionAnswering, + TFRemBertForSequenceClassification, + TFRemBertForTokenClassification, + TFRemBertModel, + TFRemBertPreTrainedModel, + ) + from .models.resnet import ( + TFResNetForImageClassification, + TFResNetModel, + TFResNetPreTrainedModel, + ) + from .models.roberta import ( + TFRobertaForCausalLM, + TFRobertaForMaskedLM, + TFRobertaForMultipleChoice, + TFRobertaForQuestionAnswering, + TFRobertaForSequenceClassification, + TFRobertaForTokenClassification, + TFRobertaMainLayer, + TFRobertaModel, + TFRobertaPreTrainedModel, + ) + from .models.roberta_prelayernorm import ( + TFRobertaPreLayerNormForCausalLM, + TFRobertaPreLayerNormForMaskedLM, + TFRobertaPreLayerNormForMultipleChoice, + TFRobertaPreLayerNormForQuestionAnswering, + TFRobertaPreLayerNormForSequenceClassification, + TFRobertaPreLayerNormForTokenClassification, + TFRobertaPreLayerNormMainLayer, + TFRobertaPreLayerNormModel, + TFRobertaPreLayerNormPreTrainedModel, + ) + from .models.roformer import ( + TFRoFormerForCausalLM, + TFRoFormerForMaskedLM, + TFRoFormerForMultipleChoice, + TFRoFormerForQuestionAnswering, + TFRoFormerForSequenceClassification, + TFRoFormerForTokenClassification, + TFRoFormerModel, + TFRoFormerPreTrainedModel, + ) + from .models.sam import ( + TFSamModel, + TFSamPreTrainedModel, + ) + from .models.segformer import ( + TFSegformerDecodeHead, + TFSegformerForImageClassification, + TFSegformerForSemanticSegmentation, + TFSegformerModel, + TFSegformerPreTrainedModel, + ) + from .models.speech_to_text import ( + TFSpeech2TextForConditionalGeneration, + TFSpeech2TextModel, + TFSpeech2TextPreTrainedModel, + ) + from .models.swiftformer import ( + TFSwiftFormerForImageClassification, + TFSwiftFormerModel, + TFSwiftFormerPreTrainedModel, + ) + from .models.swin import ( + TFSwinForImageClassification, + TFSwinForMaskedImageModeling, + TFSwinModel, + TFSwinPreTrainedModel, + ) + from .models.t5 import ( + TFT5EncoderModel, + TFT5ForConditionalGeneration, + TFT5Model, + TFT5PreTrainedModel, + ) + from .models.tapas import ( + TFTapasForMaskedLM, + TFTapasForQuestionAnswering, + TFTapasForSequenceClassification, + TFTapasModel, + TFTapasPreTrainedModel, + ) + from .models.vision_encoder_decoder import TFVisionEncoderDecoderModel + from .models.vision_text_dual_encoder import TFVisionTextDualEncoderModel + from .models.vit import ( + TFViTForImageClassification, + TFViTModel, + TFViTPreTrainedModel, + ) + from .models.vit_mae import ( + TFViTMAEForPreTraining, + TFViTMAEModel, + TFViTMAEPreTrainedModel, + ) + from .models.wav2vec2 import ( + TFWav2Vec2ForCTC, + TFWav2Vec2ForSequenceClassification, + TFWav2Vec2Model, + TFWav2Vec2PreTrainedModel, + ) + from .models.whisper import ( + TFWhisperForConditionalGeneration, + TFWhisperModel, + TFWhisperPreTrainedModel, + ) + from .models.xglm import ( + TFXGLMForCausalLM, + TFXGLMModel, + TFXGLMPreTrainedModel, + ) + from .models.xlm import ( + TFXLMForMultipleChoice, + TFXLMForQuestionAnsweringSimple, + TFXLMForSequenceClassification, + TFXLMForTokenClassification, + TFXLMMainLayer, + TFXLMModel, + TFXLMPreTrainedModel, + TFXLMWithLMHeadModel, + ) + from .models.xlm_roberta import ( + TFXLMRobertaForCausalLM, + TFXLMRobertaForMaskedLM, + TFXLMRobertaForMultipleChoice, + TFXLMRobertaForQuestionAnswering, + TFXLMRobertaForSequenceClassification, + TFXLMRobertaForTokenClassification, + TFXLMRobertaModel, + TFXLMRobertaPreTrainedModel, + ) + from .models.xlnet import ( + TFXLNetForMultipleChoice, + TFXLNetForQuestionAnsweringSimple, + TFXLNetForSequenceClassification, + TFXLNetForTokenClassification, + TFXLNetLMHeadModel, + TFXLNetMainLayer, + TFXLNetModel, + TFXLNetPreTrainedModel, + ) + + # Optimization + from .optimization_tf import ( + AdamWeightDecay, + GradientAccumulator, + WarmUp, + create_optimizer, + ) + + try: + if not ( + is_librosa_available() + and is_essentia_available() + and is_scipy_available() + and is_torch_available() + and is_pretty_midi_available() + ): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects import * + else: + from .models.pop2piano import ( + Pop2PianoFeatureExtractor, + Pop2PianoProcessor, + Pop2PianoTokenizer, + ) + + try: + if not is_torchaudio_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from .utils.dummy_torchaudio_objects import * + else: + from .models.musicgen_melody import MusicgenMelodyFeatureExtractor, MusicgenMelodyProcessor + try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + # Import the same objects as dummies to get them in the namespace. + # They will raise an import error if the user tries to instantiate / use them. + from .utils.dummy_flax_objects import * + else: + from .generation import ( + FlaxForcedBOSTokenLogitsProcessor, + FlaxForcedEOSTokenLogitsProcessor, + FlaxForceTokensLogitsProcessor, + FlaxGenerationMixin, + FlaxLogitsProcessor, + FlaxLogitsProcessorList, + FlaxLogitsWarper, + FlaxMinLengthLogitsProcessor, + FlaxSuppressTokensAtBeginLogitsProcessor, + FlaxSuppressTokensLogitsProcessor, + FlaxTemperatureLogitsWarper, + FlaxTopKLogitsWarper, + FlaxTopPLogitsWarper, + FlaxWhisperTimeStampLogitsProcessor, + ) + from .modeling_flax_utils import FlaxPreTrainedModel + + # Flax model imports + from .models.albert import ( + FlaxAlbertForMaskedLM, + FlaxAlbertForMultipleChoice, + FlaxAlbertForPreTraining, + FlaxAlbertForQuestionAnswering, + FlaxAlbertForSequenceClassification, + FlaxAlbertForTokenClassification, + FlaxAlbertModel, + FlaxAlbertPreTrainedModel, + ) + from .models.auto import ( + FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, + FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, + FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + FLAX_MODEL_FOR_MASKED_LM_MAPPING, + FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + FLAX_MODEL_FOR_PRETRAINING_MAPPING, + FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, + FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING, + FLAX_MODEL_MAPPING, + FlaxAutoModel, + FlaxAutoModelForCausalLM, + FlaxAutoModelForImageClassification, + FlaxAutoModelForMaskedLM, + FlaxAutoModelForMultipleChoice, + FlaxAutoModelForNextSentencePrediction, + FlaxAutoModelForPreTraining, + FlaxAutoModelForQuestionAnswering, + FlaxAutoModelForSeq2SeqLM, + FlaxAutoModelForSequenceClassification, + FlaxAutoModelForSpeechSeq2Seq, + FlaxAutoModelForTokenClassification, + FlaxAutoModelForVision2Seq, + ) + from .models.bart import ( + FlaxBartDecoderPreTrainedModel, + FlaxBartForCausalLM, + FlaxBartForConditionalGeneration, + FlaxBartForQuestionAnswering, + FlaxBartForSequenceClassification, + FlaxBartModel, + FlaxBartPreTrainedModel, + ) + from .models.beit import ( + FlaxBeitForImageClassification, + FlaxBeitForMaskedImageModeling, + FlaxBeitModel, + FlaxBeitPreTrainedModel, + ) + from .models.bert import ( + FlaxBertForCausalLM, + FlaxBertForMaskedLM, + FlaxBertForMultipleChoice, + FlaxBertForNextSentencePrediction, + FlaxBertForPreTraining, + FlaxBertForQuestionAnswering, + FlaxBertForSequenceClassification, + FlaxBertForTokenClassification, + FlaxBertModel, + FlaxBertPreTrainedModel, + ) + from .models.big_bird import ( + FlaxBigBirdForCausalLM, + FlaxBigBirdForMaskedLM, + FlaxBigBirdForMultipleChoice, + FlaxBigBirdForPreTraining, + FlaxBigBirdForQuestionAnswering, + FlaxBigBirdForSequenceClassification, + FlaxBigBirdForTokenClassification, + FlaxBigBirdModel, + FlaxBigBirdPreTrainedModel, + ) + from .models.blenderbot import ( + FlaxBlenderbotForConditionalGeneration, + FlaxBlenderbotModel, + FlaxBlenderbotPreTrainedModel, + ) + from .models.blenderbot_small import ( + FlaxBlenderbotSmallForConditionalGeneration, + FlaxBlenderbotSmallModel, + FlaxBlenderbotSmallPreTrainedModel, + ) + from .models.bloom import ( + FlaxBloomForCausalLM, + FlaxBloomModel, + FlaxBloomPreTrainedModel, + ) + from .models.clip import ( + FlaxCLIPModel, + FlaxCLIPPreTrainedModel, + FlaxCLIPTextModel, + FlaxCLIPTextModelWithProjection, + FlaxCLIPTextPreTrainedModel, + FlaxCLIPVisionModel, + FlaxCLIPVisionPreTrainedModel, + ) + from .models.dinov2 import ( + FlaxDinov2ForImageClassification, + FlaxDinov2Model, + FlaxDinov2PreTrainedModel, + ) + from .models.distilbert import ( + FlaxDistilBertForMaskedLM, + FlaxDistilBertForMultipleChoice, + FlaxDistilBertForQuestionAnswering, + FlaxDistilBertForSequenceClassification, + FlaxDistilBertForTokenClassification, + FlaxDistilBertModel, + FlaxDistilBertPreTrainedModel, + ) + from .models.electra import ( + FlaxElectraForCausalLM, + FlaxElectraForMaskedLM, + FlaxElectraForMultipleChoice, + FlaxElectraForPreTraining, + FlaxElectraForQuestionAnswering, + FlaxElectraForSequenceClassification, + FlaxElectraForTokenClassification, + FlaxElectraModel, + FlaxElectraPreTrainedModel, + ) + from .models.encoder_decoder import FlaxEncoderDecoderModel + from .models.gemma import ( + FlaxGemmaForCausalLM, + FlaxGemmaModel, + FlaxGemmaPreTrainedModel, + ) + from .models.gpt2 import ( + FlaxGPT2LMHeadModel, + FlaxGPT2Model, + FlaxGPT2PreTrainedModel, + ) + from .models.gpt_neo import ( + FlaxGPTNeoForCausalLM, + FlaxGPTNeoModel, + FlaxGPTNeoPreTrainedModel, + ) + from .models.gptj import ( + FlaxGPTJForCausalLM, + FlaxGPTJModel, + FlaxGPTJPreTrainedModel, + ) + from .models.llama import ( + FlaxLlamaForCausalLM, + FlaxLlamaModel, + FlaxLlamaPreTrainedModel, + ) + from .models.longt5 import ( + FlaxLongT5ForConditionalGeneration, + FlaxLongT5Model, + FlaxLongT5PreTrainedModel, + ) + from .models.marian import ( + FlaxMarianModel, + FlaxMarianMTModel, + FlaxMarianPreTrainedModel, + ) + from .models.mbart import ( + FlaxMBartForConditionalGeneration, + FlaxMBartForQuestionAnswering, + FlaxMBartForSequenceClassification, + FlaxMBartModel, + FlaxMBartPreTrainedModel, + ) + from .models.mistral import ( + FlaxMistralForCausalLM, + FlaxMistralModel, + FlaxMistralPreTrainedModel, + ) + from .models.mt5 import ( + FlaxMT5EncoderModel, + FlaxMT5ForConditionalGeneration, + FlaxMT5Model, + ) + from .models.opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel + from .models.pegasus import ( + FlaxPegasusForConditionalGeneration, + FlaxPegasusModel, + FlaxPegasusPreTrainedModel, + ) + from .models.regnet import ( + FlaxRegNetForImageClassification, + FlaxRegNetModel, + FlaxRegNetPreTrainedModel, + ) + from .models.resnet import ( + FlaxResNetForImageClassification, + FlaxResNetModel, + FlaxResNetPreTrainedModel, + ) + from .models.roberta import ( + FlaxRobertaForCausalLM, + FlaxRobertaForMaskedLM, + FlaxRobertaForMultipleChoice, + FlaxRobertaForQuestionAnswering, + FlaxRobertaForSequenceClassification, + FlaxRobertaForTokenClassification, + FlaxRobertaModel, + FlaxRobertaPreTrainedModel, + ) + from .models.roberta_prelayernorm import ( + FlaxRobertaPreLayerNormForCausalLM, + FlaxRobertaPreLayerNormForMaskedLM, + FlaxRobertaPreLayerNormForMultipleChoice, + FlaxRobertaPreLayerNormForQuestionAnswering, + FlaxRobertaPreLayerNormForSequenceClassification, + FlaxRobertaPreLayerNormForTokenClassification, + FlaxRobertaPreLayerNormModel, + FlaxRobertaPreLayerNormPreTrainedModel, + ) + from .models.roformer import ( + FlaxRoFormerForMaskedLM, + FlaxRoFormerForMultipleChoice, + FlaxRoFormerForQuestionAnswering, + FlaxRoFormerForSequenceClassification, + FlaxRoFormerForTokenClassification, + FlaxRoFormerModel, + FlaxRoFormerPreTrainedModel, + ) + from .models.speech_encoder_decoder import FlaxSpeechEncoderDecoderModel + from .models.t5 import ( + FlaxT5EncoderModel, + FlaxT5ForConditionalGeneration, + FlaxT5Model, + FlaxT5PreTrainedModel, + ) + from .models.vision_encoder_decoder import FlaxVisionEncoderDecoderModel + from .models.vision_text_dual_encoder import FlaxVisionTextDualEncoderModel + from .models.vit import ( + FlaxViTForImageClassification, + FlaxViTModel, + FlaxViTPreTrainedModel, + ) + from .models.wav2vec2 import ( + FlaxWav2Vec2ForCTC, + FlaxWav2Vec2ForPreTraining, + FlaxWav2Vec2Model, + FlaxWav2Vec2PreTrainedModel, + ) + from .models.whisper import ( + FlaxWhisperForAudioClassification, + FlaxWhisperForConditionalGeneration, + FlaxWhisperModel, + FlaxWhisperPreTrainedModel, + ) + from .models.xglm import ( + FlaxXGLMForCausalLM, + FlaxXGLMModel, + FlaxXGLMPreTrainedModel, + ) + from .models.xlm_roberta import ( + FlaxXLMRobertaForCausalLM, + FlaxXLMRobertaForMaskedLM, + FlaxXLMRobertaForMultipleChoice, + FlaxXLMRobertaForQuestionAnswering, + FlaxXLMRobertaForSequenceClassification, + FlaxXLMRobertaForTokenClassification, + FlaxXLMRobertaModel, + FlaxXLMRobertaPreTrainedModel, + ) + + +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + extra_objects={"__version__": __version__}, + ) + + +if not is_tf_available() and not is_torch_available() and not is_flax_available(): + logger.warning_advice( + "None of PyTorch, TensorFlow >= 2.0, or Flax have been found. " + "Models won't be available and only tokenizers, configuration " + "and file/data utilities can be used." + ) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/__init__.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a72fca91e91291cb3f607f016f494b35c6d8bb2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/__init__.py @@ -0,0 +1,318 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from . import ( + albert, + align, + altclip, + aria, + audio_spectrogram_transformer, + auto, + autoformer, + aya_vision, + bamba, + bark, + bart, + barthez, + bartpho, + beit, + bert, + bert_generation, + bert_japanese, + bertweet, + big_bird, + bigbird_pegasus, + biogpt, + bit, + blenderbot, + blenderbot_small, + blip, + blip_2, + bloom, + bridgetower, + bros, + byt5, + camembert, + canine, + chameleon, + chinese_clip, + clap, + clip, + clipseg, + clvp, + code_llama, + codegen, + cohere, + cohere2, + colpali, + conditional_detr, + convbert, + convnext, + convnextv2, + cpm, + cpmant, + ctrl, + cvt, + dab_detr, + dac, + data2vec, + dbrx, + deberta, + deberta_v2, + decision_transformer, + deformable_detr, + deit, + deprecated, + depth_anything, + depth_pro, + detr, + dialogpt, + diffllama, + dinat, + dinov2, + dinov2_with_registers, + distilbert, + dit, + donut, + dpr, + dpt, + efficientnet, + electra, + emu3, + encodec, + encoder_decoder, + ernie, + esm, + falcon, + falcon_mamba, + fastspeech2_conformer, + flaubert, + flava, + fnet, + focalnet, + fsmt, + funnel, + fuyu, + gemma, + gemma2, + gemma3, + git, + glm, + glpn, + got_ocr2, + gpt2, + gpt_bigcode, + gpt_neo, + gpt_neox, + gpt_neox_japanese, + gpt_sw3, + gptj, + granite, + granitemoe, + granitemoeshared, + grounding_dino, + groupvit, + helium, + herbert, + hiera, + hubert, + ibert, + idefics, + idefics2, + idefics3, + ijepa, + imagegpt, + informer, + instructblip, + instructblipvideo, + jamba, + jetmoe, + kosmos2, + layoutlm, + layoutlmv2, + layoutlmv3, + layoutxlm, + led, + levit, + lilt, + llama, + llava, + llava_next, + llava_next_video, + llava_onevision, + longformer, + longt5, + luke, + lxmert, + m2m_100, + mamba, + mamba2, + marian, + markuplm, + mask2former, + maskformer, + mbart, + mbart50, + megatron_bert, + megatron_gpt2, + mgp_str, + mimi, + mistral, + mistral3, + mixtral, + mllama, + mluke, + mobilebert, + mobilenet_v1, + mobilenet_v2, + mobilevit, + mobilevitv2, + modernbert, + moonshine, + moshi, + mpnet, + mpt, + mra, + mt5, + musicgen, + musicgen_melody, + mvp, + myt5, + nemotron, + nllb, + nllb_moe, + nougat, + nystromformer, + olmo, + olmo2, + olmoe, + omdet_turbo, + oneformer, + openai, + opt, + owlv2, + owlvit, + paligemma, + patchtsmixer, + patchtst, + pegasus, + pegasus_x, + perceiver, + persimmon, + phi, + phi3, + phimoe, + phobert, + pix2struct, + pixtral, + plbart, + poolformer, + pop2piano, + prophetnet, + pvt, + pvt_v2, + qwen2, + qwen2_5_vl, + qwen2_audio, + qwen2_moe, + qwen2_vl, + rag, + recurrent_gemma, + reformer, + regnet, + rembert, + resnet, + roberta, + roberta_prelayernorm, + roc_bert, + roformer, + rt_detr, + rt_detr_v2, + rwkv, + sam, + seamless_m4t, + seamless_m4t_v2, + segformer, + seggpt, + sew, + sew_d, + siglip, + siglip2, + smolvlm, + speech_encoder_decoder, + speech_to_text, + speecht5, + splinter, + squeezebert, + stablelm, + starcoder2, + superglue, + superpoint, + swiftformer, + swin, + swin2sr, + swinv2, + switch_transformers, + t5, + table_transformer, + tapas, + textnet, + time_series_transformer, + timesformer, + timm_backbone, + timm_wrapper, + trocr, + tvp, + udop, + umt5, + unispeech, + unispeech_sat, + univnet, + upernet, + video_llava, + videomae, + vilt, + vipllava, + vision_encoder_decoder, + vision_text_dual_encoder, + visual_bert, + vit, + vit_mae, + vit_msn, + vitdet, + vitmatte, + vitpose, + vitpose_backbone, + vits, + vivit, + wav2vec2, + wav2vec2_bert, + wav2vec2_conformer, + wav2vec2_phoneme, + wav2vec2_with_lm, + wavlm, + whisper, + x_clip, + xglm, + xlm, + xlm_roberta, + xlm_roberta_xl, + xlnet, + xmod, + yolos, + yoso, + zamba, + zamba2, + zoedepth, +) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/configuration_auto.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/configuration_auto.py new file mode 100644 index 0000000000000000000000000000000000000000..0969976937f17e81c9ef02198df9e06e407023ea --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/configuration_auto.py @@ -0,0 +1,1150 @@ +# coding=utf-8 +# Copyright 2018 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Auto Config class.""" + +import importlib +import os +import re +import warnings +from collections import OrderedDict +from typing import List, Union + +from ...configuration_utils import PretrainedConfig +from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code +from ...utils import CONFIG_NAME, logging + + +logger = logging.get_logger(__name__) + + +CONFIG_MAPPING_NAMES = OrderedDict( + [ + # Add configs here + ("albert", "AlbertConfig"), + ("align", "AlignConfig"), + ("altclip", "AltCLIPConfig"), + ("aria", "AriaConfig"), + ("aria_text", "AriaTextConfig"), + ("audio-spectrogram-transformer", "ASTConfig"), + ("autoformer", "AutoformerConfig"), + ("aya_vision", "AyaVisionConfig"), + ("bamba", "BambaConfig"), + ("bark", "BarkConfig"), + ("bart", "BartConfig"), + ("beit", "BeitConfig"), + ("bert", "BertConfig"), + ("bert-generation", "BertGenerationConfig"), + ("big_bird", "BigBirdConfig"), + ("bigbird_pegasus", "BigBirdPegasusConfig"), + ("biogpt", "BioGptConfig"), + ("bit", "BitConfig"), + ("blenderbot", "BlenderbotConfig"), + ("blenderbot-small", "BlenderbotSmallConfig"), + ("blip", "BlipConfig"), + ("blip-2", "Blip2Config"), + ("bloom", "BloomConfig"), + ("bridgetower", "BridgeTowerConfig"), + ("bros", "BrosConfig"), + ("camembert", "CamembertConfig"), + ("canine", "CanineConfig"), + ("chameleon", "ChameleonConfig"), + ("chinese_clip", "ChineseCLIPConfig"), + ("chinese_clip_vision_model", "ChineseCLIPVisionConfig"), + ("clap", "ClapConfig"), + ("clip", "CLIPConfig"), + ("clip_text_model", "CLIPTextConfig"), + ("clip_vision_model", "CLIPVisionConfig"), + ("clipseg", "CLIPSegConfig"), + ("clvp", "ClvpConfig"), + ("code_llama", "LlamaConfig"), + ("codegen", "CodeGenConfig"), + ("cohere", "CohereConfig"), + ("cohere2", "Cohere2Config"), + ("colpali", "ColPaliConfig"), + ("conditional_detr", "ConditionalDetrConfig"), + ("convbert", "ConvBertConfig"), + ("convnext", "ConvNextConfig"), + ("convnextv2", "ConvNextV2Config"), + ("cpmant", "CpmAntConfig"), + ("ctrl", "CTRLConfig"), + ("cvt", "CvtConfig"), + ("dab-detr", "DabDetrConfig"), + ("dac", "DacConfig"), + ("data2vec-audio", "Data2VecAudioConfig"), + ("data2vec-text", "Data2VecTextConfig"), + ("data2vec-vision", "Data2VecVisionConfig"), + ("dbrx", "DbrxConfig"), + ("deberta", "DebertaConfig"), + ("deberta-v2", "DebertaV2Config"), + ("decision_transformer", "DecisionTransformerConfig"), + ("deformable_detr", "DeformableDetrConfig"), + ("deit", "DeiTConfig"), + ("depth_anything", "DepthAnythingConfig"), + ("depth_pro", "DepthProConfig"), + ("deta", "DetaConfig"), + ("detr", "DetrConfig"), + ("diffllama", "DiffLlamaConfig"), + ("dinat", "DinatConfig"), + ("dinov2", "Dinov2Config"), + ("dinov2_with_registers", "Dinov2WithRegistersConfig"), + ("distilbert", "DistilBertConfig"), + ("donut-swin", "DonutSwinConfig"), + ("dpr", "DPRConfig"), + ("dpt", "DPTConfig"), + ("efficientformer", "EfficientFormerConfig"), + ("efficientnet", "EfficientNetConfig"), + ("electra", "ElectraConfig"), + ("emu3", "Emu3Config"), + ("encodec", "EncodecConfig"), + ("encoder-decoder", "EncoderDecoderConfig"), + ("ernie", "ErnieConfig"), + ("ernie_m", "ErnieMConfig"), + ("esm", "EsmConfig"), + ("falcon", "FalconConfig"), + ("falcon_mamba", "FalconMambaConfig"), + ("fastspeech2_conformer", "FastSpeech2ConformerConfig"), + ("flaubert", "FlaubertConfig"), + ("flava", "FlavaConfig"), + ("fnet", "FNetConfig"), + ("focalnet", "FocalNetConfig"), + ("fsmt", "FSMTConfig"), + ("funnel", "FunnelConfig"), + ("fuyu", "FuyuConfig"), + ("gemma", "GemmaConfig"), + ("gemma2", "Gemma2Config"), + ("gemma3", "Gemma3Config"), + ("gemma3_text", "Gemma3TextConfig"), + ("git", "GitConfig"), + ("glm", "GlmConfig"), + ("glpn", "GLPNConfig"), + ("got_ocr2", "GotOcr2Config"), + ("gpt-sw3", "GPT2Config"), + ("gpt2", "GPT2Config"), + ("gpt_bigcode", "GPTBigCodeConfig"), + ("gpt_neo", "GPTNeoConfig"), + ("gpt_neox", "GPTNeoXConfig"), + ("gpt_neox_japanese", "GPTNeoXJapaneseConfig"), + ("gptj", "GPTJConfig"), + ("gptsan-japanese", "GPTSanJapaneseConfig"), + ("granite", "GraniteConfig"), + ("granitemoe", "GraniteMoeConfig"), + ("granitemoeshared", "GraniteMoeSharedConfig"), + ("granitevision", "LlavaNextConfig"), + ("graphormer", "GraphormerConfig"), + ("grounding-dino", "GroundingDinoConfig"), + ("groupvit", "GroupViTConfig"), + ("helium", "HeliumConfig"), + ("hiera", "HieraConfig"), + ("hubert", "HubertConfig"), + ("ibert", "IBertConfig"), + ("idefics", "IdeficsConfig"), + ("idefics2", "Idefics2Config"), + ("idefics3", "Idefics3Config"), + ("idefics3_vision", "Idefics3VisionConfig"), + ("ijepa", "IJepaConfig"), + ("imagegpt", "ImageGPTConfig"), + ("informer", "InformerConfig"), + ("instructblip", "InstructBlipConfig"), + ("instructblipvideo", "InstructBlipVideoConfig"), + ("jamba", "JambaConfig"), + ("jetmoe", "JetMoeConfig"), + ("jukebox", "JukeboxConfig"), + ("kosmos-2", "Kosmos2Config"), + ("layoutlm", "LayoutLMConfig"), + ("layoutlmv2", "LayoutLMv2Config"), + ("layoutlmv3", "LayoutLMv3Config"), + ("led", "LEDConfig"), + ("levit", "LevitConfig"), + ("lilt", "LiltConfig"), + ("llama", "LlamaConfig"), + ("llava", "LlavaConfig"), + ("llava_next", "LlavaNextConfig"), + ("llava_next_video", "LlavaNextVideoConfig"), + ("llava_onevision", "LlavaOnevisionConfig"), + ("longformer", "LongformerConfig"), + ("longt5", "LongT5Config"), + ("luke", "LukeConfig"), + ("lxmert", "LxmertConfig"), + ("m2m_100", "M2M100Config"), + ("mamba", "MambaConfig"), + ("mamba2", "Mamba2Config"), + ("marian", "MarianConfig"), + ("markuplm", "MarkupLMConfig"), + ("mask2former", "Mask2FormerConfig"), + ("maskformer", "MaskFormerConfig"), + ("maskformer-swin", "MaskFormerSwinConfig"), + ("mbart", "MBartConfig"), + ("mctct", "MCTCTConfig"), + ("mega", "MegaConfig"), + ("megatron-bert", "MegatronBertConfig"), + ("mgp-str", "MgpstrConfig"), + ("mimi", "MimiConfig"), + ("mistral", "MistralConfig"), + ("mistral3", "Mistral3Config"), + ("mixtral", "MixtralConfig"), + ("mllama", "MllamaConfig"), + ("mobilebert", "MobileBertConfig"), + ("mobilenet_v1", "MobileNetV1Config"), + ("mobilenet_v2", "MobileNetV2Config"), + ("mobilevit", "MobileViTConfig"), + ("mobilevitv2", "MobileViTV2Config"), + ("modernbert", "ModernBertConfig"), + ("moonshine", "MoonshineConfig"), + ("moshi", "MoshiConfig"), + ("mpnet", "MPNetConfig"), + ("mpt", "MptConfig"), + ("mra", "MraConfig"), + ("mt5", "MT5Config"), + ("musicgen", "MusicgenConfig"), + ("musicgen_melody", "MusicgenMelodyConfig"), + ("mvp", "MvpConfig"), + ("nat", "NatConfig"), + ("nemotron", "NemotronConfig"), + ("nezha", "NezhaConfig"), + ("nllb-moe", "NllbMoeConfig"), + ("nougat", "VisionEncoderDecoderConfig"), + ("nystromformer", "NystromformerConfig"), + ("olmo", "OlmoConfig"), + ("olmo2", "Olmo2Config"), + ("olmoe", "OlmoeConfig"), + ("omdet-turbo", "OmDetTurboConfig"), + ("oneformer", "OneFormerConfig"), + ("open-llama", "OpenLlamaConfig"), + ("openai-gpt", "OpenAIGPTConfig"), + ("opt", "OPTConfig"), + ("owlv2", "Owlv2Config"), + ("owlvit", "OwlViTConfig"), + ("paligemma", "PaliGemmaConfig"), + ("patchtsmixer", "PatchTSMixerConfig"), + ("patchtst", "PatchTSTConfig"), + ("pegasus", "PegasusConfig"), + ("pegasus_x", "PegasusXConfig"), + ("perceiver", "PerceiverConfig"), + ("persimmon", "PersimmonConfig"), + ("phi", "PhiConfig"), + ("phi3", "Phi3Config"), + ("phimoe", "PhimoeConfig"), + ("pix2struct", "Pix2StructConfig"), + ("pixtral", "PixtralVisionConfig"), + ("plbart", "PLBartConfig"), + ("poolformer", "PoolFormerConfig"), + ("pop2piano", "Pop2PianoConfig"), + ("prophetnet", "ProphetNetConfig"), + ("pvt", "PvtConfig"), + ("pvt_v2", "PvtV2Config"), + ("qdqbert", "QDQBertConfig"), + ("qwen2", "Qwen2Config"), + ("qwen2_5_vl", "Qwen2_5_VLConfig"), + ("qwen2_audio", "Qwen2AudioConfig"), + ("qwen2_audio_encoder", "Qwen2AudioEncoderConfig"), + ("qwen2_moe", "Qwen2MoeConfig"), + ("qwen2_vl", "Qwen2VLConfig"), + ("rag", "RagConfig"), + ("realm", "RealmConfig"), + ("recurrent_gemma", "RecurrentGemmaConfig"), + ("reformer", "ReformerConfig"), + ("regnet", "RegNetConfig"), + ("rembert", "RemBertConfig"), + ("resnet", "ResNetConfig"), + ("retribert", "RetriBertConfig"), + ("roberta", "RobertaConfig"), + ("roberta-prelayernorm", "RobertaPreLayerNormConfig"), + ("roc_bert", "RoCBertConfig"), + ("roformer", "RoFormerConfig"), + ("rt_detr", "RTDetrConfig"), + ("rt_detr_resnet", "RTDetrResNetConfig"), + ("rt_detr_v2", "RTDetrV2Config"), + ("rwkv", "RwkvConfig"), + ("sam", "SamConfig"), + ("seamless_m4t", "SeamlessM4TConfig"), + ("seamless_m4t_v2", "SeamlessM4Tv2Config"), + ("segformer", "SegformerConfig"), + ("seggpt", "SegGptConfig"), + ("sew", "SEWConfig"), + ("sew-d", "SEWDConfig"), + ("siglip", "SiglipConfig"), + ("siglip2", "Siglip2Config"), + ("siglip_vision_model", "SiglipVisionConfig"), + ("smolvlm", "SmolVLMConfig"), + ("smolvlm_vision", "SmolVLMVisionConfig"), + ("speech-encoder-decoder", "SpeechEncoderDecoderConfig"), + ("speech_to_text", "Speech2TextConfig"), + ("speech_to_text_2", "Speech2Text2Config"), + ("speecht5", "SpeechT5Config"), + ("splinter", "SplinterConfig"), + ("squeezebert", "SqueezeBertConfig"), + ("stablelm", "StableLmConfig"), + ("starcoder2", "Starcoder2Config"), + ("superglue", "SuperGlueConfig"), + ("superpoint", "SuperPointConfig"), + ("swiftformer", "SwiftFormerConfig"), + ("swin", "SwinConfig"), + ("swin2sr", "Swin2SRConfig"), + ("swinv2", "Swinv2Config"), + ("switch_transformers", "SwitchTransformersConfig"), + ("t5", "T5Config"), + ("table-transformer", "TableTransformerConfig"), + ("tapas", "TapasConfig"), + ("textnet", "TextNetConfig"), + ("time_series_transformer", "TimeSeriesTransformerConfig"), + ("timesformer", "TimesformerConfig"), + ("timm_backbone", "TimmBackboneConfig"), + ("timm_wrapper", "TimmWrapperConfig"), + ("trajectory_transformer", "TrajectoryTransformerConfig"), + ("transfo-xl", "TransfoXLConfig"), + ("trocr", "TrOCRConfig"), + ("tvlt", "TvltConfig"), + ("tvp", "TvpConfig"), + ("udop", "UdopConfig"), + ("umt5", "UMT5Config"), + ("unispeech", "UniSpeechConfig"), + ("unispeech-sat", "UniSpeechSatConfig"), + ("univnet", "UnivNetConfig"), + ("upernet", "UperNetConfig"), + ("van", "VanConfig"), + ("video_llava", "VideoLlavaConfig"), + ("videomae", "VideoMAEConfig"), + ("vilt", "ViltConfig"), + ("vipllava", "VipLlavaConfig"), + ("vision-encoder-decoder", "VisionEncoderDecoderConfig"), + ("vision-text-dual-encoder", "VisionTextDualEncoderConfig"), + ("visual_bert", "VisualBertConfig"), + ("vit", "ViTConfig"), + ("vit_hybrid", "ViTHybridConfig"), + ("vit_mae", "ViTMAEConfig"), + ("vit_msn", "ViTMSNConfig"), + ("vitdet", "VitDetConfig"), + ("vitmatte", "VitMatteConfig"), + ("vitpose", "VitPoseConfig"), + ("vitpose_backbone", "VitPoseBackboneConfig"), + ("vits", "VitsConfig"), + ("vivit", "VivitConfig"), + ("wav2vec2", "Wav2Vec2Config"), + ("wav2vec2-bert", "Wav2Vec2BertConfig"), + ("wav2vec2-conformer", "Wav2Vec2ConformerConfig"), + ("wavlm", "WavLMConfig"), + ("whisper", "WhisperConfig"), + ("xclip", "XCLIPConfig"), + ("xglm", "XGLMConfig"), + ("xlm", "XLMConfig"), + ("xlm-prophetnet", "XLMProphetNetConfig"), + ("xlm-roberta", "XLMRobertaConfig"), + ("xlm-roberta-xl", "XLMRobertaXLConfig"), + ("xlnet", "XLNetConfig"), + ("xmod", "XmodConfig"), + ("yolos", "YolosConfig"), + ("yoso", "YosoConfig"), + ("zamba", "ZambaConfig"), + ("zamba2", "Zamba2Config"), + ("zoedepth", "ZoeDepthConfig"), + ] +) + + +MODEL_NAMES_MAPPING = OrderedDict( + [ + # Add full (and cased) model names here + ("albert", "ALBERT"), + ("align", "ALIGN"), + ("altclip", "AltCLIP"), + ("aria", "Aria"), + ("aria_text", "AriaText"), + ("audio-spectrogram-transformer", "Audio Spectrogram Transformer"), + ("autoformer", "Autoformer"), + ("aya_vision", "AyaVision"), + ("bamba", "Bamba"), + ("bark", "Bark"), + ("bart", "BART"), + ("barthez", "BARThez"), + ("bartpho", "BARTpho"), + ("beit", "BEiT"), + ("bert", "BERT"), + ("bert-generation", "Bert Generation"), + ("bert-japanese", "BertJapanese"), + ("bertweet", "BERTweet"), + ("big_bird", "BigBird"), + ("bigbird_pegasus", "BigBird-Pegasus"), + ("biogpt", "BioGpt"), + ("bit", "BiT"), + ("blenderbot", "Blenderbot"), + ("blenderbot-small", "BlenderbotSmall"), + ("blip", "BLIP"), + ("blip-2", "BLIP-2"), + ("bloom", "BLOOM"), + ("bort", "BORT"), + ("bridgetower", "BridgeTower"), + ("bros", "BROS"), + ("byt5", "ByT5"), + ("camembert", "CamemBERT"), + ("canine", "CANINE"), + ("chameleon", "Chameleon"), + ("chinese_clip", "Chinese-CLIP"), + ("chinese_clip_vision_model", "ChineseCLIPVisionModel"), + ("clap", "CLAP"), + ("clip", "CLIP"), + ("clip_text_model", "CLIPTextModel"), + ("clip_vision_model", "CLIPVisionModel"), + ("clipseg", "CLIPSeg"), + ("clvp", "CLVP"), + ("code_llama", "CodeLlama"), + ("codegen", "CodeGen"), + ("cohere", "Cohere"), + ("cohere2", "Cohere2"), + ("colpali", "ColPali"), + ("conditional_detr", "Conditional DETR"), + ("convbert", "ConvBERT"), + ("convnext", "ConvNeXT"), + ("convnextv2", "ConvNeXTV2"), + ("cpm", "CPM"), + ("cpmant", "CPM-Ant"), + ("ctrl", "CTRL"), + ("cvt", "CvT"), + ("dab-detr", "DAB-DETR"), + ("dac", "DAC"), + ("data2vec-audio", "Data2VecAudio"), + ("data2vec-text", "Data2VecText"), + ("data2vec-vision", "Data2VecVision"), + ("dbrx", "DBRX"), + ("deberta", "DeBERTa"), + ("deberta-v2", "DeBERTa-v2"), + ("decision_transformer", "Decision Transformer"), + ("deformable_detr", "Deformable DETR"), + ("deit", "DeiT"), + ("deplot", "DePlot"), + ("depth_anything", "Depth Anything"), + ("depth_anything_v2", "Depth Anything V2"), + ("depth_pro", "DepthPro"), + ("deta", "DETA"), + ("detr", "DETR"), + ("dialogpt", "DialoGPT"), + ("diffllama", "DiffLlama"), + ("dinat", "DiNAT"), + ("dinov2", "DINOv2"), + ("dinov2_with_registers", "DINOv2 with Registers"), + ("distilbert", "DistilBERT"), + ("dit", "DiT"), + ("donut-swin", "DonutSwin"), + ("dpr", "DPR"), + ("dpt", "DPT"), + ("efficientformer", "EfficientFormer"), + ("efficientnet", "EfficientNet"), + ("electra", "ELECTRA"), + ("emu3", "Emu3"), + ("encodec", "EnCodec"), + ("encoder-decoder", "Encoder decoder"), + ("ernie", "ERNIE"), + ("ernie_m", "ErnieM"), + ("esm", "ESM"), + ("falcon", "Falcon"), + ("falcon3", "Falcon3"), + ("falcon_mamba", "FalconMamba"), + ("fastspeech2_conformer", "FastSpeech2Conformer"), + ("flan-t5", "FLAN-T5"), + ("flan-ul2", "FLAN-UL2"), + ("flaubert", "FlauBERT"), + ("flava", "FLAVA"), + ("fnet", "FNet"), + ("focalnet", "FocalNet"), + ("fsmt", "FairSeq Machine-Translation"), + ("funnel", "Funnel Transformer"), + ("fuyu", "Fuyu"), + ("gemma", "Gemma"), + ("gemma2", "Gemma2"), + ("gemma3", "Gemma3ForConditionalGeneration"), + ("gemma3_text", "Gemma3ForCausalLM"), + ("git", "GIT"), + ("glm", "GLM"), + ("glpn", "GLPN"), + ("got_ocr2", "GOT-OCR2"), + ("gpt-sw3", "GPT-Sw3"), + ("gpt2", "OpenAI GPT-2"), + ("gpt_bigcode", "GPTBigCode"), + ("gpt_neo", "GPT Neo"), + ("gpt_neox", "GPT NeoX"), + ("gpt_neox_japanese", "GPT NeoX Japanese"), + ("gptj", "GPT-J"), + ("gptsan-japanese", "GPTSAN-japanese"), + ("granite", "Granite"), + ("granitemoe", "GraniteMoeMoe"), + ("granitemoeshared", "GraniteMoeSharedMoe"), + ("granitevision", "LLaVA-NeXT"), + ("graphormer", "Graphormer"), + ("grounding-dino", "Grounding DINO"), + ("groupvit", "GroupViT"), + ("helium", "Helium"), + ("herbert", "HerBERT"), + ("hiera", "Hiera"), + ("hubert", "Hubert"), + ("ibert", "I-BERT"), + ("idefics", "IDEFICS"), + ("idefics2", "Idefics2"), + ("idefics3", "Idefics3"), + ("idefics3_vision", "Idefics3VisionTransformer"), + ("ijepa", "I-JEPA"), + ("imagegpt", "ImageGPT"), + ("informer", "Informer"), + ("instructblip", "InstructBLIP"), + ("instructblipvideo", "InstructBlipVideo"), + ("jamba", "Jamba"), + ("jetmoe", "JetMoe"), + ("jukebox", "Jukebox"), + ("kosmos-2", "KOSMOS-2"), + ("layoutlm", "LayoutLM"), + ("layoutlmv2", "LayoutLMv2"), + ("layoutlmv3", "LayoutLMv3"), + ("layoutxlm", "LayoutXLM"), + ("led", "LED"), + ("levit", "LeViT"), + ("lilt", "LiLT"), + ("llama", "LLaMA"), + ("llama2", "Llama2"), + ("llama3", "Llama3"), + ("llava", "LLaVa"), + ("llava_next", "LLaVA-NeXT"), + ("llava_next_video", "LLaVa-NeXT-Video"), + ("llava_onevision", "LLaVA-Onevision"), + ("longformer", "Longformer"), + ("longt5", "LongT5"), + ("luke", "LUKE"), + ("lxmert", "LXMERT"), + ("m2m_100", "M2M100"), + ("madlad-400", "MADLAD-400"), + ("mamba", "Mamba"), + ("mamba2", "mamba2"), + ("marian", "Marian"), + ("markuplm", "MarkupLM"), + ("mask2former", "Mask2Former"), + ("maskformer", "MaskFormer"), + ("maskformer-swin", "MaskFormerSwin"), + ("matcha", "MatCha"), + ("mbart", "mBART"), + ("mbart50", "mBART-50"), + ("mctct", "M-CTC-T"), + ("mega", "MEGA"), + ("megatron-bert", "Megatron-BERT"), + ("megatron_gpt2", "Megatron-GPT2"), + ("mgp-str", "MGP-STR"), + ("mimi", "Mimi"), + ("mistral", "Mistral"), + ("mistral3", "Mistral3"), + ("mixtral", "Mixtral"), + ("mllama", "Mllama"), + ("mluke", "mLUKE"), + ("mms", "MMS"), + ("mobilebert", "MobileBERT"), + ("mobilenet_v1", "MobileNetV1"), + ("mobilenet_v2", "MobileNetV2"), + ("mobilevit", "MobileViT"), + ("mobilevitv2", "MobileViTV2"), + ("modernbert", "ModernBERT"), + ("moonshine", "Moonshine"), + ("moshi", "Moshi"), + ("mpnet", "MPNet"), + ("mpt", "MPT"), + ("mra", "MRA"), + ("mt5", "MT5"), + ("musicgen", "MusicGen"), + ("musicgen_melody", "MusicGen Melody"), + ("mvp", "MVP"), + ("myt5", "myt5"), + ("nat", "NAT"), + ("nemotron", "Nemotron"), + ("nezha", "Nezha"), + ("nllb", "NLLB"), + ("nllb-moe", "NLLB-MOE"), + ("nougat", "Nougat"), + ("nystromformer", "Nyströmformer"), + ("olmo", "OLMo"), + ("olmo2", "OLMo2"), + ("olmoe", "OLMoE"), + ("omdet-turbo", "OmDet-Turbo"), + ("oneformer", "OneFormer"), + ("open-llama", "OpenLlama"), + ("openai-gpt", "OpenAI GPT"), + ("opt", "OPT"), + ("owlv2", "OWLv2"), + ("owlvit", "OWL-ViT"), + ("paligemma", "PaliGemma"), + ("patchtsmixer", "PatchTSMixer"), + ("patchtst", "PatchTST"), + ("pegasus", "Pegasus"), + ("pegasus_x", "PEGASUS-X"), + ("perceiver", "Perceiver"), + ("persimmon", "Persimmon"), + ("phi", "Phi"), + ("phi3", "Phi3"), + ("phimoe", "Phimoe"), + ("phobert", "PhoBERT"), + ("pix2struct", "Pix2Struct"), + ("pixtral", "Pixtral"), + ("plbart", "PLBart"), + ("poolformer", "PoolFormer"), + ("pop2piano", "Pop2Piano"), + ("prophetnet", "ProphetNet"), + ("pvt", "PVT"), + ("pvt_v2", "PVTv2"), + ("qdqbert", "QDQBert"), + ("qwen2", "Qwen2"), + ("qwen2_5_vl", "Qwen2_5_VL"), + ("qwen2_audio", "Qwen2Audio"), + ("qwen2_audio_encoder", "Qwen2AudioEncoder"), + ("qwen2_moe", "Qwen2MoE"), + ("qwen2_vl", "Qwen2VL"), + ("rag", "RAG"), + ("realm", "REALM"), + ("recurrent_gemma", "RecurrentGemma"), + ("reformer", "Reformer"), + ("regnet", "RegNet"), + ("rembert", "RemBERT"), + ("resnet", "ResNet"), + ("retribert", "RetriBERT"), + ("roberta", "RoBERTa"), + ("roberta-prelayernorm", "RoBERTa-PreLayerNorm"), + ("roc_bert", "RoCBert"), + ("roformer", "RoFormer"), + ("rt_detr", "RT-DETR"), + ("rt_detr_resnet", "RT-DETR-ResNet"), + ("rt_detr_v2", "RT-DETRv2"), + ("rwkv", "RWKV"), + ("sam", "SAM"), + ("seamless_m4t", "SeamlessM4T"), + ("seamless_m4t_v2", "SeamlessM4Tv2"), + ("segformer", "SegFormer"), + ("seggpt", "SegGPT"), + ("sew", "SEW"), + ("sew-d", "SEW-D"), + ("siglip", "SigLIP"), + ("siglip2", "SigLIP2"), + ("siglip2_vision_model", "Siglip2VisionModel"), + ("siglip_vision_model", "SiglipVisionModel"), + ("smolvlm", "SmolVLM"), + ("smolvlm_vision", "SmolVLMVisionTransformer"), + ("speech-encoder-decoder", "Speech Encoder decoder"), + ("speech_to_text", "Speech2Text"), + ("speech_to_text_2", "Speech2Text2"), + ("speecht5", "SpeechT5"), + ("splinter", "Splinter"), + ("squeezebert", "SqueezeBERT"), + ("stablelm", "StableLm"), + ("starcoder2", "Starcoder2"), + ("superglue", "SuperGlue"), + ("superpoint", "SuperPoint"), + ("swiftformer", "SwiftFormer"), + ("swin", "Swin Transformer"), + ("swin2sr", "Swin2SR"), + ("swinv2", "Swin Transformer V2"), + ("switch_transformers", "SwitchTransformers"), + ("t5", "T5"), + ("t5v1.1", "T5v1.1"), + ("table-transformer", "Table Transformer"), + ("tapas", "TAPAS"), + ("tapex", "TAPEX"), + ("textnet", "TextNet"), + ("time_series_transformer", "Time Series Transformer"), + ("timesformer", "TimeSformer"), + ("timm_backbone", "TimmBackbone"), + ("timm_wrapper", "TimmWrapperModel"), + ("trajectory_transformer", "Trajectory Transformer"), + ("transfo-xl", "Transformer-XL"), + ("trocr", "TrOCR"), + ("tvlt", "TVLT"), + ("tvp", "TVP"), + ("udop", "UDOP"), + ("ul2", "UL2"), + ("umt5", "UMT5"), + ("unispeech", "UniSpeech"), + ("unispeech-sat", "UniSpeechSat"), + ("univnet", "UnivNet"), + ("upernet", "UPerNet"), + ("van", "VAN"), + ("video_llava", "VideoLlava"), + ("videomae", "VideoMAE"), + ("vilt", "ViLT"), + ("vipllava", "VipLlava"), + ("vision-encoder-decoder", "Vision Encoder decoder"), + ("vision-text-dual-encoder", "VisionTextDualEncoder"), + ("visual_bert", "VisualBERT"), + ("vit", "ViT"), + ("vit_hybrid", "ViT Hybrid"), + ("vit_mae", "ViTMAE"), + ("vit_msn", "ViTMSN"), + ("vitdet", "VitDet"), + ("vitmatte", "ViTMatte"), + ("vitpose", "ViTPose"), + ("vitpose_backbone", "ViTPoseBackbone"), + ("vits", "VITS"), + ("vivit", "ViViT"), + ("wav2vec2", "Wav2Vec2"), + ("wav2vec2-bert", "Wav2Vec2-BERT"), + ("wav2vec2-conformer", "Wav2Vec2-Conformer"), + ("wav2vec2_phoneme", "Wav2Vec2Phoneme"), + ("wavlm", "WavLM"), + ("whisper", "Whisper"), + ("xclip", "X-CLIP"), + ("xglm", "XGLM"), + ("xlm", "XLM"), + ("xlm-prophetnet", "XLM-ProphetNet"), + ("xlm-roberta", "XLM-RoBERTa"), + ("xlm-roberta-xl", "XLM-RoBERTa-XL"), + ("xlm-v", "XLM-V"), + ("xlnet", "XLNet"), + ("xls_r", "XLS-R"), + ("xlsr_wav2vec2", "XLSR-Wav2Vec2"), + ("xmod", "X-MOD"), + ("yolos", "YOLOS"), + ("yoso", "YOSO"), + ("zamba", "Zamba"), + ("zamba2", "Zamba2"), + ("zoedepth", "ZoeDepth"), + ] +) + +# This is tied to the processing `-` -> `_` in `model_type_to_module_name`. For example, instead of putting +# `transfo-xl` (as in `CONFIG_MAPPING_NAMES`), we should use `transfo_xl`. +DEPRECATED_MODELS = [ + "bort", + "deta", + "efficientformer", + "ernie_m", + "gptsan_japanese", + "graphormer", + "jukebox", + "mctct", + "mega", + "mmbt", + "nat", + "nezha", + "open_llama", + "qdqbert", + "realm", + "retribert", + "speech_to_text_2", + "tapex", + "trajectory_transformer", + "transfo_xl", + "tvlt", + "van", + "vit_hybrid", + "xlm_prophetnet", +] + +SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict( + [ + ("openai-gpt", "openai"), + ("data2vec-audio", "data2vec"), + ("data2vec-text", "data2vec"), + ("data2vec-vision", "data2vec"), + ("donut-swin", "donut"), + ("kosmos-2", "kosmos2"), + ("maskformer-swin", "maskformer"), + ("xclip", "x_clip"), + ("clip_vision_model", "clip"), + ("qwen2_audio_encoder", "qwen2_audio"), + ("clip_text_model", "clip"), + ("aria_text", "aria"), + ("gemma3_text", "gemma3"), + ("idefics3_vision", "idefics3"), + ("siglip_vision_model", "siglip"), + ("smolvlm_vision", "smolvlm"), + ("chinese_clip_vision_model", "chinese_clip"), + ("rt_detr_resnet", "rt_detr"), + ("granitevision", "llava_next"), + ] +) + + +def model_type_to_module_name(key): + """Converts a config key to the corresponding module.""" + # Special treatment + if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME: + key = SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key] + + if key in DEPRECATED_MODELS: + key = f"deprecated.{key}" + return key + + key = key.replace("-", "_") + if key in DEPRECATED_MODELS: + key = f"deprecated.{key}" + + return key + + +def config_class_to_model_type(config): + """Converts a config class name to the corresponding model type""" + for key, cls in CONFIG_MAPPING_NAMES.items(): + if cls == config: + return key + # if key not found check in extra content + for key, cls in CONFIG_MAPPING._extra_content.items(): + if cls.__name__ == config: + return key + return None + + +class _LazyConfigMapping(OrderedDict): + """ + A dictionary that lazily load its values when they are requested. + """ + + def __init__(self, mapping): + self._mapping = mapping + self._extra_content = {} + self._modules = {} + + def __getitem__(self, key): + if key in self._extra_content: + return self._extra_content[key] + if key not in self._mapping: + raise KeyError(key) + value = self._mapping[key] + module_name = model_type_to_module_name(key) + if module_name not in self._modules: + self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models") + if hasattr(self._modules[module_name], value): + return getattr(self._modules[module_name], value) + + # Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the + # object at the top level. + transformers_module = importlib.import_module("transformers") + return getattr(transformers_module, value) + + def keys(self): + return list(self._mapping.keys()) + list(self._extra_content.keys()) + + def values(self): + return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values()) + + def items(self): + return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items()) + + def __iter__(self): + return iter(list(self._mapping.keys()) + list(self._extra_content.keys())) + + def __contains__(self, item): + return item in self._mapping or item in self._extra_content + + def register(self, key, value, exist_ok=False): + """ + Register a new configuration in this mapping. + """ + if key in self._mapping.keys() and not exist_ok: + raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.") + self._extra_content[key] = value + + +CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES) + + +class _LazyLoadAllMappings(OrderedDict): + """ + A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values, + etc.) + + Args: + mapping: The mapping to load. + """ + + def __init__(self, mapping): + self._mapping = mapping + self._initialized = False + self._data = {} + + def _initialize(self): + if self._initialized: + return + + for model_type, map_name in self._mapping.items(): + module_name = model_type_to_module_name(model_type) + module = importlib.import_module(f".{module_name}", "transformers.models") + mapping = getattr(module, map_name) + self._data.update(mapping) + + self._initialized = True + + def __getitem__(self, key): + self._initialize() + return self._data[key] + + def keys(self): + self._initialize() + return self._data.keys() + + def values(self): + self._initialize() + return self._data.values() + + def items(self): + self._initialize() + return self._data.keys() + + def __iter__(self): + self._initialize() + return iter(self._data) + + def __contains__(self, item): + self._initialize() + return item in self._data + + +def _get_class_name(model_class: Union[str, List[str]]): + if isinstance(model_class, (list, tuple)): + return " or ".join([f"[`{c}`]" for c in model_class if c is not None]) + return f"[`{model_class}`]" + + +def _list_model_options(indent, config_to_class=None, use_model_types=True): + if config_to_class is None and not use_model_types: + raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.") + if use_model_types: + if config_to_class is None: + model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()} + else: + model_type_to_name = { + model_type: _get_class_name(model_class) + for model_type, model_class in config_to_class.items() + if model_type in MODEL_NAMES_MAPPING + } + lines = [ + f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)" + for model_type in sorted(model_type_to_name.keys()) + ] + else: + config_to_name = { + CONFIG_MAPPING_NAMES[config]: _get_class_name(clas) + for config, clas in config_to_class.items() + if config in CONFIG_MAPPING_NAMES + } + config_to_model_name = { + config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items() + } + lines = [ + f"{indent}- [`{config_name}`] configuration class:" + f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)" + for config_name in sorted(config_to_name.keys()) + ] + return "\n".join(lines) + + +def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True): + def docstring_decorator(fn): + docstrings = fn.__doc__ + if docstrings is None: + # Example: -OO + return fn + lines = docstrings.split("\n") + i = 0 + while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None: + i += 1 + if i < len(lines): + indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0] + if use_model_types: + indent = f"{indent} " + lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types) + docstrings = "\n".join(lines) + else: + raise ValueError( + f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current" + f" docstring is:\n{docstrings}" + ) + fn.__doc__ = docstrings + return fn + + return docstring_decorator + + +class AutoConfig: + r""" + This is a generic configuration class that will be instantiated as one of the configuration classes of the library + when created with the [`~AutoConfig.from_pretrained`] class method. + + This class cannot be instantiated directly using `__init__()` (throws an error). + """ + + def __init__(self): + raise EnvironmentError( + "AutoConfig is designed to be instantiated " + "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method." + ) + + @classmethod + def for_model(cls, model_type: str, *args, **kwargs): + if model_type in CONFIG_MAPPING: + config_class = CONFIG_MAPPING[model_type] + return config_class(*args, **kwargs) + raise ValueError( + f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}" + ) + + @classmethod + @replace_list_option_in_docstrings() + def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): + r""" + Instantiate one of the configuration classes of the library from a pretrained model configuration. + + The configuration class to instantiate is selected based on the `model_type` property of the config object that + is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`: + + List options + + Args: + pretrained_model_name_or_path (`str` or `os.PathLike`): + Can be either: + + - A string, the *model id* of a pretrained model configuration hosted inside a model repo on + huggingface.co. + - A path to a *directory* containing a configuration file saved using the + [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method, + e.g., `./my_model_directory/`. + - A path or url to a saved configuration JSON *file*, e.g., + `./my_model_directory/configuration.json`. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model configuration should be cached if the + standard cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force the (re-)download the model weights and configuration files and override the + cached versions if they exist. + resume_download: + Deprecated and ignored. All downloads are now resumed by default when possible. + Will be removed in v5 of Transformers. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + return_unused_kwargs (`bool`, *optional*, defaults to `False`): + If `False`, then this function returns just the final configuration object. + + If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a + dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the + part of `kwargs` which has not been used to update `config` and is otherwise ignored. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether or not to allow for custom models defined on the Hub in their own modeling files. This option + should only be set to `True` for repositories you trust and in which you have read the code, as it will + execute code present on the Hub on your local machine. + kwargs(additional keyword arguments, *optional*): + The values in kwargs of any keys which are configuration attributes will be used to override the loaded + values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled + by the `return_unused_kwargs` keyword parameter. + + Examples: + + ```python + >>> from transformers import AutoConfig + + >>> # Download configuration from huggingface.co and cache. + >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased") + + >>> # Download configuration from huggingface.co (user-uploaded) and cache. + >>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased") + + >>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*). + >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/") + + >>> # Load a specific configuration file. + >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json") + + >>> # Change some config attributes when loading a pretrained config. + >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False) + >>> config.output_attentions + True + + >>> config, unused_kwargs = AutoConfig.from_pretrained( + ... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True + ... ) + >>> config.output_attentions + True + + >>> unused_kwargs + {'foo': False} + ```""" + use_auth_token = kwargs.pop("use_auth_token", None) + if use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", + FutureWarning, + ) + if kwargs.get("token", None) is not None: + raise ValueError( + "`token` and `use_auth_token` are both specified. Please set only the argument `token`." + ) + kwargs["token"] = use_auth_token + + kwargs["_from_auto"] = True + kwargs["name_or_path"] = pretrained_model_name_or_path + trust_remote_code = kwargs.pop("trust_remote_code", None) + code_revision = kwargs.pop("code_revision", None) + + config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs) + has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"] + has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING + trust_remote_code = resolve_trust_remote_code( + trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code + ) + + if has_remote_code and trust_remote_code: + class_ref = config_dict["auto_map"]["AutoConfig"] + config_class = get_class_from_dynamic_module( + class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs + ) + if os.path.isdir(pretrained_model_name_or_path): + config_class.register_for_auto_class() + return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs) + elif "model_type" in config_dict: + try: + config_class = CONFIG_MAPPING[config_dict["model_type"]] + except KeyError: + raise ValueError( + f"The checkpoint you are trying to load has model type `{config_dict['model_type']}` " + "but Transformers does not recognize this architecture. This could be because of an " + "issue with the checkpoint, or because your version of Transformers is out of date.\n\n" + "You can update Transformers with the command `pip install --upgrade transformers`. If this " + "does not work, and the checkpoint is very new, then there may not be a release version " + "that supports this model yet. In this case, you can get the most up-to-date code by installing " + "Transformers from source with the command " + "`pip install git+https://github.com/huggingface/transformers.git`" + ) + return config_class.from_dict(config_dict, **unused_kwargs) + else: + # Fallback: use pattern matching on the string. + # We go from longer names to shorter names to catch roberta before bert (for instance) + for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True): + if pattern in str(pretrained_model_name_or_path): + return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs) + + raise ValueError( + f"Unrecognized model in {pretrained_model_name_or_path}. " + f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings " + f"in its name: {', '.join(CONFIG_MAPPING.keys())}" + ) + + @staticmethod + def register(model_type, config, exist_ok=False): + """ + Register a new configuration for this class. + + Args: + model_type (`str`): The model type like "bert" or "gpt". + config ([`PretrainedConfig`]): The config to register. + """ + if issubclass(config, PretrainedConfig) and config.model_type != model_type: + raise ValueError( + "The config you are passing has a `model_type` attribute that is not consistent with the model type " + f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they " + "match!" + ) + CONFIG_MAPPING.register(model_type, config, exist_ok=exist_ok) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/image_processing_auto.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/image_processing_auto.py new file mode 100644 index 0000000000000000000000000000000000000000..b1db2458397c745b61634c5c27451f57a04f251d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/image_processing_auto.py @@ -0,0 +1,636 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""AutoImageProcessor class.""" + +import importlib +import json +import os +import warnings +from collections import OrderedDict +from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union + +# Build the list of all image processors +from ...configuration_utils import PretrainedConfig +from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code +from ...image_processing_utils import BaseImageProcessor, ImageProcessingMixin +from ...image_processing_utils_fast import BaseImageProcessorFast +from ...utils import ( + CONFIG_NAME, + IMAGE_PROCESSOR_NAME, + cached_file, + is_timm_config_dict, + is_timm_local_checkpoint, + is_torchvision_available, + is_vision_available, + logging, +) +from .auto_factory import _LazyAutoMapping +from .configuration_auto import ( + CONFIG_MAPPING_NAMES, + AutoConfig, + model_type_to_module_name, + replace_list_option_in_docstrings, +) + + +logger = logging.get_logger(__name__) + + +if TYPE_CHECKING: + # This significantly improves completion suggestion performance when + # the transformers package is used with Microsoft's Pylance language server. + IMAGE_PROCESSOR_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict() +else: + IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict( + [ + ("align", ("EfficientNetImageProcessor",)), + ("aria", ("AriaImageProcessor")), + ("beit", ("BeitImageProcessor",)), + ("bit", ("BitImageProcessor",)), + ("blip", ("BlipImageProcessor", "BlipImageProcessorFast")), + ("blip-2", ("BlipImageProcessor", "BlipImageProcessorFast")), + ("bridgetower", ("BridgeTowerImageProcessor",)), + ("chameleon", ("ChameleonImageProcessor",)), + ("chinese_clip", ("ChineseCLIPImageProcessor",)), + ("clip", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("clipseg", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("conditional_detr", ("ConditionalDetrImageProcessor",)), + ("convnext", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("convnextv2", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("cvt", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("data2vec-vision", ("BeitImageProcessor",)), + ("deformable_detr", ("DeformableDetrImageProcessor", "DeformableDetrImageProcessorFast")), + ("deit", ("DeiTImageProcessor", "DeiTImageProcessorFast")), + ("depth_anything", ("DPTImageProcessor",)), + ("depth_pro", ("DepthProImageProcessor", "DepthProImageProcessorFast")), + ("deta", ("DetaImageProcessor",)), + ("detr", ("DetrImageProcessor", "DetrImageProcessorFast")), + ("dinat", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("dinov2", ("BitImageProcessor",)), + ("donut-swin", ("DonutImageProcessor",)), + ("dpt", ("DPTImageProcessor",)), + ("efficientformer", ("EfficientFormerImageProcessor",)), + ("efficientnet", ("EfficientNetImageProcessor",)), + ("flava", ("FlavaImageProcessor",)), + ("focalnet", ("BitImageProcessor",)), + ("fuyu", ("FuyuImageProcessor",)), + ("gemma3", ("Gemma3ImageProcessor", "Gemma3ImageProcessorFast")), + ("git", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("glpn", ("GLPNImageProcessor",)), + ("got_ocr2", ("GotOcr2ImageProcessor", "GotOcr2ImageProcessorFast")), + ("grounding-dino", ("GroundingDinoImageProcessor",)), + ("groupvit", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("hiera", ("BitImageProcessor",)), + ("idefics", ("IdeficsImageProcessor",)), + ("idefics2", ("Idefics2ImageProcessor",)), + ("idefics3", ("Idefics3ImageProcessor",)), + ("ijepa", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("imagegpt", ("ImageGPTImageProcessor",)), + ("instructblip", ("BlipImageProcessor", "BlipImageProcessorFast")), + ("instructblipvideo", ("InstructBlipVideoImageProcessor",)), + ("kosmos-2", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("layoutlmv2", ("LayoutLMv2ImageProcessor",)), + ("layoutlmv3", ("LayoutLMv3ImageProcessor",)), + ("levit", ("LevitImageProcessor",)), + ("llava", ("LlavaImageProcessor", "LlavaImageProcessorFast")), + ("llava_next", ("LlavaNextImageProcessor", "LlavaNextImageProcessorFast")), + ("llava_next_video", ("LlavaNextVideoImageProcessor",)), + ("llava_onevision", ("LlavaOnevisionImageProcessor", "LlavaOnevisionImageProcessorFast")), + ("mask2former", ("Mask2FormerImageProcessor",)), + ("maskformer", ("MaskFormerImageProcessor",)), + ("mgp-str", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("mistral3", ("PixtralImageProcessor", "PixtralImageProcessorFast")), + ("mllama", ("MllamaImageProcessor",)), + ("mobilenet_v1", ("MobileNetV1ImageProcessor",)), + ("mobilenet_v2", ("MobileNetV2ImageProcessor",)), + ("mobilevit", ("MobileViTImageProcessor",)), + ("mobilevitv2", ("MobileViTImageProcessor",)), + ("nat", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("nougat", ("NougatImageProcessor",)), + ("oneformer", ("OneFormerImageProcessor",)), + ("owlv2", ("Owlv2ImageProcessor",)), + ("owlvit", ("OwlViTImageProcessor",)), + ("paligemma", ("SiglipImageProcessor", "SiglipImageProcessorFast")), + ("perceiver", ("PerceiverImageProcessor",)), + ("pix2struct", ("Pix2StructImageProcessor",)), + ("pixtral", ("PixtralImageProcessor", "PixtralImageProcessorFast")), + ("poolformer", ("PoolFormerImageProcessor",)), + ("pvt", ("PvtImageProcessor",)), + ("pvt_v2", ("PvtImageProcessor",)), + ("qwen2_5_vl", ("Qwen2VLImageProcessor", "Qwen2VLImageProcessorFast")), + ("qwen2_vl", ("Qwen2VLImageProcessor", "Qwen2VLImageProcessorFast")), + ("regnet", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("resnet", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("rt_detr", ("RTDetrImageProcessor", "RTDetrImageProcessorFast")), + ("sam", ("SamImageProcessor",)), + ("segformer", ("SegformerImageProcessor",)), + ("seggpt", ("SegGptImageProcessor",)), + ("siglip", ("SiglipImageProcessor", "SiglipImageProcessorFast")), + ("siglip2", ("Siglip2ImageProcessor", "Siglip2ImageProcessorFast")), + ("superglue", "SuperGlueImageProcessor"), + ("swiftformer", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("swin", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("swin2sr", ("Swin2SRImageProcessor",)), + ("swinv2", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("table-transformer", ("DetrImageProcessor",)), + ("timesformer", ("VideoMAEImageProcessor",)), + ("timm_wrapper", ("TimmWrapperImageProcessor",)), + ("tvlt", ("TvltImageProcessor",)), + ("tvp", ("TvpImageProcessor",)), + ("udop", ("LayoutLMv3ImageProcessor",)), + ("upernet", ("SegformerImageProcessor",)), + ("van", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")), + ("videomae", ("VideoMAEImageProcessor",)), + ("vilt", ("ViltImageProcessor",)), + ("vipllava", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("vit", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("vit_hybrid", ("ViTHybridImageProcessor",)), + ("vit_mae", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("vit_msn", ("ViTImageProcessor", "ViTImageProcessorFast")), + ("vitmatte", ("VitMatteImageProcessor",)), + ("xclip", ("CLIPImageProcessor", "CLIPImageProcessorFast")), + ("yolos", ("YolosImageProcessor",)), + ("zoedepth", ("ZoeDepthImageProcessor",)), + ] + ) + +for model_type, image_processors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): + slow_image_processor_class, *fast_image_processor_class = image_processors + if not is_vision_available(): + slow_image_processor_class = None + + # If the fast image processor is not defined, or torchvision is not available, we set it to None + if not fast_image_processor_class or fast_image_processor_class[0] is None or not is_torchvision_available(): + fast_image_processor_class = None + else: + fast_image_processor_class = fast_image_processor_class[0] + + IMAGE_PROCESSOR_MAPPING_NAMES[model_type] = (slow_image_processor_class, fast_image_processor_class) + +IMAGE_PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) + + +def get_image_processor_class_from_name(class_name: str): + if class_name == "BaseImageProcessorFast": + return BaseImageProcessorFast + + for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): + if class_name in extractors: + module_name = model_type_to_module_name(module_name) + + module = importlib.import_module(f".{module_name}", "transformers.models") + try: + return getattr(module, class_name) + except AttributeError: + continue + + for _, extractors in IMAGE_PROCESSOR_MAPPING._extra_content.items(): + for extractor in extractors: + if getattr(extractor, "__name__", None) == class_name: + return extractor + + # We did not find the class, but maybe it's because a dep is missing. In that case, the class will be in the main + # init and we return the proper dummy to get an appropriate error message. + main_module = importlib.import_module("transformers") + if hasattr(main_module, class_name): + return getattr(main_module, class_name) + + return None + + +def get_image_processor_config( + pretrained_model_name_or_path: Union[str, os.PathLike], + cache_dir: Optional[Union[str, os.PathLike]] = None, + force_download: bool = False, + resume_download: Optional[bool] = None, + proxies: Optional[Dict[str, str]] = None, + token: Optional[Union[bool, str]] = None, + revision: Optional[str] = None, + local_files_only: bool = False, + **kwargs, +): + """ + Loads the image processor configuration from a pretrained model image processor configuration. + + Args: + pretrained_model_name_or_path (`str` or `os.PathLike`): + This can be either: + + - a string, the *model id* of a pretrained model configuration hosted inside a model repo on + huggingface.co. + - a path to a *directory* containing a configuration file saved using the + [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. + + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model configuration should be cached if the standard + cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the configuration files and override the cached versions if they + exist. + resume_download: + Deprecated and ignored. All downloads are now resumed by default when possible. + Will be removed in v5 of Transformers. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `huggingface-cli login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, will only try to load the image processor configuration from local files. + + + + Passing `token=True` is required when you want to use a private model. + + + + Returns: + `Dict`: The configuration of the image processor. + + Examples: + + ```python + # Download configuration from huggingface.co and cache. + image_processor_config = get_image_processor_config("google-bert/bert-base-uncased") + # This model does not have a image processor config so the result will be an empty dict. + image_processor_config = get_image_processor_config("FacebookAI/xlm-roberta-base") + + # Save a pretrained image processor locally and you can reload its config + from transformers import AutoTokenizer + + image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k") + image_processor.save_pretrained("image-processor-test") + image_processor_config = get_image_processor_config("image-processor-test") + ```""" + use_auth_token = kwargs.pop("use_auth_token", None) + if use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", + FutureWarning, + ) + if token is not None: + raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.") + token = use_auth_token + + resolved_config_file = cached_file( + pretrained_model_name_or_path, + IMAGE_PROCESSOR_NAME, + cache_dir=cache_dir, + force_download=force_download, + resume_download=resume_download, + proxies=proxies, + token=token, + revision=revision, + local_files_only=local_files_only, + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + if resolved_config_file is None: + logger.info( + "Could not locate the image processor configuration file, will try to use the model config instead." + ) + return {} + + with open(resolved_config_file, encoding="utf-8") as reader: + return json.load(reader) + + +def _warning_fast_image_processor_available(fast_class): + logger.warning( + f"Fast image processor class {fast_class} is available for this model. " + "Using slow image processor class. To use the fast image processor class set `use_fast=True`." + ) + + +class AutoImageProcessor: + r""" + This is a generic image processor class that will be instantiated as one of the image processor classes of the + library when created with the [`AutoImageProcessor.from_pretrained`] class method. + + This class cannot be instantiated directly using `__init__()` (throws an error). + """ + + def __init__(self): + raise EnvironmentError( + "AutoImageProcessor is designed to be instantiated " + "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method." + ) + + @classmethod + @replace_list_option_in_docstrings(IMAGE_PROCESSOR_MAPPING_NAMES) + def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): + r""" + Instantiate one of the image processor classes of the library from a pretrained model vocabulary. + + The image processor class to instantiate is selected based on the `model_type` property of the config object + (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's + missing, by falling back to using pattern matching on `pretrained_model_name_or_path`: + + List options + + Params: + pretrained_model_name_or_path (`str` or `os.PathLike`): + This can be either: + + - a string, the *model id* of a pretrained image_processor hosted inside a model repo on + huggingface.co. + - a path to a *directory* containing a image processor file saved using the + [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g., + `./my_model_directory/`. + - a path or url to a saved image processor JSON *file*, e.g., + `./my_model_directory/preprocessor_config.json`. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model image processor should be cached if the + standard cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the image processor files and override the cached versions if + they exist. + resume_download: + Deprecated and ignored. All downloads are now resumed by default when possible. + Will be removed in v5 of Transformers. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `huggingface-cli login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + use_fast (`bool`, *optional*, defaults to `False`): + Use a fast torchvision-base image processor if it is supported for a given model. + If a fast image processor is not available for a given model, a normal numpy-based image processor + is returned instead. + return_unused_kwargs (`bool`, *optional*, defaults to `False`): + If `False`, then this function returns just the final image processor object. If `True`, then this + functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary + consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of + `kwargs` which has not been used to update `image_processor` and is otherwise ignored. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether or not to allow for custom models defined on the Hub in their own modeling files. This option + should only be set to `True` for repositories you trust and in which you have read the code, as it will + execute code present on the Hub on your local machine. + image_processor_filename (`str`, *optional*, defaults to `"config.json"`): + The name of the file in the model directory to use for the image processor config. + kwargs (`Dict[str, Any]`, *optional*): + The values in kwargs of any keys which are image processor attributes will be used to override the + loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is + controlled by the `return_unused_kwargs` keyword parameter. + + + + Passing `token=True` is required when you want to use a private model. + + + + Examples: + + ```python + >>> from transformers import AutoImageProcessor + + >>> # Download image processor from huggingface.co and cache. + >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k") + + >>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*) + >>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/") + ```""" + use_auth_token = kwargs.pop("use_auth_token", None) + if use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", + FutureWarning, + ) + if kwargs.get("token", None) is not None: + raise ValueError( + "`token` and `use_auth_token` are both specified. Please set only the argument `token`." + ) + kwargs["token"] = use_auth_token + + config = kwargs.pop("config", None) + # TODO: @yoni, change in v4.48 (use_fast set to True by default) + use_fast = kwargs.pop("use_fast", None) + trust_remote_code = kwargs.pop("trust_remote_code", None) + kwargs["_from_auto"] = True + + # Resolve the image processor config filename + if "image_processor_filename" in kwargs: + image_processor_filename = kwargs.pop("image_processor_filename") + elif is_timm_local_checkpoint(pretrained_model_name_or_path): + image_processor_filename = CONFIG_NAME + else: + image_processor_filename = IMAGE_PROCESSOR_NAME + + # Load the image processor config + try: + # Main path for all transformers models and local TimmWrapper checkpoints + config_dict, _ = ImageProcessingMixin.get_image_processor_dict( + pretrained_model_name_or_path, image_processor_filename=image_processor_filename, **kwargs + ) + except Exception as initial_exception: + # Fallback path for Hub TimmWrapper checkpoints. Timm models' image processing is saved in `config.json` + # instead of `preprocessor_config.json`. Because this is an Auto class and we don't have any information + # except the model name, the only way to check if a remote checkpoint is a timm model is to try to + # load `config.json` and if it fails with some error, we raise the initial exception. + try: + config_dict, _ = ImageProcessingMixin.get_image_processor_dict( + pretrained_model_name_or_path, image_processor_filename=CONFIG_NAME, **kwargs + ) + except Exception: + raise initial_exception + + # In case we have a config_dict, but it's not a timm config dict, we raise the initial exception, + # because only timm models have image processing in `config.json`. + if not is_timm_config_dict(config_dict): + raise initial_exception + + image_processor_type = config_dict.get("image_processor_type", None) + image_processor_auto_map = None + if "AutoImageProcessor" in config_dict.get("auto_map", {}): + image_processor_auto_map = config_dict["auto_map"]["AutoImageProcessor"] + + # If we still don't have the image processor class, check if we're loading from a previous feature extractor config + # and if so, infer the image processor class from there. + if image_processor_type is None and image_processor_auto_map is None: + feature_extractor_class = config_dict.pop("feature_extractor_type", None) + if feature_extractor_class is not None: + image_processor_type = feature_extractor_class.replace("FeatureExtractor", "ImageProcessor") + if "AutoFeatureExtractor" in config_dict.get("auto_map", {}): + feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"] + image_processor_auto_map = feature_extractor_auto_map.replace("FeatureExtractor", "ImageProcessor") + + # If we don't find the image processor class in the image processor config, let's try the model config. + if image_processor_type is None and image_processor_auto_map is None: + if not isinstance(config, PretrainedConfig): + config = AutoConfig.from_pretrained( + pretrained_model_name_or_path, + trust_remote_code=trust_remote_code, + **kwargs, + ) + # It could be in `config.image_processor_type`` + image_processor_type = getattr(config, "image_processor_type", None) + if hasattr(config, "auto_map") and "AutoImageProcessor" in config.auto_map: + image_processor_auto_map = config.auto_map["AutoImageProcessor"] + + image_processor_class = None + # TODO: @yoni, change logic in v4.50 (when use_fast set to True by default) + if image_processor_type is not None: + # if use_fast is not set and the processor was saved with a fast processor, we use it, otherwise we use the slow processor. + if use_fast is None: + use_fast = image_processor_type.endswith("Fast") + if not use_fast: + logger.warning_once( + "Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. " + "`use_fast=True` will be the default behavior in v4.50, even if the model was saved with a slow processor. " + "This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`." + ) + # Update class name to reflect the use_fast option. If class is not found, we fall back to the slow version. + if use_fast and not is_torchvision_available(): + logger.warning_once( + "Using `use_fast=True` but `torchvision` is not available. Falling back to the slow image processor." + ) + use_fast = False + if use_fast: + if not image_processor_type.endswith("Fast"): + image_processor_type += "Fast" + for _, image_processors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): + if image_processor_type in image_processors: + break + else: + image_processor_type = image_processor_type[:-4] + use_fast = False + logger.warning_once( + "`use_fast` is set to `True` but the image processor class does not have a fast version. " + " Falling back to the slow version." + ) + image_processor_class = get_image_processor_class_from_name(image_processor_type) + else: + image_processor_type = ( + image_processor_type[:-4] if image_processor_type.endswith("Fast") else image_processor_type + ) + image_processor_class = get_image_processor_class_from_name(image_processor_type) + + has_remote_code = image_processor_auto_map is not None + has_local_code = image_processor_class is not None or type(config) in IMAGE_PROCESSOR_MAPPING + trust_remote_code = resolve_trust_remote_code( + trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code + ) + + if image_processor_auto_map is not None and not isinstance(image_processor_auto_map, tuple): + # In some configs, only the slow image processor class is stored + image_processor_auto_map = (image_processor_auto_map, None) + + if has_remote_code and trust_remote_code: + if not use_fast and image_processor_auto_map[1] is not None: + _warning_fast_image_processor_available(image_processor_auto_map[1]) + + if use_fast and image_processor_auto_map[1] is not None: + class_ref = image_processor_auto_map[1] + else: + class_ref = image_processor_auto_map[0] + image_processor_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs) + _ = kwargs.pop("code_revision", None) + if os.path.isdir(pretrained_model_name_or_path): + image_processor_class.register_for_auto_class() + return image_processor_class.from_dict(config_dict, **kwargs) + elif image_processor_class is not None: + return image_processor_class.from_dict(config_dict, **kwargs) + # Last try: we use the IMAGE_PROCESSOR_MAPPING. + elif type(config) in IMAGE_PROCESSOR_MAPPING: + image_processor_tuple = IMAGE_PROCESSOR_MAPPING[type(config)] + + image_processor_class_py, image_processor_class_fast = image_processor_tuple + + if not use_fast and image_processor_class_fast is not None: + _warning_fast_image_processor_available(image_processor_class_fast) + + if image_processor_class_fast and (use_fast or image_processor_class_py is None): + return image_processor_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) + else: + if image_processor_class_py is not None: + return image_processor_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) + else: + raise ValueError( + "This image processor cannot be instantiated. Please make sure you have `Pillow` installed." + ) + + raise ValueError( + f"Unrecognized image processor in {pretrained_model_name_or_path}. Should have a " + f"`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following " + f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}" + ) + + @staticmethod + def register( + config_class, + image_processor_class=None, + slow_image_processor_class=None, + fast_image_processor_class=None, + exist_ok=False, + ): + """ + Register a new image processor for this class. + + Args: + config_class ([`PretrainedConfig`]): + The configuration corresponding to the model to register. + image_processor_class ([`ImageProcessingMixin`]): The image processor to register. + """ + if image_processor_class is not None: + if slow_image_processor_class is not None: + raise ValueError("Cannot specify both image_processor_class and slow_image_processor_class") + warnings.warn( + "The image_processor_class argument is deprecated and will be removed in v4.42. Please use `slow_image_processor_class`, or `fast_image_processor_class` instead", + FutureWarning, + ) + slow_image_processor_class = image_processor_class + + if slow_image_processor_class is None and fast_image_processor_class is None: + raise ValueError("You need to specify either slow_image_processor_class or fast_image_processor_class") + if slow_image_processor_class is not None and issubclass(slow_image_processor_class, BaseImageProcessorFast): + raise ValueError("You passed a fast image processor in as the `slow_image_processor_class`.") + if fast_image_processor_class is not None and issubclass(fast_image_processor_class, BaseImageProcessor): + raise ValueError("You passed a slow image processor in as the `fast_image_processor_class`.") + + if ( + slow_image_processor_class is not None + and fast_image_processor_class is not None + and issubclass(fast_image_processor_class, BaseImageProcessorFast) + and fast_image_processor_class.slow_image_processor_class != slow_image_processor_class + ): + raise ValueError( + "The fast processor class you are passing has a `slow_image_processor_class` attribute that is not " + "consistent with the slow processor class you passed (fast tokenizer has " + f"{fast_image_processor_class.slow_image_processor_class} and you passed {slow_image_processor_class}. Fix one of those " + "so they match!" + ) + + # Avoid resetting a set slow/fast image processor if we are passing just the other ones. + if config_class in IMAGE_PROCESSOR_MAPPING._extra_content: + existing_slow, existing_fast = IMAGE_PROCESSOR_MAPPING[config_class] + if slow_image_processor_class is None: + slow_image_processor_class = existing_slow + if fast_image_processor_class is None: + fast_image_processor_class = existing_fast + + IMAGE_PROCESSOR_MAPPING.register( + config_class, (slow_image_processor_class, fast_image_processor_class), exist_ok=exist_ok + ) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/modeling_auto.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/modeling_auto.py new file mode 100644 index 0000000000000000000000000000000000000000..90dee0eb5805aa7c62a62bea27e76740a98fbacd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/modeling_auto.py @@ -0,0 +1,1926 @@ +# coding=utf-8 +# Copyright 2018 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Auto Model class.""" + +import warnings +from collections import OrderedDict + +from ...utils import logging +from .auto_factory import ( + _BaseAutoBackboneClass, + _BaseAutoModelClass, + _LazyAutoMapping, + auto_class_update, +) +from .configuration_auto import CONFIG_MAPPING_NAMES + + +logger = logging.get_logger(__name__) + +MODEL_MAPPING_NAMES = OrderedDict( + [ + # Base model mapping + ("albert", "AlbertModel"), + ("align", "AlignModel"), + ("altclip", "AltCLIPModel"), + ("aria", "AriaForConditionalGeneration"), + ("aria_text", "AriaTextModel"), + ("audio-spectrogram-transformer", "ASTModel"), + ("autoformer", "AutoformerModel"), + ("bamba", "BambaModel"), + ("bark", "BarkModel"), + ("bart", "BartModel"), + ("beit", "BeitModel"), + ("bert", "BertModel"), + ("bert-generation", "BertGenerationEncoder"), + ("big_bird", "BigBirdModel"), + ("bigbird_pegasus", "BigBirdPegasusModel"), + ("biogpt", "BioGptModel"), + ("bit", "BitModel"), + ("blenderbot", "BlenderbotModel"), + ("blenderbot-small", "BlenderbotSmallModel"), + ("blip", "BlipModel"), + ("blip-2", "Blip2Model"), + ("bloom", "BloomModel"), + ("bridgetower", "BridgeTowerModel"), + ("bros", "BrosModel"), + ("camembert", "CamembertModel"), + ("canine", "CanineModel"), + ("chameleon", "ChameleonModel"), + ("chinese_clip", "ChineseCLIPModel"), + ("chinese_clip_vision_model", "ChineseCLIPVisionModel"), + ("clap", "ClapModel"), + ("clip", "CLIPModel"), + ("clip_text_model", "CLIPTextModel"), + ("clip_vision_model", "CLIPVisionModel"), + ("clipseg", "CLIPSegModel"), + ("clvp", "ClvpModelForConditionalGeneration"), + ("code_llama", "LlamaModel"), + ("codegen", "CodeGenModel"), + ("cohere", "CohereModel"), + ("cohere2", "Cohere2Model"), + ("conditional_detr", "ConditionalDetrModel"), + ("convbert", "ConvBertModel"), + ("convnext", "ConvNextModel"), + ("convnextv2", "ConvNextV2Model"), + ("cpmant", "CpmAntModel"), + ("ctrl", "CTRLModel"), + ("cvt", "CvtModel"), + ("dab-detr", "DabDetrModel"), + ("dac", "DacModel"), + ("data2vec-audio", "Data2VecAudioModel"), + ("data2vec-text", "Data2VecTextModel"), + ("data2vec-vision", "Data2VecVisionModel"), + ("dbrx", "DbrxModel"), + ("deberta", "DebertaModel"), + ("deberta-v2", "DebertaV2Model"), + ("decision_transformer", "DecisionTransformerModel"), + ("deformable_detr", "DeformableDetrModel"), + ("deit", "DeiTModel"), + ("depth_pro", "DepthProModel"), + ("deta", "DetaModel"), + ("detr", "DetrModel"), + ("diffllama", "DiffLlamaModel"), + ("dinat", "DinatModel"), + ("dinov2", "Dinov2Model"), + ("dinov2_with_registers", "Dinov2WithRegistersModel"), + ("distilbert", "DistilBertModel"), + ("donut-swin", "DonutSwinModel"), + ("dpr", "DPRQuestionEncoder"), + ("dpt", "DPTModel"), + ("efficientformer", "EfficientFormerModel"), + ("efficientnet", "EfficientNetModel"), + ("electra", "ElectraModel"), + ("encodec", "EncodecModel"), + ("ernie", "ErnieModel"), + ("ernie_m", "ErnieMModel"), + ("esm", "EsmModel"), + ("falcon", "FalconModel"), + ("falcon_mamba", "FalconMambaModel"), + ("fastspeech2_conformer", "FastSpeech2ConformerModel"), + ("flaubert", "FlaubertModel"), + ("flava", "FlavaModel"), + ("fnet", "FNetModel"), + ("focalnet", "FocalNetModel"), + ("fsmt", "FSMTModel"), + ("funnel", ("FunnelModel", "FunnelBaseModel")), + ("gemma", "GemmaModel"), + ("gemma2", "Gemma2Model"), + ("gemma3_text", "Gemma3TextModel"), + ("git", "GitModel"), + ("glm", "GlmModel"), + ("glpn", "GLPNModel"), + ("got_ocr2", "GotOcr2ForConditionalGeneration"), + ("gpt-sw3", "GPT2Model"), + ("gpt2", "GPT2Model"), + ("gpt_bigcode", "GPTBigCodeModel"), + ("gpt_neo", "GPTNeoModel"), + ("gpt_neox", "GPTNeoXModel"), + ("gpt_neox_japanese", "GPTNeoXJapaneseModel"), + ("gptj", "GPTJModel"), + ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"), + ("granite", "GraniteModel"), + ("granitemoe", "GraniteMoeModel"), + ("granitemoeshared", "GraniteMoeSharedModel"), + ("graphormer", "GraphormerModel"), + ("grounding-dino", "GroundingDinoModel"), + ("groupvit", "GroupViTModel"), + ("helium", "HeliumModel"), + ("hiera", "HieraModel"), + ("hubert", "HubertModel"), + ("ibert", "IBertModel"), + ("idefics", "IdeficsModel"), + ("idefics2", "Idefics2Model"), + ("idefics3", "Idefics3Model"), + ("idefics3_vision", "Idefics3VisionTransformer"), + ("ijepa", "IJepaModel"), + ("imagegpt", "ImageGPTModel"), + ("informer", "InformerModel"), + ("jamba", "JambaModel"), + ("jetmoe", "JetMoeModel"), + ("jukebox", "JukeboxModel"), + ("kosmos-2", "Kosmos2Model"), + ("layoutlm", "LayoutLMModel"), + ("layoutlmv2", "LayoutLMv2Model"), + ("layoutlmv3", "LayoutLMv3Model"), + ("led", "LEDModel"), + ("levit", "LevitModel"), + ("lilt", "LiltModel"), + ("llama", "LlamaModel"), + ("longformer", "LongformerModel"), + ("longt5", "LongT5Model"), + ("luke", "LukeModel"), + ("lxmert", "LxmertModel"), + ("m2m_100", "M2M100Model"), + ("mamba", "MambaModel"), + ("mamba2", "Mamba2Model"), + ("marian", "MarianModel"), + ("markuplm", "MarkupLMModel"), + ("mask2former", "Mask2FormerModel"), + ("maskformer", "MaskFormerModel"), + ("maskformer-swin", "MaskFormerSwinModel"), + ("mbart", "MBartModel"), + ("mctct", "MCTCTModel"), + ("mega", "MegaModel"), + ("megatron-bert", "MegatronBertModel"), + ("mgp-str", "MgpstrForSceneTextRecognition"), + ("mimi", "MimiModel"), + ("mistral", "MistralModel"), + ("mixtral", "MixtralModel"), + ("mobilebert", "MobileBertModel"), + ("mobilenet_v1", "MobileNetV1Model"), + ("mobilenet_v2", "MobileNetV2Model"), + ("mobilevit", "MobileViTModel"), + ("mobilevitv2", "MobileViTV2Model"), + ("modernbert", "ModernBertModel"), + ("moonshine", "MoonshineModel"), + ("moshi", "MoshiModel"), + ("mpnet", "MPNetModel"), + ("mpt", "MptModel"), + ("mra", "MraModel"), + ("mt5", "MT5Model"), + ("musicgen", "MusicgenModel"), + ("musicgen_melody", "MusicgenMelodyModel"), + ("mvp", "MvpModel"), + ("nat", "NatModel"), + ("nemotron", "NemotronModel"), + ("nezha", "NezhaModel"), + ("nllb-moe", "NllbMoeModel"), + ("nystromformer", "NystromformerModel"), + ("olmo", "OlmoModel"), + ("olmo2", "Olmo2Model"), + ("olmoe", "OlmoeModel"), + ("omdet-turbo", "OmDetTurboForObjectDetection"), + ("oneformer", "OneFormerModel"), + ("open-llama", "OpenLlamaModel"), + ("openai-gpt", "OpenAIGPTModel"), + ("opt", "OPTModel"), + ("owlv2", "Owlv2Model"), + ("owlvit", "OwlViTModel"), + ("patchtsmixer", "PatchTSMixerModel"), + ("patchtst", "PatchTSTModel"), + ("pegasus", "PegasusModel"), + ("pegasus_x", "PegasusXModel"), + ("perceiver", "PerceiverModel"), + ("persimmon", "PersimmonModel"), + ("phi", "PhiModel"), + ("phi3", "Phi3Model"), + ("phimoe", "PhimoeModel"), + ("pixtral", "PixtralVisionModel"), + ("plbart", "PLBartModel"), + ("poolformer", "PoolFormerModel"), + ("prophetnet", "ProphetNetModel"), + ("pvt", "PvtModel"), + ("pvt_v2", "PvtV2Model"), + ("qdqbert", "QDQBertModel"), + ("qwen2", "Qwen2Model"), + ("qwen2_5_vl", "Qwen2_5_VLModel"), + ("qwen2_audio_encoder", "Qwen2AudioEncoder"), + ("qwen2_moe", "Qwen2MoeModel"), + ("qwen2_vl", "Qwen2VLModel"), + ("recurrent_gemma", "RecurrentGemmaModel"), + ("reformer", "ReformerModel"), + ("regnet", "RegNetModel"), + ("rembert", "RemBertModel"), + ("resnet", "ResNetModel"), + ("retribert", "RetriBertModel"), + ("roberta", "RobertaModel"), + ("roberta-prelayernorm", "RobertaPreLayerNormModel"), + ("roc_bert", "RoCBertModel"), + ("roformer", "RoFormerModel"), + ("rt_detr", "RTDetrModel"), + ("rt_detr_v2", "RTDetrV2Model"), + ("rwkv", "RwkvModel"), + ("sam", "SamModel"), + ("seamless_m4t", "SeamlessM4TModel"), + ("seamless_m4t_v2", "SeamlessM4Tv2Model"), + ("segformer", "SegformerModel"), + ("seggpt", "SegGptModel"), + ("sew", "SEWModel"), + ("sew-d", "SEWDModel"), + ("siglip", "SiglipModel"), + ("siglip2", "Siglip2Model"), + ("siglip_vision_model", "SiglipVisionModel"), + ("smolvlm", "SmolVLMModel"), + ("smolvlm_vision", "SmolVLMVisionTransformer"), + ("speech_to_text", "Speech2TextModel"), + ("speecht5", "SpeechT5Model"), + ("splinter", "SplinterModel"), + ("squeezebert", "SqueezeBertModel"), + ("stablelm", "StableLmModel"), + ("starcoder2", "Starcoder2Model"), + ("superglue", "SuperGlueForKeypointMatching"), + ("swiftformer", "SwiftFormerModel"), + ("swin", "SwinModel"), + ("swin2sr", "Swin2SRModel"), + ("swinv2", "Swinv2Model"), + ("switch_transformers", "SwitchTransformersModel"), + ("t5", "T5Model"), + ("table-transformer", "TableTransformerModel"), + ("tapas", "TapasModel"), + ("textnet", "TextNetModel"), + ("time_series_transformer", "TimeSeriesTransformerModel"), + ("timesformer", "TimesformerModel"), + ("timm_backbone", "TimmBackbone"), + ("timm_wrapper", "TimmWrapperModel"), + ("trajectory_transformer", "TrajectoryTransformerModel"), + ("transfo-xl", "TransfoXLModel"), + ("tvlt", "TvltModel"), + ("tvp", "TvpModel"), + ("udop", "UdopModel"), + ("umt5", "UMT5Model"), + ("unispeech", "UniSpeechModel"), + ("unispeech-sat", "UniSpeechSatModel"), + ("univnet", "UnivNetModel"), + ("van", "VanModel"), + ("videomae", "VideoMAEModel"), + ("vilt", "ViltModel"), + ("vision-text-dual-encoder", "VisionTextDualEncoderModel"), + ("visual_bert", "VisualBertModel"), + ("vit", "ViTModel"), + ("vit_hybrid", "ViTHybridModel"), + ("vit_mae", "ViTMAEModel"), + ("vit_msn", "ViTMSNModel"), + ("vitdet", "VitDetModel"), + ("vits", "VitsModel"), + ("vivit", "VivitModel"), + ("wav2vec2", "Wav2Vec2Model"), + ("wav2vec2-bert", "Wav2Vec2BertModel"), + ("wav2vec2-conformer", "Wav2Vec2ConformerModel"), + ("wavlm", "WavLMModel"), + ("whisper", "WhisperModel"), + ("xclip", "XCLIPModel"), + ("xglm", "XGLMModel"), + ("xlm", "XLMModel"), + ("xlm-prophetnet", "XLMProphetNetModel"), + ("xlm-roberta", "XLMRobertaModel"), + ("xlm-roberta-xl", "XLMRobertaXLModel"), + ("xlnet", "XLNetModel"), + ("xmod", "XmodModel"), + ("yolos", "YolosModel"), + ("yoso", "YosoModel"), + ("zamba", "ZambaModel"), + ("zamba2", "Zamba2Model"), + ] +) + +MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict( + [ + # Model for pre-training mapping + ("albert", "AlbertForPreTraining"), + ("bart", "BartForConditionalGeneration"), + ("bert", "BertForPreTraining"), + ("big_bird", "BigBirdForPreTraining"), + ("bloom", "BloomForCausalLM"), + ("camembert", "CamembertForMaskedLM"), + ("colpali", "ColPaliForRetrieval"), + ("ctrl", "CTRLLMHeadModel"), + ("data2vec-text", "Data2VecTextForMaskedLM"), + ("deberta", "DebertaForMaskedLM"), + ("deberta-v2", "DebertaV2ForMaskedLM"), + ("distilbert", "DistilBertForMaskedLM"), + ("electra", "ElectraForPreTraining"), + ("ernie", "ErnieForPreTraining"), + ("falcon_mamba", "FalconMambaForCausalLM"), + ("flaubert", "FlaubertWithLMHeadModel"), + ("flava", "FlavaForPreTraining"), + ("fnet", "FNetForPreTraining"), + ("fsmt", "FSMTForConditionalGeneration"), + ("funnel", "FunnelForPreTraining"), + ("gemma3", "Gemma3ForConditionalGeneration"), + ("gpt-sw3", "GPT2LMHeadModel"), + ("gpt2", "GPT2LMHeadModel"), + ("gpt_bigcode", "GPTBigCodeForCausalLM"), + ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"), + ("hiera", "HieraForPreTraining"), + ("ibert", "IBertForMaskedLM"), + ("idefics", "IdeficsForVisionText2Text"), + ("idefics2", "Idefics2ForConditionalGeneration"), + ("idefics3", "Idefics3ForConditionalGeneration"), + ("layoutlm", "LayoutLMForMaskedLM"), + ("llava", "LlavaForConditionalGeneration"), + ("llava_next", "LlavaNextForConditionalGeneration"), + ("llava_next_video", "LlavaNextVideoForConditionalGeneration"), + ("llava_onevision", "LlavaOnevisionForConditionalGeneration"), + ("longformer", "LongformerForMaskedLM"), + ("luke", "LukeForMaskedLM"), + ("lxmert", "LxmertForPreTraining"), + ("mamba", "MambaForCausalLM"), + ("mamba2", "Mamba2ForCausalLM"), + ("mega", "MegaForMaskedLM"), + ("megatron-bert", "MegatronBertForPreTraining"), + ("mistral3", "Mistral3ForConditionalGeneration"), + ("mllama", "MllamaForConditionalGeneration"), + ("mobilebert", "MobileBertForPreTraining"), + ("mpnet", "MPNetForMaskedLM"), + ("mpt", "MptForCausalLM"), + ("mra", "MraForMaskedLM"), + ("mvp", "MvpForConditionalGeneration"), + ("nezha", "NezhaForPreTraining"), + ("nllb-moe", "NllbMoeForConditionalGeneration"), + ("openai-gpt", "OpenAIGPTLMHeadModel"), + ("paligemma", "PaliGemmaForConditionalGeneration"), + ("qwen2_audio", "Qwen2AudioForConditionalGeneration"), + ("retribert", "RetriBertModel"), + ("roberta", "RobertaForMaskedLM"), + ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"), + ("roc_bert", "RoCBertForPreTraining"), + ("rwkv", "RwkvForCausalLM"), + ("splinter", "SplinterForPreTraining"), + ("squeezebert", "SqueezeBertForMaskedLM"), + ("switch_transformers", "SwitchTransformersForConditionalGeneration"), + ("t5", "T5ForConditionalGeneration"), + ("tapas", "TapasForMaskedLM"), + ("transfo-xl", "TransfoXLLMHeadModel"), + ("tvlt", "TvltForPreTraining"), + ("unispeech", "UniSpeechForPreTraining"), + ("unispeech-sat", "UniSpeechSatForPreTraining"), + ("video_llava", "VideoLlavaForConditionalGeneration"), + ("videomae", "VideoMAEForPreTraining"), + ("vipllava", "VipLlavaForConditionalGeneration"), + ("visual_bert", "VisualBertForPreTraining"), + ("vit_mae", "ViTMAEForPreTraining"), + ("wav2vec2", "Wav2Vec2ForPreTraining"), + ("wav2vec2-conformer", "Wav2Vec2ConformerForPreTraining"), + ("xlm", "XLMWithLMHeadModel"), + ("xlm-roberta", "XLMRobertaForMaskedLM"), + ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"), + ("xlnet", "XLNetLMHeadModel"), + ("xmod", "XmodForMaskedLM"), + ] +) + +MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict( + [ + # Model with LM heads mapping + ("albert", "AlbertForMaskedLM"), + ("bart", "BartForConditionalGeneration"), + ("bert", "BertForMaskedLM"), + ("big_bird", "BigBirdForMaskedLM"), + ("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"), + ("blenderbot-small", "BlenderbotSmallForConditionalGeneration"), + ("bloom", "BloomForCausalLM"), + ("camembert", "CamembertForMaskedLM"), + ("codegen", "CodeGenForCausalLM"), + ("convbert", "ConvBertForMaskedLM"), + ("cpmant", "CpmAntForCausalLM"), + ("ctrl", "CTRLLMHeadModel"), + ("data2vec-text", "Data2VecTextForMaskedLM"), + ("deberta", "DebertaForMaskedLM"), + ("deberta-v2", "DebertaV2ForMaskedLM"), + ("distilbert", "DistilBertForMaskedLM"), + ("electra", "ElectraForMaskedLM"), + ("encoder-decoder", "EncoderDecoderModel"), + ("ernie", "ErnieForMaskedLM"), + ("esm", "EsmForMaskedLM"), + ("falcon_mamba", "FalconMambaForCausalLM"), + ("flaubert", "FlaubertWithLMHeadModel"), + ("fnet", "FNetForMaskedLM"), + ("fsmt", "FSMTForConditionalGeneration"), + ("funnel", "FunnelForMaskedLM"), + ("git", "GitForCausalLM"), + ("gpt-sw3", "GPT2LMHeadModel"), + ("gpt2", "GPT2LMHeadModel"), + ("gpt_bigcode", "GPTBigCodeForCausalLM"), + ("gpt_neo", "GPTNeoForCausalLM"), + ("gpt_neox", "GPTNeoXForCausalLM"), + ("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"), + ("gptj", "GPTJForCausalLM"), + ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"), + ("ibert", "IBertForMaskedLM"), + ("layoutlm", "LayoutLMForMaskedLM"), + ("led", "LEDForConditionalGeneration"), + ("longformer", "LongformerForMaskedLM"), + ("longt5", "LongT5ForConditionalGeneration"), + ("luke", "LukeForMaskedLM"), + ("m2m_100", "M2M100ForConditionalGeneration"), + ("mamba", "MambaForCausalLM"), + ("mamba2", "Mamba2ForCausalLM"), + ("marian", "MarianMTModel"), + ("mega", "MegaForMaskedLM"), + ("megatron-bert", "MegatronBertForCausalLM"), + ("mobilebert", "MobileBertForMaskedLM"), + ("moonshine", "MoonshineForConditionalGeneration"), + ("mpnet", "MPNetForMaskedLM"), + ("mpt", "MptForCausalLM"), + ("mra", "MraForMaskedLM"), + ("mvp", "MvpForConditionalGeneration"), + ("nezha", "NezhaForMaskedLM"), + ("nllb-moe", "NllbMoeForConditionalGeneration"), + ("nystromformer", "NystromformerForMaskedLM"), + ("openai-gpt", "OpenAIGPTLMHeadModel"), + ("pegasus_x", "PegasusXForConditionalGeneration"), + ("plbart", "PLBartForConditionalGeneration"), + ("pop2piano", "Pop2PianoForConditionalGeneration"), + ("qdqbert", "QDQBertForMaskedLM"), + ("reformer", "ReformerModelWithLMHead"), + ("rembert", "RemBertForMaskedLM"), + ("roberta", "RobertaForMaskedLM"), + ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"), + ("roc_bert", "RoCBertForMaskedLM"), + ("roformer", "RoFormerForMaskedLM"), + ("rwkv", "RwkvForCausalLM"), + ("speech_to_text", "Speech2TextForConditionalGeneration"), + ("squeezebert", "SqueezeBertForMaskedLM"), + ("switch_transformers", "SwitchTransformersForConditionalGeneration"), + ("t5", "T5ForConditionalGeneration"), + ("tapas", "TapasForMaskedLM"), + ("transfo-xl", "TransfoXLLMHeadModel"), + ("wav2vec2", "Wav2Vec2ForMaskedLM"), + ("whisper", "WhisperForConditionalGeneration"), + ("xlm", "XLMWithLMHeadModel"), + ("xlm-roberta", "XLMRobertaForMaskedLM"), + ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"), + ("xlnet", "XLNetLMHeadModel"), + ("xmod", "XmodForMaskedLM"), + ("yoso", "YosoForMaskedLM"), + ] +) + +MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict( + [ + # Model for Causal LM mapping + ("aria_text", "AriaTextForCausalLM"), + ("bamba", "BambaForCausalLM"), + ("bart", "BartForCausalLM"), + ("bert", "BertLMHeadModel"), + ("bert-generation", "BertGenerationDecoder"), + ("big_bird", "BigBirdForCausalLM"), + ("bigbird_pegasus", "BigBirdPegasusForCausalLM"), + ("biogpt", "BioGptForCausalLM"), + ("blenderbot", "BlenderbotForCausalLM"), + ("blenderbot-small", "BlenderbotSmallForCausalLM"), + ("bloom", "BloomForCausalLM"), + ("camembert", "CamembertForCausalLM"), + ("code_llama", "LlamaForCausalLM"), + ("codegen", "CodeGenForCausalLM"), + ("cohere", "CohereForCausalLM"), + ("cohere2", "Cohere2ForCausalLM"), + ("cpmant", "CpmAntForCausalLM"), + ("ctrl", "CTRLLMHeadModel"), + ("data2vec-text", "Data2VecTextForCausalLM"), + ("dbrx", "DbrxForCausalLM"), + ("diffllama", "DiffLlamaForCausalLM"), + ("electra", "ElectraForCausalLM"), + ("emu3", "Emu3ForCausalLM"), + ("ernie", "ErnieForCausalLM"), + ("falcon", "FalconForCausalLM"), + ("falcon_mamba", "FalconMambaForCausalLM"), + ("fuyu", "FuyuForCausalLM"), + ("gemma", "GemmaForCausalLM"), + ("gemma2", "Gemma2ForCausalLM"), + ("gemma3", "Gemma3ForCausalLM"), + ("gemma3_text", "Gemma3ForCausalLM"), + ("git", "GitForCausalLM"), + ("glm", "GlmForCausalLM"), + ("got_ocr2", "GotOcr2ForConditionalGeneration"), + ("gpt-sw3", "GPT2LMHeadModel"), + ("gpt2", "GPT2LMHeadModel"), + ("gpt_bigcode", "GPTBigCodeForCausalLM"), + ("gpt_neo", "GPTNeoForCausalLM"), + ("gpt_neox", "GPTNeoXForCausalLM"), + ("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"), + ("gptj", "GPTJForCausalLM"), + ("granite", "GraniteForCausalLM"), + ("granitemoe", "GraniteMoeForCausalLM"), + ("granitemoeshared", "GraniteMoeSharedForCausalLM"), + ("helium", "HeliumForCausalLM"), + ("jamba", "JambaForCausalLM"), + ("jetmoe", "JetMoeForCausalLM"), + ("llama", "LlamaForCausalLM"), + ("mamba", "MambaForCausalLM"), + ("mamba2", "Mamba2ForCausalLM"), + ("marian", "MarianForCausalLM"), + ("mbart", "MBartForCausalLM"), + ("mega", "MegaForCausalLM"), + ("megatron-bert", "MegatronBertForCausalLM"), + ("mistral", "MistralForCausalLM"), + ("mixtral", "MixtralForCausalLM"), + ("mllama", "MllamaForCausalLM"), + ("moshi", "MoshiForCausalLM"), + ("mpt", "MptForCausalLM"), + ("musicgen", "MusicgenForCausalLM"), + ("musicgen_melody", "MusicgenMelodyForCausalLM"), + ("mvp", "MvpForCausalLM"), + ("nemotron", "NemotronForCausalLM"), + ("olmo", "OlmoForCausalLM"), + ("olmo2", "Olmo2ForCausalLM"), + ("olmoe", "OlmoeForCausalLM"), + ("open-llama", "OpenLlamaForCausalLM"), + ("openai-gpt", "OpenAIGPTLMHeadModel"), + ("opt", "OPTForCausalLM"), + ("pegasus", "PegasusForCausalLM"), + ("persimmon", "PersimmonForCausalLM"), + ("phi", "PhiForCausalLM"), + ("phi3", "Phi3ForCausalLM"), + ("phimoe", "PhimoeForCausalLM"), + ("plbart", "PLBartForCausalLM"), + ("prophetnet", "ProphetNetForCausalLM"), + ("qdqbert", "QDQBertLMHeadModel"), + ("qwen2", "Qwen2ForCausalLM"), + ("qwen2_moe", "Qwen2MoeForCausalLM"), + ("recurrent_gemma", "RecurrentGemmaForCausalLM"), + ("reformer", "ReformerModelWithLMHead"), + ("rembert", "RemBertForCausalLM"), + ("roberta", "RobertaForCausalLM"), + ("roberta-prelayernorm", "RobertaPreLayerNormForCausalLM"), + ("roc_bert", "RoCBertForCausalLM"), + ("roformer", "RoFormerForCausalLM"), + ("rwkv", "RwkvForCausalLM"), + ("speech_to_text_2", "Speech2Text2ForCausalLM"), + ("stablelm", "StableLmForCausalLM"), + ("starcoder2", "Starcoder2ForCausalLM"), + ("transfo-xl", "TransfoXLLMHeadModel"), + ("trocr", "TrOCRForCausalLM"), + ("whisper", "WhisperForCausalLM"), + ("xglm", "XGLMForCausalLM"), + ("xlm", "XLMWithLMHeadModel"), + ("xlm-prophetnet", "XLMProphetNetForCausalLM"), + ("xlm-roberta", "XLMRobertaForCausalLM"), + ("xlm-roberta-xl", "XLMRobertaXLForCausalLM"), + ("xlnet", "XLNetLMHeadModel"), + ("xmod", "XmodForCausalLM"), + ("zamba", "ZambaForCausalLM"), + ("zamba2", "Zamba2ForCausalLM"), + ] +) + +MODEL_FOR_IMAGE_MAPPING_NAMES = OrderedDict( + [ + # Model for Image mapping + ("beit", "BeitModel"), + ("bit", "BitModel"), + ("conditional_detr", "ConditionalDetrModel"), + ("convnext", "ConvNextModel"), + ("convnextv2", "ConvNextV2Model"), + ("dab-detr", "DabDetrModel"), + ("data2vec-vision", "Data2VecVisionModel"), + ("deformable_detr", "DeformableDetrModel"), + ("deit", "DeiTModel"), + ("depth_pro", "DepthProModel"), + ("deta", "DetaModel"), + ("detr", "DetrModel"), + ("dinat", "DinatModel"), + ("dinov2", "Dinov2Model"), + ("dinov2_with_registers", "Dinov2WithRegistersModel"), + ("dpt", "DPTModel"), + ("efficientformer", "EfficientFormerModel"), + ("efficientnet", "EfficientNetModel"), + ("focalnet", "FocalNetModel"), + ("glpn", "GLPNModel"), + ("hiera", "HieraModel"), + ("ijepa", "IJepaModel"), + ("imagegpt", "ImageGPTModel"), + ("levit", "LevitModel"), + ("mllama", "MllamaVisionModel"), + ("mobilenet_v1", "MobileNetV1Model"), + ("mobilenet_v2", "MobileNetV2Model"), + ("mobilevit", "MobileViTModel"), + ("mobilevitv2", "MobileViTV2Model"), + ("nat", "NatModel"), + ("poolformer", "PoolFormerModel"), + ("pvt", "PvtModel"), + ("regnet", "RegNetModel"), + ("resnet", "ResNetModel"), + ("segformer", "SegformerModel"), + ("siglip_vision_model", "SiglipVisionModel"), + ("swiftformer", "SwiftFormerModel"), + ("swin", "SwinModel"), + ("swin2sr", "Swin2SRModel"), + ("swinv2", "Swinv2Model"), + ("table-transformer", "TableTransformerModel"), + ("timesformer", "TimesformerModel"), + ("timm_backbone", "TimmBackbone"), + ("timm_wrapper", "TimmWrapperModel"), + ("van", "VanModel"), + ("videomae", "VideoMAEModel"), + ("vit", "ViTModel"), + ("vit_hybrid", "ViTHybridModel"), + ("vit_mae", "ViTMAEModel"), + ("vit_msn", "ViTMSNModel"), + ("vitdet", "VitDetModel"), + ("vivit", "VivitModel"), + ("yolos", "YolosModel"), + ] +) + +MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict( + [ + ("deit", "DeiTForMaskedImageModeling"), + ("focalnet", "FocalNetForMaskedImageModeling"), + ("swin", "SwinForMaskedImageModeling"), + ("swinv2", "Swinv2ForMaskedImageModeling"), + ("vit", "ViTForMaskedImageModeling"), + ] +) + + +MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES = OrderedDict( + # Model for Causal Image Modeling mapping + [ + ("imagegpt", "ImageGPTForCausalImageModeling"), + ] +) + +MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Image Classification mapping + ("beit", "BeitForImageClassification"), + ("bit", "BitForImageClassification"), + ("clip", "CLIPForImageClassification"), + ("convnext", "ConvNextForImageClassification"), + ("convnextv2", "ConvNextV2ForImageClassification"), + ("cvt", "CvtForImageClassification"), + ("data2vec-vision", "Data2VecVisionForImageClassification"), + ( + "deit", + ("DeiTForImageClassification", "DeiTForImageClassificationWithTeacher"), + ), + ("dinat", "DinatForImageClassification"), + ("dinov2", "Dinov2ForImageClassification"), + ("dinov2_with_registers", "Dinov2WithRegistersForImageClassification"), + ( + "efficientformer", + ( + "EfficientFormerForImageClassification", + "EfficientFormerForImageClassificationWithTeacher", + ), + ), + ("efficientnet", "EfficientNetForImageClassification"), + ("focalnet", "FocalNetForImageClassification"), + ("hiera", "HieraForImageClassification"), + ("ijepa", "IJepaForImageClassification"), + ("imagegpt", "ImageGPTForImageClassification"), + ( + "levit", + ("LevitForImageClassification", "LevitForImageClassificationWithTeacher"), + ), + ("mobilenet_v1", "MobileNetV1ForImageClassification"), + ("mobilenet_v2", "MobileNetV2ForImageClassification"), + ("mobilevit", "MobileViTForImageClassification"), + ("mobilevitv2", "MobileViTV2ForImageClassification"), + ("nat", "NatForImageClassification"), + ( + "perceiver", + ( + "PerceiverForImageClassificationLearned", + "PerceiverForImageClassificationFourier", + "PerceiverForImageClassificationConvProcessing", + ), + ), + ("poolformer", "PoolFormerForImageClassification"), + ("pvt", "PvtForImageClassification"), + ("pvt_v2", "PvtV2ForImageClassification"), + ("regnet", "RegNetForImageClassification"), + ("resnet", "ResNetForImageClassification"), + ("segformer", "SegformerForImageClassification"), + ("siglip", "SiglipForImageClassification"), + ("siglip2", "Siglip2ForImageClassification"), + ("swiftformer", "SwiftFormerForImageClassification"), + ("swin", "SwinForImageClassification"), + ("swinv2", "Swinv2ForImageClassification"), + ("textnet", "TextNetForImageClassification"), + ("timm_wrapper", "TimmWrapperForImageClassification"), + ("van", "VanForImageClassification"), + ("vit", "ViTForImageClassification"), + ("vit_hybrid", "ViTHybridForImageClassification"), + ("vit_msn", "ViTMSNForImageClassification"), + ] +) + +MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = OrderedDict( + [ + # Do not add new models here, this class will be deprecated in the future. + # Model for Image Segmentation mapping + ("detr", "DetrForSegmentation"), + ] +) + +MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Semantic Segmentation mapping + ("beit", "BeitForSemanticSegmentation"), + ("data2vec-vision", "Data2VecVisionForSemanticSegmentation"), + ("dpt", "DPTForSemanticSegmentation"), + ("mobilenet_v2", "MobileNetV2ForSemanticSegmentation"), + ("mobilevit", "MobileViTForSemanticSegmentation"), + ("mobilevitv2", "MobileViTV2ForSemanticSegmentation"), + ("segformer", "SegformerForSemanticSegmentation"), + ("upernet", "UperNetForSemanticSegmentation"), + ] +) + +MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Instance Segmentation mapping + # MaskFormerForInstanceSegmentation can be removed from this mapping in v5 + ("maskformer", "MaskFormerForInstanceSegmentation"), + ] +) + +MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Universal Segmentation mapping + ("detr", "DetrForSegmentation"), + ("mask2former", "Mask2FormerForUniversalSegmentation"), + ("maskformer", "MaskFormerForInstanceSegmentation"), + ("oneformer", "OneFormerForUniversalSegmentation"), + ] +) + +MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + ("timesformer", "TimesformerForVideoClassification"), + ("videomae", "VideoMAEForVideoClassification"), + ("vivit", "VivitForVideoClassification"), + ] +) + +MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict( + [ + ("blip", "BlipForConditionalGeneration"), + ("blip-2", "Blip2ForConditionalGeneration"), + ("chameleon", "ChameleonForConditionalGeneration"), + ("git", "GitForCausalLM"), + ("idefics2", "Idefics2ForConditionalGeneration"), + ("idefics3", "Idefics3ForConditionalGeneration"), + ("instructblip", "InstructBlipForConditionalGeneration"), + ("instructblipvideo", "InstructBlipVideoForConditionalGeneration"), + ("kosmos-2", "Kosmos2ForConditionalGeneration"), + ("llava", "LlavaForConditionalGeneration"), + ("llava_next", "LlavaNextForConditionalGeneration"), + ("llava_next_video", "LlavaNextVideoForConditionalGeneration"), + ("llava_onevision", "LlavaOnevisionForConditionalGeneration"), + ("mistral3", "Mistral3ForConditionalGeneration"), + ("mllama", "MllamaForConditionalGeneration"), + ("paligemma", "PaliGemmaForConditionalGeneration"), + ("pix2struct", "Pix2StructForConditionalGeneration"), + ("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"), + ("qwen2_vl", "Qwen2VLForConditionalGeneration"), + ("video_llava", "VideoLlavaForConditionalGeneration"), + ("vipllava", "VipLlavaForConditionalGeneration"), + ("vision-encoder-decoder", "VisionEncoderDecoderModel"), + ] +) + +MODEL_FOR_RETRIEVAL_MAPPING_NAMES = OrderedDict( + [ + ("colpali", "ColPaliForRetrieval"), + ] +) + +MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = OrderedDict( + [ + ("aria", "AriaForConditionalGeneration"), + ("aya_vision", "AyaVisionForConditionalGeneration"), + ("blip", "BlipForConditionalGeneration"), + ("blip-2", "Blip2ForConditionalGeneration"), + ("chameleon", "ChameleonForConditionalGeneration"), + ("emu3", "Emu3ForConditionalGeneration"), + ("fuyu", "FuyuForCausalLM"), + ("gemma3", "Gemma3ForConditionalGeneration"), + ("git", "GitForCausalLM"), + ("got_ocr2", "GotOcr2ForConditionalGeneration"), + ("idefics", "IdeficsForVisionText2Text"), + ("idefics2", "Idefics2ForConditionalGeneration"), + ("idefics3", "Idefics3ForConditionalGeneration"), + ("instructblip", "InstructBlipForConditionalGeneration"), + ("kosmos-2", "Kosmos2ForConditionalGeneration"), + ("llava", "LlavaForConditionalGeneration"), + ("llava_next", "LlavaNextForConditionalGeneration"), + ("llava_onevision", "LlavaOnevisionForConditionalGeneration"), + ("mistral3", "Mistral3ForConditionalGeneration"), + ("mllama", "MllamaForConditionalGeneration"), + ("paligemma", "PaliGemmaForConditionalGeneration"), + ("pix2struct", "Pix2StructForConditionalGeneration"), + ("pixtral", "LlavaForConditionalGeneration"), + ("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"), + ("qwen2_vl", "Qwen2VLForConditionalGeneration"), + ("smolvlm", "SmolVLMForConditionalGeneration"), + ("udop", "UdopForConditionalGeneration"), + ("vipllava", "VipLlavaForConditionalGeneration"), + ("vision-encoder-decoder", "VisionEncoderDecoderModel"), + ] +) + +MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict( + [ + # Model for Masked LM mapping + ("albert", "AlbertForMaskedLM"), + ("bart", "BartForConditionalGeneration"), + ("bert", "BertForMaskedLM"), + ("big_bird", "BigBirdForMaskedLM"), + ("camembert", "CamembertForMaskedLM"), + ("convbert", "ConvBertForMaskedLM"), + ("data2vec-text", "Data2VecTextForMaskedLM"), + ("deberta", "DebertaForMaskedLM"), + ("deberta-v2", "DebertaV2ForMaskedLM"), + ("distilbert", "DistilBertForMaskedLM"), + ("electra", "ElectraForMaskedLM"), + ("ernie", "ErnieForMaskedLM"), + ("esm", "EsmForMaskedLM"), + ("flaubert", "FlaubertWithLMHeadModel"), + ("fnet", "FNetForMaskedLM"), + ("funnel", "FunnelForMaskedLM"), + ("ibert", "IBertForMaskedLM"), + ("layoutlm", "LayoutLMForMaskedLM"), + ("longformer", "LongformerForMaskedLM"), + ("luke", "LukeForMaskedLM"), + ("mbart", "MBartForConditionalGeneration"), + ("mega", "MegaForMaskedLM"), + ("megatron-bert", "MegatronBertForMaskedLM"), + ("mobilebert", "MobileBertForMaskedLM"), + ("modernbert", "ModernBertForMaskedLM"), + ("mpnet", "MPNetForMaskedLM"), + ("mra", "MraForMaskedLM"), + ("mvp", "MvpForConditionalGeneration"), + ("nezha", "NezhaForMaskedLM"), + ("nystromformer", "NystromformerForMaskedLM"), + ("perceiver", "PerceiverForMaskedLM"), + ("qdqbert", "QDQBertForMaskedLM"), + ("reformer", "ReformerForMaskedLM"), + ("rembert", "RemBertForMaskedLM"), + ("roberta", "RobertaForMaskedLM"), + ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"), + ("roc_bert", "RoCBertForMaskedLM"), + ("roformer", "RoFormerForMaskedLM"), + ("squeezebert", "SqueezeBertForMaskedLM"), + ("tapas", "TapasForMaskedLM"), + ("wav2vec2", "Wav2Vec2ForMaskedLM"), + ("xlm", "XLMWithLMHeadModel"), + ("xlm-roberta", "XLMRobertaForMaskedLM"), + ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"), + ("xmod", "XmodForMaskedLM"), + ("yoso", "YosoForMaskedLM"), + ] +) + +MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict( + [ + # Model for Object Detection mapping + ("conditional_detr", "ConditionalDetrForObjectDetection"), + ("dab-detr", "DabDetrForObjectDetection"), + ("deformable_detr", "DeformableDetrForObjectDetection"), + ("deta", "DetaForObjectDetection"), + ("detr", "DetrForObjectDetection"), + ("rt_detr", "RTDetrForObjectDetection"), + ("rt_detr_v2", "RTDetrV2ForObjectDetection"), + ("table-transformer", "TableTransformerForObjectDetection"), + ("yolos", "YolosForObjectDetection"), + ] +) + +MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict( + [ + # Model for Zero Shot Object Detection mapping + ("grounding-dino", "GroundingDinoForObjectDetection"), + ("omdet-turbo", "OmDetTurboForObjectDetection"), + ("owlv2", "Owlv2ForObjectDetection"), + ("owlvit", "OwlViTForObjectDetection"), + ] +) + +MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = OrderedDict( + [ + # Model for depth estimation mapping + ("depth_anything", "DepthAnythingForDepthEstimation"), + ("depth_pro", "DepthProForDepthEstimation"), + ("dpt", "DPTForDepthEstimation"), + ("glpn", "GLPNForDepthEstimation"), + ("zoedepth", "ZoeDepthForDepthEstimation"), + ] +) +MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict( + [ + # Model for Seq2Seq Causal LM mapping + ("bart", "BartForConditionalGeneration"), + ("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"), + ("blenderbot", "BlenderbotForConditionalGeneration"), + ("blenderbot-small", "BlenderbotSmallForConditionalGeneration"), + ("encoder-decoder", "EncoderDecoderModel"), + ("fsmt", "FSMTForConditionalGeneration"), + ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"), + ("led", "LEDForConditionalGeneration"), + ("longt5", "LongT5ForConditionalGeneration"), + ("m2m_100", "M2M100ForConditionalGeneration"), + ("marian", "MarianMTModel"), + ("mbart", "MBartForConditionalGeneration"), + ("mt5", "MT5ForConditionalGeneration"), + ("mvp", "MvpForConditionalGeneration"), + ("nllb-moe", "NllbMoeForConditionalGeneration"), + ("pegasus", "PegasusForConditionalGeneration"), + ("pegasus_x", "PegasusXForConditionalGeneration"), + ("plbart", "PLBartForConditionalGeneration"), + ("prophetnet", "ProphetNetForConditionalGeneration"), + ("qwen2_audio", "Qwen2AudioForConditionalGeneration"), + ("seamless_m4t", "SeamlessM4TForTextToText"), + ("seamless_m4t_v2", "SeamlessM4Tv2ForTextToText"), + ("switch_transformers", "SwitchTransformersForConditionalGeneration"), + ("t5", "T5ForConditionalGeneration"), + ("umt5", "UMT5ForConditionalGeneration"), + ("xlm-prophetnet", "XLMProphetNetForConditionalGeneration"), + ] +) + +MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict( + [ + ("moonshine", "MoonshineForConditionalGeneration"), + ("pop2piano", "Pop2PianoForConditionalGeneration"), + ("seamless_m4t", "SeamlessM4TForSpeechToText"), + ("seamless_m4t_v2", "SeamlessM4Tv2ForSpeechToText"), + ("speech-encoder-decoder", "SpeechEncoderDecoderModel"), + ("speech_to_text", "Speech2TextForConditionalGeneration"), + ("speecht5", "SpeechT5ForSpeechToText"), + ("whisper", "WhisperForConditionalGeneration"), + ] +) + +MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Sequence Classification mapping + ("albert", "AlbertForSequenceClassification"), + ("bart", "BartForSequenceClassification"), + ("bert", "BertForSequenceClassification"), + ("big_bird", "BigBirdForSequenceClassification"), + ("bigbird_pegasus", "BigBirdPegasusForSequenceClassification"), + ("biogpt", "BioGptForSequenceClassification"), + ("bloom", "BloomForSequenceClassification"), + ("camembert", "CamembertForSequenceClassification"), + ("canine", "CanineForSequenceClassification"), + ("code_llama", "LlamaForSequenceClassification"), + ("convbert", "ConvBertForSequenceClassification"), + ("ctrl", "CTRLForSequenceClassification"), + ("data2vec-text", "Data2VecTextForSequenceClassification"), + ("deberta", "DebertaForSequenceClassification"), + ("deberta-v2", "DebertaV2ForSequenceClassification"), + ("diffllama", "DiffLlamaForSequenceClassification"), + ("distilbert", "DistilBertForSequenceClassification"), + ("electra", "ElectraForSequenceClassification"), + ("ernie", "ErnieForSequenceClassification"), + ("ernie_m", "ErnieMForSequenceClassification"), + ("esm", "EsmForSequenceClassification"), + ("falcon", "FalconForSequenceClassification"), + ("flaubert", "FlaubertForSequenceClassification"), + ("fnet", "FNetForSequenceClassification"), + ("funnel", "FunnelForSequenceClassification"), + ("gemma", "GemmaForSequenceClassification"), + ("gemma2", "Gemma2ForSequenceClassification"), + ("glm", "GlmForSequenceClassification"), + ("gpt-sw3", "GPT2ForSequenceClassification"), + ("gpt2", "GPT2ForSequenceClassification"), + ("gpt_bigcode", "GPTBigCodeForSequenceClassification"), + ("gpt_neo", "GPTNeoForSequenceClassification"), + ("gpt_neox", "GPTNeoXForSequenceClassification"), + ("gptj", "GPTJForSequenceClassification"), + ("helium", "HeliumForSequenceClassification"), + ("ibert", "IBertForSequenceClassification"), + ("jamba", "JambaForSequenceClassification"), + ("jetmoe", "JetMoeForSequenceClassification"), + ("layoutlm", "LayoutLMForSequenceClassification"), + ("layoutlmv2", "LayoutLMv2ForSequenceClassification"), + ("layoutlmv3", "LayoutLMv3ForSequenceClassification"), + ("led", "LEDForSequenceClassification"), + ("lilt", "LiltForSequenceClassification"), + ("llama", "LlamaForSequenceClassification"), + ("longformer", "LongformerForSequenceClassification"), + ("luke", "LukeForSequenceClassification"), + ("markuplm", "MarkupLMForSequenceClassification"), + ("mbart", "MBartForSequenceClassification"), + ("mega", "MegaForSequenceClassification"), + ("megatron-bert", "MegatronBertForSequenceClassification"), + ("mistral", "MistralForSequenceClassification"), + ("mixtral", "MixtralForSequenceClassification"), + ("mobilebert", "MobileBertForSequenceClassification"), + ("modernbert", "ModernBertForSequenceClassification"), + ("mpnet", "MPNetForSequenceClassification"), + ("mpt", "MptForSequenceClassification"), + ("mra", "MraForSequenceClassification"), + ("mt5", "MT5ForSequenceClassification"), + ("mvp", "MvpForSequenceClassification"), + ("nemotron", "NemotronForSequenceClassification"), + ("nezha", "NezhaForSequenceClassification"), + ("nystromformer", "NystromformerForSequenceClassification"), + ("open-llama", "OpenLlamaForSequenceClassification"), + ("openai-gpt", "OpenAIGPTForSequenceClassification"), + ("opt", "OPTForSequenceClassification"), + ("perceiver", "PerceiverForSequenceClassification"), + ("persimmon", "PersimmonForSequenceClassification"), + ("phi", "PhiForSequenceClassification"), + ("phi3", "Phi3ForSequenceClassification"), + ("phimoe", "PhimoeForSequenceClassification"), + ("plbart", "PLBartForSequenceClassification"), + ("qdqbert", "QDQBertForSequenceClassification"), + ("qwen2", "Qwen2ForSequenceClassification"), + ("qwen2_moe", "Qwen2MoeForSequenceClassification"), + ("reformer", "ReformerForSequenceClassification"), + ("rembert", "RemBertForSequenceClassification"), + ("roberta", "RobertaForSequenceClassification"), + ("roberta-prelayernorm", "RobertaPreLayerNormForSequenceClassification"), + ("roc_bert", "RoCBertForSequenceClassification"), + ("roformer", "RoFormerForSequenceClassification"), + ("squeezebert", "SqueezeBertForSequenceClassification"), + ("stablelm", "StableLmForSequenceClassification"), + ("starcoder2", "Starcoder2ForSequenceClassification"), + ("t5", "T5ForSequenceClassification"), + ("tapas", "TapasForSequenceClassification"), + ("transfo-xl", "TransfoXLForSequenceClassification"), + ("umt5", "UMT5ForSequenceClassification"), + ("xlm", "XLMForSequenceClassification"), + ("xlm-roberta", "XLMRobertaForSequenceClassification"), + ("xlm-roberta-xl", "XLMRobertaXLForSequenceClassification"), + ("xlnet", "XLNetForSequenceClassification"), + ("xmod", "XmodForSequenceClassification"), + ("yoso", "YosoForSequenceClassification"), + ("zamba", "ZambaForSequenceClassification"), + ("zamba2", "Zamba2ForSequenceClassification"), + ] +) + +MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict( + [ + # Model for Question Answering mapping + ("albert", "AlbertForQuestionAnswering"), + ("bart", "BartForQuestionAnswering"), + ("bert", "BertForQuestionAnswering"), + ("big_bird", "BigBirdForQuestionAnswering"), + ("bigbird_pegasus", "BigBirdPegasusForQuestionAnswering"), + ("bloom", "BloomForQuestionAnswering"), + ("camembert", "CamembertForQuestionAnswering"), + ("canine", "CanineForQuestionAnswering"), + ("convbert", "ConvBertForQuestionAnswering"), + ("data2vec-text", "Data2VecTextForQuestionAnswering"), + ("deberta", "DebertaForQuestionAnswering"), + ("deberta-v2", "DebertaV2ForQuestionAnswering"), + ("diffllama", "DiffLlamaForQuestionAnswering"), + ("distilbert", "DistilBertForQuestionAnswering"), + ("electra", "ElectraForQuestionAnswering"), + ("ernie", "ErnieForQuestionAnswering"), + ("ernie_m", "ErnieMForQuestionAnswering"), + ("falcon", "FalconForQuestionAnswering"), + ("flaubert", "FlaubertForQuestionAnsweringSimple"), + ("fnet", "FNetForQuestionAnswering"), + ("funnel", "FunnelForQuestionAnswering"), + ("gpt2", "GPT2ForQuestionAnswering"), + ("gpt_neo", "GPTNeoForQuestionAnswering"), + ("gpt_neox", "GPTNeoXForQuestionAnswering"), + ("gptj", "GPTJForQuestionAnswering"), + ("ibert", "IBertForQuestionAnswering"), + ("layoutlmv2", "LayoutLMv2ForQuestionAnswering"), + ("layoutlmv3", "LayoutLMv3ForQuestionAnswering"), + ("led", "LEDForQuestionAnswering"), + ("lilt", "LiltForQuestionAnswering"), + ("llama", "LlamaForQuestionAnswering"), + ("longformer", "LongformerForQuestionAnswering"), + ("luke", "LukeForQuestionAnswering"), + ("lxmert", "LxmertForQuestionAnswering"), + ("markuplm", "MarkupLMForQuestionAnswering"), + ("mbart", "MBartForQuestionAnswering"), + ("mega", "MegaForQuestionAnswering"), + ("megatron-bert", "MegatronBertForQuestionAnswering"), + ("mistral", "MistralForQuestionAnswering"), + ("mixtral", "MixtralForQuestionAnswering"), + ("mobilebert", "MobileBertForQuestionAnswering"), + ("mpnet", "MPNetForQuestionAnswering"), + ("mpt", "MptForQuestionAnswering"), + ("mra", "MraForQuestionAnswering"), + ("mt5", "MT5ForQuestionAnswering"), + ("mvp", "MvpForQuestionAnswering"), + ("nemotron", "NemotronForQuestionAnswering"), + ("nezha", "NezhaForQuestionAnswering"), + ("nystromformer", "NystromformerForQuestionAnswering"), + ("opt", "OPTForQuestionAnswering"), + ("qdqbert", "QDQBertForQuestionAnswering"), + ("qwen2", "Qwen2ForQuestionAnswering"), + ("qwen2_moe", "Qwen2MoeForQuestionAnswering"), + ("reformer", "ReformerForQuestionAnswering"), + ("rembert", "RemBertForQuestionAnswering"), + ("roberta", "RobertaForQuestionAnswering"), + ("roberta-prelayernorm", "RobertaPreLayerNormForQuestionAnswering"), + ("roc_bert", "RoCBertForQuestionAnswering"), + ("roformer", "RoFormerForQuestionAnswering"), + ("splinter", "SplinterForQuestionAnswering"), + ("squeezebert", "SqueezeBertForQuestionAnswering"), + ("t5", "T5ForQuestionAnswering"), + ("umt5", "UMT5ForQuestionAnswering"), + ("xlm", "XLMForQuestionAnsweringSimple"), + ("xlm-roberta", "XLMRobertaForQuestionAnswering"), + ("xlm-roberta-xl", "XLMRobertaXLForQuestionAnswering"), + ("xlnet", "XLNetForQuestionAnsweringSimple"), + ("xmod", "XmodForQuestionAnswering"), + ("yoso", "YosoForQuestionAnswering"), + ] +) + +MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict( + [ + # Model for Table Question Answering mapping + ("tapas", "TapasForQuestionAnswering"), + ] +) + +MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict( + [ + ("blip", "BlipForQuestionAnswering"), + ("blip-2", "Blip2ForConditionalGeneration"), + ("vilt", "ViltForQuestionAnswering"), + ] +) + +MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict( + [ + ("layoutlm", "LayoutLMForQuestionAnswering"), + ("layoutlmv2", "LayoutLMv2ForQuestionAnswering"), + ("layoutlmv3", "LayoutLMv3ForQuestionAnswering"), + ] +) + +MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Token Classification mapping + ("albert", "AlbertForTokenClassification"), + ("bert", "BertForTokenClassification"), + ("big_bird", "BigBirdForTokenClassification"), + ("biogpt", "BioGptForTokenClassification"), + ("bloom", "BloomForTokenClassification"), + ("bros", "BrosForTokenClassification"), + ("camembert", "CamembertForTokenClassification"), + ("canine", "CanineForTokenClassification"), + ("convbert", "ConvBertForTokenClassification"), + ("data2vec-text", "Data2VecTextForTokenClassification"), + ("deberta", "DebertaForTokenClassification"), + ("deberta-v2", "DebertaV2ForTokenClassification"), + ("diffllama", "DiffLlamaForTokenClassification"), + ("distilbert", "DistilBertForTokenClassification"), + ("electra", "ElectraForTokenClassification"), + ("ernie", "ErnieForTokenClassification"), + ("ernie_m", "ErnieMForTokenClassification"), + ("esm", "EsmForTokenClassification"), + ("falcon", "FalconForTokenClassification"), + ("flaubert", "FlaubertForTokenClassification"), + ("fnet", "FNetForTokenClassification"), + ("funnel", "FunnelForTokenClassification"), + ("gemma", "GemmaForTokenClassification"), + ("gemma2", "Gemma2ForTokenClassification"), + ("glm", "GlmForTokenClassification"), + ("gpt-sw3", "GPT2ForTokenClassification"), + ("gpt2", "GPT2ForTokenClassification"), + ("gpt_bigcode", "GPTBigCodeForTokenClassification"), + ("gpt_neo", "GPTNeoForTokenClassification"), + ("gpt_neox", "GPTNeoXForTokenClassification"), + ("helium", "HeliumForTokenClassification"), + ("ibert", "IBertForTokenClassification"), + ("layoutlm", "LayoutLMForTokenClassification"), + ("layoutlmv2", "LayoutLMv2ForTokenClassification"), + ("layoutlmv3", "LayoutLMv3ForTokenClassification"), + ("lilt", "LiltForTokenClassification"), + ("llama", "LlamaForTokenClassification"), + ("longformer", "LongformerForTokenClassification"), + ("luke", "LukeForTokenClassification"), + ("markuplm", "MarkupLMForTokenClassification"), + ("mega", "MegaForTokenClassification"), + ("megatron-bert", "MegatronBertForTokenClassification"), + ("mistral", "MistralForTokenClassification"), + ("mixtral", "MixtralForTokenClassification"), + ("mobilebert", "MobileBertForTokenClassification"), + ("modernbert", "ModernBertForTokenClassification"), + ("mpnet", "MPNetForTokenClassification"), + ("mpt", "MptForTokenClassification"), + ("mra", "MraForTokenClassification"), + ("mt5", "MT5ForTokenClassification"), + ("nemotron", "NemotronForTokenClassification"), + ("nezha", "NezhaForTokenClassification"), + ("nystromformer", "NystromformerForTokenClassification"), + ("persimmon", "PersimmonForTokenClassification"), + ("phi", "PhiForTokenClassification"), + ("phi3", "Phi3ForTokenClassification"), + ("qdqbert", "QDQBertForTokenClassification"), + ("qwen2", "Qwen2ForTokenClassification"), + ("qwen2_moe", "Qwen2MoeForTokenClassification"), + ("rembert", "RemBertForTokenClassification"), + ("roberta", "RobertaForTokenClassification"), + ("roberta-prelayernorm", "RobertaPreLayerNormForTokenClassification"), + ("roc_bert", "RoCBertForTokenClassification"), + ("roformer", "RoFormerForTokenClassification"), + ("squeezebert", "SqueezeBertForTokenClassification"), + ("stablelm", "StableLmForTokenClassification"), + ("starcoder2", "Starcoder2ForTokenClassification"), + ("t5", "T5ForTokenClassification"), + ("umt5", "UMT5ForTokenClassification"), + ("xlm", "XLMForTokenClassification"), + ("xlm-roberta", "XLMRobertaForTokenClassification"), + ("xlm-roberta-xl", "XLMRobertaXLForTokenClassification"), + ("xlnet", "XLNetForTokenClassification"), + ("xmod", "XmodForTokenClassification"), + ("yoso", "YosoForTokenClassification"), + ] +) + +MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict( + [ + # Model for Multiple Choice mapping + ("albert", "AlbertForMultipleChoice"), + ("bert", "BertForMultipleChoice"), + ("big_bird", "BigBirdForMultipleChoice"), + ("camembert", "CamembertForMultipleChoice"), + ("canine", "CanineForMultipleChoice"), + ("convbert", "ConvBertForMultipleChoice"), + ("data2vec-text", "Data2VecTextForMultipleChoice"), + ("deberta-v2", "DebertaV2ForMultipleChoice"), + ("distilbert", "DistilBertForMultipleChoice"), + ("electra", "ElectraForMultipleChoice"), + ("ernie", "ErnieForMultipleChoice"), + ("ernie_m", "ErnieMForMultipleChoice"), + ("flaubert", "FlaubertForMultipleChoice"), + ("fnet", "FNetForMultipleChoice"), + ("funnel", "FunnelForMultipleChoice"), + ("ibert", "IBertForMultipleChoice"), + ("longformer", "LongformerForMultipleChoice"), + ("luke", "LukeForMultipleChoice"), + ("mega", "MegaForMultipleChoice"), + ("megatron-bert", "MegatronBertForMultipleChoice"), + ("mobilebert", "MobileBertForMultipleChoice"), + ("mpnet", "MPNetForMultipleChoice"), + ("mra", "MraForMultipleChoice"), + ("nezha", "NezhaForMultipleChoice"), + ("nystromformer", "NystromformerForMultipleChoice"), + ("qdqbert", "QDQBertForMultipleChoice"), + ("rembert", "RemBertForMultipleChoice"), + ("roberta", "RobertaForMultipleChoice"), + ("roberta-prelayernorm", "RobertaPreLayerNormForMultipleChoice"), + ("roc_bert", "RoCBertForMultipleChoice"), + ("roformer", "RoFormerForMultipleChoice"), + ("squeezebert", "SqueezeBertForMultipleChoice"), + ("xlm", "XLMForMultipleChoice"), + ("xlm-roberta", "XLMRobertaForMultipleChoice"), + ("xlm-roberta-xl", "XLMRobertaXLForMultipleChoice"), + ("xlnet", "XLNetForMultipleChoice"), + ("xmod", "XmodForMultipleChoice"), + ("yoso", "YosoForMultipleChoice"), + ] +) + +MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict( + [ + ("bert", "BertForNextSentencePrediction"), + ("ernie", "ErnieForNextSentencePrediction"), + ("fnet", "FNetForNextSentencePrediction"), + ("megatron-bert", "MegatronBertForNextSentencePrediction"), + ("mobilebert", "MobileBertForNextSentencePrediction"), + ("nezha", "NezhaForNextSentencePrediction"), + ("qdqbert", "QDQBertForNextSentencePrediction"), + ] +) + +MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Audio Classification mapping + ("audio-spectrogram-transformer", "ASTForAudioClassification"), + ("data2vec-audio", "Data2VecAudioForSequenceClassification"), + ("hubert", "HubertForSequenceClassification"), + ("sew", "SEWForSequenceClassification"), + ("sew-d", "SEWDForSequenceClassification"), + ("unispeech", "UniSpeechForSequenceClassification"), + ("unispeech-sat", "UniSpeechSatForSequenceClassification"), + ("wav2vec2", "Wav2Vec2ForSequenceClassification"), + ("wav2vec2-bert", "Wav2Vec2BertForSequenceClassification"), + ("wav2vec2-conformer", "Wav2Vec2ConformerForSequenceClassification"), + ("wavlm", "WavLMForSequenceClassification"), + ("whisper", "WhisperForAudioClassification"), + ] +) + +MODEL_FOR_CTC_MAPPING_NAMES = OrderedDict( + [ + # Model for Connectionist temporal classification (CTC) mapping + ("data2vec-audio", "Data2VecAudioForCTC"), + ("hubert", "HubertForCTC"), + ("mctct", "MCTCTForCTC"), + ("sew", "SEWForCTC"), + ("sew-d", "SEWDForCTC"), + ("unispeech", "UniSpeechForCTC"), + ("unispeech-sat", "UniSpeechSatForCTC"), + ("wav2vec2", "Wav2Vec2ForCTC"), + ("wav2vec2-bert", "Wav2Vec2BertForCTC"), + ("wav2vec2-conformer", "Wav2Vec2ConformerForCTC"), + ("wavlm", "WavLMForCTC"), + ] +) + +MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Audio Classification mapping + ("data2vec-audio", "Data2VecAudioForAudioFrameClassification"), + ("unispeech-sat", "UniSpeechSatForAudioFrameClassification"), + ("wav2vec2", "Wav2Vec2ForAudioFrameClassification"), + ("wav2vec2-bert", "Wav2Vec2BertForAudioFrameClassification"), + ("wav2vec2-conformer", "Wav2Vec2ConformerForAudioFrameClassification"), + ("wavlm", "WavLMForAudioFrameClassification"), + ] +) + +MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = OrderedDict( + [ + # Model for Audio Classification mapping + ("data2vec-audio", "Data2VecAudioForXVector"), + ("unispeech-sat", "UniSpeechSatForXVector"), + ("wav2vec2", "Wav2Vec2ForXVector"), + ("wav2vec2-bert", "Wav2Vec2BertForXVector"), + ("wav2vec2-conformer", "Wav2Vec2ConformerForXVector"), + ("wavlm", "WavLMForXVector"), + ] +) + +MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = OrderedDict( + [ + # Model for Text-To-Spectrogram mapping + ("fastspeech2_conformer", "FastSpeech2ConformerModel"), + ("speecht5", "SpeechT5ForTextToSpeech"), + ] +) + +MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = OrderedDict( + [ + # Model for Text-To-Waveform mapping + ("bark", "BarkModel"), + ("fastspeech2_conformer", "FastSpeech2ConformerWithHifiGan"), + ("musicgen", "MusicgenForConditionalGeneration"), + ("musicgen_melody", "MusicgenMelodyForConditionalGeneration"), + ("seamless_m4t", "SeamlessM4TForTextToSpeech"), + ("seamless_m4t_v2", "SeamlessM4Tv2ForTextToSpeech"), + ("vits", "VitsModel"), + ] +) + +MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + # Model for Zero Shot Image Classification mapping + ("align", "AlignModel"), + ("altclip", "AltCLIPModel"), + ("blip", "BlipModel"), + ("blip-2", "Blip2ForImageTextRetrieval"), + ("chinese_clip", "ChineseCLIPModel"), + ("clip", "CLIPModel"), + ("clipseg", "CLIPSegModel"), + ("siglip", "SiglipModel"), + ("siglip2", "Siglip2Model"), + ] +) + +MODEL_FOR_BACKBONE_MAPPING_NAMES = OrderedDict( + [ + # Backbone mapping + ("beit", "BeitBackbone"), + ("bit", "BitBackbone"), + ("convnext", "ConvNextBackbone"), + ("convnextv2", "ConvNextV2Backbone"), + ("dinat", "DinatBackbone"), + ("dinov2", "Dinov2Backbone"), + ("dinov2_with_registers", "Dinov2WithRegistersBackbone"), + ("focalnet", "FocalNetBackbone"), + ("hiera", "HieraBackbone"), + ("maskformer-swin", "MaskFormerSwinBackbone"), + ("nat", "NatBackbone"), + ("pvt_v2", "PvtV2Backbone"), + ("resnet", "ResNetBackbone"), + ("rt_detr_resnet", "RTDetrResNetBackbone"), + ("swin", "SwinBackbone"), + ("swinv2", "Swinv2Backbone"), + ("textnet", "TextNetBackbone"), + ("timm_backbone", "TimmBackbone"), + ("vitdet", "VitDetBackbone"), + ("vitpose_backbone", "VitPoseBackbone"), + ] +) + +MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = OrderedDict( + [ + ("sam", "SamModel"), + ] +) + + +MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES = OrderedDict( + [ + ("superpoint", "SuperPointForKeypointDetection"), + ] +) + + +MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES = OrderedDict( + [ + ("albert", "AlbertModel"), + ("bert", "BertModel"), + ("big_bird", "BigBirdModel"), + ("clip_text_model", "CLIPTextModel"), + ("data2vec-text", "Data2VecTextModel"), + ("deberta", "DebertaModel"), + ("deberta-v2", "DebertaV2Model"), + ("distilbert", "DistilBertModel"), + ("electra", "ElectraModel"), + ("emu3", "Emu3TextModel"), + ("flaubert", "FlaubertModel"), + ("ibert", "IBertModel"), + ("longformer", "LongformerModel"), + ("mllama", "MllamaTextModel"), + ("mobilebert", "MobileBertModel"), + ("mt5", "MT5EncoderModel"), + ("nystromformer", "NystromformerModel"), + ("reformer", "ReformerModel"), + ("rembert", "RemBertModel"), + ("roberta", "RobertaModel"), + ("roberta-prelayernorm", "RobertaPreLayerNormModel"), + ("roc_bert", "RoCBertModel"), + ("roformer", "RoFormerModel"), + ("squeezebert", "SqueezeBertModel"), + ("t5", "T5EncoderModel"), + ("umt5", "UMT5EncoderModel"), + ("xlm", "XLMModel"), + ("xlm-roberta", "XLMRobertaModel"), + ("xlm-roberta-xl", "XLMRobertaXLModel"), + ] +) + +MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES = OrderedDict( + [ + ("patchtsmixer", "PatchTSMixerForTimeSeriesClassification"), + ("patchtst", "PatchTSTForClassification"), + ] +) + +MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES = OrderedDict( + [ + ("patchtsmixer", "PatchTSMixerForRegression"), + ("patchtst", "PatchTSTForRegression"), + ] +) + +MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = OrderedDict( + [ + ("swin2sr", "Swin2SRForImageSuperResolution"), + ] +) + +MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_MAPPING_NAMES) +MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_PRETRAINING_MAPPING_NAMES) +MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES) +MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) +MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES +) +MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES +) +MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES +) +MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES +) +MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES +) +MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) +MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES +) +MODEL_FOR_RETRIEVAL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_RETRIEVAL_MAPPING_NAMES) +MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES +) +MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES +) +MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES) +MODEL_FOR_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_MAPPING_NAMES) +MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES +) +MODEL_FOR_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES) +MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES +) +MODEL_FOR_DEPTH_ESTIMATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES) +MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES +) +MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES +) +MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES +) +MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES) +MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES +) +MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_CTC_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES) +MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES) +MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES +) +MODEL_FOR_AUDIO_XVECTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES) + +MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES +) + +MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES) + +MODEL_FOR_BACKBONE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_BACKBONE_MAPPING_NAMES) + +MODEL_FOR_MASK_GENERATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES) + +MODEL_FOR_KEYPOINT_DETECTION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES +) + +MODEL_FOR_TEXT_ENCODING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES) + +MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES +) + +MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING = _LazyAutoMapping( + CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES +) + +MODEL_FOR_IMAGE_TO_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES) + + +class AutoModelForMaskGeneration(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_MASK_GENERATION_MAPPING + + +class AutoModelForKeypointDetection(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_KEYPOINT_DETECTION_MAPPING + + +class AutoModelForTextEncoding(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_TEXT_ENCODING_MAPPING + + +class AutoModelForImageToImage(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_IMAGE_TO_IMAGE_MAPPING + + +class AutoModel(_BaseAutoModelClass): + _model_mapping = MODEL_MAPPING + + +AutoModel = auto_class_update(AutoModel) + + +class AutoModelForPreTraining(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_PRETRAINING_MAPPING + + +AutoModelForPreTraining = auto_class_update(AutoModelForPreTraining, head_doc="pretraining") + + +# Private on purpose, the public class will add the deprecation warnings. +class _AutoModelWithLMHead(_BaseAutoModelClass): + _model_mapping = MODEL_WITH_LM_HEAD_MAPPING + + +_AutoModelWithLMHead = auto_class_update(_AutoModelWithLMHead, head_doc="language modeling") + + +class AutoModelForCausalLM(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING + + +AutoModelForCausalLM = auto_class_update(AutoModelForCausalLM, head_doc="causal language modeling") + + +class AutoModelForMaskedLM(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_MASKED_LM_MAPPING + + +AutoModelForMaskedLM = auto_class_update(AutoModelForMaskedLM, head_doc="masked language modeling") + + +class AutoModelForSeq2SeqLM(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + + +AutoModelForSeq2SeqLM = auto_class_update( + AutoModelForSeq2SeqLM, + head_doc="sequence-to-sequence language modeling", + checkpoint_for_example="google-t5/t5-base", +) + + +class AutoModelForSequenceClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING + + +AutoModelForSequenceClassification = auto_class_update( + AutoModelForSequenceClassification, head_doc="sequence classification" +) + + +class AutoModelForQuestionAnswering(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_QUESTION_ANSWERING_MAPPING + + +AutoModelForQuestionAnswering = auto_class_update(AutoModelForQuestionAnswering, head_doc="question answering") + + +class AutoModelForTableQuestionAnswering(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING + + +AutoModelForTableQuestionAnswering = auto_class_update( + AutoModelForTableQuestionAnswering, + head_doc="table question answering", + checkpoint_for_example="google/tapas-base-finetuned-wtq", +) + + +class AutoModelForVisualQuestionAnswering(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING + + +AutoModelForVisualQuestionAnswering = auto_class_update( + AutoModelForVisualQuestionAnswering, + head_doc="visual question answering", + checkpoint_for_example="dandelin/vilt-b32-finetuned-vqa", +) + + +class AutoModelForDocumentQuestionAnswering(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING + + +AutoModelForDocumentQuestionAnswering = auto_class_update( + AutoModelForDocumentQuestionAnswering, + head_doc="document question answering", + checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3', +) + + +class AutoModelForTokenClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING + + +AutoModelForTokenClassification = auto_class_update(AutoModelForTokenClassification, head_doc="token classification") + + +class AutoModelForMultipleChoice(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_MULTIPLE_CHOICE_MAPPING + + +AutoModelForMultipleChoice = auto_class_update(AutoModelForMultipleChoice, head_doc="multiple choice") + + +class AutoModelForNextSentencePrediction(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING + + +AutoModelForNextSentencePrediction = auto_class_update( + AutoModelForNextSentencePrediction, head_doc="next sentence prediction" +) + + +class AutoModelForImageClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING + + +AutoModelForImageClassification = auto_class_update(AutoModelForImageClassification, head_doc="image classification") + + +class AutoModelForZeroShotImageClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING + + +AutoModelForZeroShotImageClassification = auto_class_update( + AutoModelForZeroShotImageClassification, head_doc="zero-shot image classification" +) + + +class AutoModelForImageSegmentation(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING + + +AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation") + + +class AutoModelForSemanticSegmentation(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING + + +AutoModelForSemanticSegmentation = auto_class_update( + AutoModelForSemanticSegmentation, head_doc="semantic segmentation" +) + + +class AutoModelForUniversalSegmentation(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING + + +AutoModelForUniversalSegmentation = auto_class_update( + AutoModelForUniversalSegmentation, head_doc="universal image segmentation" +) + + +class AutoModelForInstanceSegmentation(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING + + +AutoModelForInstanceSegmentation = auto_class_update( + AutoModelForInstanceSegmentation, head_doc="instance segmentation" +) + + +class AutoModelForObjectDetection(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING + + +AutoModelForObjectDetection = auto_class_update(AutoModelForObjectDetection, head_doc="object detection") + + +class AutoModelForZeroShotObjectDetection(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING + + +AutoModelForZeroShotObjectDetection = auto_class_update( + AutoModelForZeroShotObjectDetection, head_doc="zero-shot object detection" +) + + +class AutoModelForDepthEstimation(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_DEPTH_ESTIMATION_MAPPING + + +AutoModelForDepthEstimation = auto_class_update(AutoModelForDepthEstimation, head_doc="depth estimation") + + +class AutoModelForVideoClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING + + +AutoModelForVideoClassification = auto_class_update(AutoModelForVideoClassification, head_doc="video classification") + + +class AutoModelForVision2Seq(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING + + +AutoModelForVision2Seq = auto_class_update(AutoModelForVision2Seq, head_doc="vision-to-text modeling") + + +class AutoModelForImageTextToText(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING + + +AutoModelForImageTextToText = auto_class_update(AutoModelForImageTextToText, head_doc="image-text-to-text modeling") + + +class AutoModelForAudioClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING + + +AutoModelForAudioClassification = auto_class_update(AutoModelForAudioClassification, head_doc="audio classification") + + +class AutoModelForCTC(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_CTC_MAPPING + + +AutoModelForCTC = auto_class_update(AutoModelForCTC, head_doc="connectionist temporal classification") + + +class AutoModelForSpeechSeq2Seq(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING + + +AutoModelForSpeechSeq2Seq = auto_class_update( + AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling" +) + + +class AutoModelForAudioFrameClassification(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING + + +AutoModelForAudioFrameClassification = auto_class_update( + AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification" +) + + +class AutoModelForAudioXVector(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_AUDIO_XVECTOR_MAPPING + + +class AutoModelForTextToSpectrogram(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING + + +class AutoModelForTextToWaveform(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING + + +class AutoBackbone(_BaseAutoBackboneClass): + _model_mapping = MODEL_FOR_BACKBONE_MAPPING + + +AutoModelForAudioXVector = auto_class_update(AutoModelForAudioXVector, head_doc="audio retrieval via x-vector") + + +class AutoModelForMaskedImageModeling(_BaseAutoModelClass): + _model_mapping = MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING + + +AutoModelForMaskedImageModeling = auto_class_update(AutoModelForMaskedImageModeling, head_doc="masked image modeling") + + +class AutoModelWithLMHead(_AutoModelWithLMHead): + @classmethod + def from_config(cls, config): + warnings.warn( + "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use " + "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and " + "`AutoModelForSeq2SeqLM` for encoder-decoder models.", + FutureWarning, + ) + return super().from_config(config) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + warnings.warn( + "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use " + "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and " + "`AutoModelForSeq2SeqLM` for encoder-decoder models.", + FutureWarning, + ) + return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/processing_auto.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/processing_auto.py new file mode 100644 index 0000000000000000000000000000000000000000..04c256957d0bfd5ecdbf12a71700be642f3bf459 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/auto/processing_auto.py @@ -0,0 +1,388 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""AutoProcessor class.""" + +import importlib +import inspect +import json +import os +import warnings +from collections import OrderedDict + +# Build the list of all feature extractors +from ...configuration_utils import PretrainedConfig +from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code +from ...feature_extraction_utils import FeatureExtractionMixin +from ...image_processing_utils import ImageProcessingMixin +from ...processing_utils import ProcessorMixin +from ...tokenization_utils import TOKENIZER_CONFIG_FILE +from ...utils import FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, cached_file, logging +from .auto_factory import _LazyAutoMapping +from .configuration_auto import ( + CONFIG_MAPPING_NAMES, + AutoConfig, + model_type_to_module_name, + replace_list_option_in_docstrings, +) +from .feature_extraction_auto import AutoFeatureExtractor +from .image_processing_auto import AutoImageProcessor +from .tokenization_auto import AutoTokenizer + + +logger = logging.get_logger(__name__) + +PROCESSOR_MAPPING_NAMES = OrderedDict( + [ + ("align", "AlignProcessor"), + ("altclip", "AltCLIPProcessor"), + ("aria", "AriaProcessor"), + ("aya_vision", "AyaVisionProcessor"), + ("bark", "BarkProcessor"), + ("blip", "BlipProcessor"), + ("blip-2", "Blip2Processor"), + ("bridgetower", "BridgeTowerProcessor"), + ("chameleon", "ChameleonProcessor"), + ("chinese_clip", "ChineseCLIPProcessor"), + ("clap", "ClapProcessor"), + ("clip", "CLIPProcessor"), + ("clipseg", "CLIPSegProcessor"), + ("clvp", "ClvpProcessor"), + ("colpali", "ColPaliProcessor"), + ("emu3", "Emu3Processor"), + ("flava", "FlavaProcessor"), + ("fuyu", "FuyuProcessor"), + ("gemma3", "Gemma3Processor"), + ("git", "GitProcessor"), + ("got_ocr2", "GotOcr2Processor"), + ("grounding-dino", "GroundingDinoProcessor"), + ("groupvit", "CLIPProcessor"), + ("hubert", "Wav2Vec2Processor"), + ("idefics", "IdeficsProcessor"), + ("idefics2", "Idefics2Processor"), + ("idefics3", "Idefics3Processor"), + ("instructblip", "InstructBlipProcessor"), + ("instructblipvideo", "InstructBlipVideoProcessor"), + ("kosmos-2", "Kosmos2Processor"), + ("layoutlmv2", "LayoutLMv2Processor"), + ("layoutlmv3", "LayoutLMv3Processor"), + ("llava", "LlavaProcessor"), + ("llava_next", "LlavaNextProcessor"), + ("llava_next_video", "LlavaNextVideoProcessor"), + ("llava_onevision", "LlavaOnevisionProcessor"), + ("markuplm", "MarkupLMProcessor"), + ("mctct", "MCTCTProcessor"), + ("mgp-str", "MgpstrProcessor"), + ("mistral3", "PixtralProcessor"), + ("mllama", "MllamaProcessor"), + ("moonshine", "Wav2Vec2Processor"), + ("oneformer", "OneFormerProcessor"), + ("owlv2", "Owlv2Processor"), + ("owlvit", "OwlViTProcessor"), + ("paligemma", "PaliGemmaProcessor"), + ("pix2struct", "Pix2StructProcessor"), + ("pixtral", "PixtralProcessor"), + ("pop2piano", "Pop2PianoProcessor"), + ("qwen2_5_vl", "Qwen2_5_VLProcessor"), + ("qwen2_audio", "Qwen2AudioProcessor"), + ("qwen2_vl", "Qwen2VLProcessor"), + ("sam", "SamProcessor"), + ("seamless_m4t", "SeamlessM4TProcessor"), + ("sew", "Wav2Vec2Processor"), + ("sew-d", "Wav2Vec2Processor"), + ("siglip", "SiglipProcessor"), + ("siglip2", "Siglip2Processor"), + ("speech_to_text", "Speech2TextProcessor"), + ("speech_to_text_2", "Speech2Text2Processor"), + ("speecht5", "SpeechT5Processor"), + ("trocr", "TrOCRProcessor"), + ("tvlt", "TvltProcessor"), + ("tvp", "TvpProcessor"), + ("udop", "UdopProcessor"), + ("unispeech", "Wav2Vec2Processor"), + ("unispeech-sat", "Wav2Vec2Processor"), + ("video_llava", "VideoLlavaProcessor"), + ("vilt", "ViltProcessor"), + ("vipllava", "LlavaProcessor"), + ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"), + ("wav2vec2", "Wav2Vec2Processor"), + ("wav2vec2-bert", "Wav2Vec2Processor"), + ("wav2vec2-conformer", "Wav2Vec2Processor"), + ("wavlm", "Wav2Vec2Processor"), + ("whisper", "WhisperProcessor"), + ("xclip", "XCLIPProcessor"), + ] +) + +PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES) + + +def processor_class_from_name(class_name: str): + for module_name, processors in PROCESSOR_MAPPING_NAMES.items(): + if class_name in processors: + module_name = model_type_to_module_name(module_name) + + module = importlib.import_module(f".{module_name}", "transformers.models") + try: + return getattr(module, class_name) + except AttributeError: + continue + + for processor in PROCESSOR_MAPPING._extra_content.values(): + if getattr(processor, "__name__", None) == class_name: + return processor + + # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main + # init and we return the proper dummy to get an appropriate error message. + main_module = importlib.import_module("transformers") + if hasattr(main_module, class_name): + return getattr(main_module, class_name) + + return None + + +class AutoProcessor: + r""" + This is a generic processor class that will be instantiated as one of the processor classes of the library when + created with the [`AutoProcessor.from_pretrained`] class method. + + This class cannot be instantiated directly using `__init__()` (throws an error). + """ + + def __init__(self): + raise EnvironmentError( + "AutoProcessor is designed to be instantiated " + "using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method." + ) + + @classmethod + @replace_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES) + def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): + r""" + Instantiate one of the processor classes of the library from a pretrained model vocabulary. + + The processor class to instantiate is selected based on the `model_type` property of the config object (either + passed as an argument or loaded from `pretrained_model_name_or_path` if possible): + + List options + + Params: + pretrained_model_name_or_path (`str` or `os.PathLike`): + This can be either: + + - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on + huggingface.co. + - a path to a *directory* containing a processor files saved using the `save_pretrained()` method, + e.g., `./my_model_directory/`. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model feature extractor should be cached if the + standard cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the feature extractor files and override the cached versions + if they exist. + resume_download: + Deprecated and ignored. All downloads are now resumed by default when possible. + Will be removed in v5 of Transformers. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `huggingface-cli login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + return_unused_kwargs (`bool`, *optional*, defaults to `False`): + If `False`, then this function returns just the final feature extractor object. If `True`, then this + functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary + consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of + `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored. + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether or not to allow for custom models defined on the Hub in their own modeling files. This option + should only be set to `True` for repositories you trust and in which you have read the code, as it will + execute code present on the Hub on your local machine. + kwargs (`Dict[str, Any]`, *optional*): + The values in kwargs of any keys which are feature extractor attributes will be used to override the + loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is + controlled by the `return_unused_kwargs` keyword parameter. + + + + Passing `token=True` is required when you want to use a private model. + + + + Examples: + + ```python + >>> from transformers import AutoProcessor + + >>> # Download processor from huggingface.co and cache. + >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") + + >>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*) + >>> # processor = AutoProcessor.from_pretrained("./test/saved_model/") + ```""" + use_auth_token = kwargs.pop("use_auth_token", None) + if use_auth_token is not None: + warnings.warn( + "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", + FutureWarning, + ) + if kwargs.get("token", None) is not None: + raise ValueError( + "`token` and `use_auth_token` are both specified. Please set only the argument `token`." + ) + kwargs["token"] = use_auth_token + + config = kwargs.pop("config", None) + trust_remote_code = kwargs.pop("trust_remote_code", None) + kwargs["_from_auto"] = True + + processor_class = None + processor_auto_map = None + + # First, let's see if we have a processor or preprocessor config. + # Filter the kwargs for `cached_file`. + cached_file_kwargs = { + key: kwargs[key] for key in inspect.signature(cached_file).parameters.keys() if key in kwargs + } + # We don't want to raise + cached_file_kwargs.update( + { + "_raise_exceptions_for_gated_repo": False, + "_raise_exceptions_for_missing_entries": False, + "_raise_exceptions_for_connection_errors": False, + } + ) + + # Let's start by checking whether the processor class is saved in a processor config + processor_config_file = cached_file(pretrained_model_name_or_path, PROCESSOR_NAME, **cached_file_kwargs) + if processor_config_file is not None: + config_dict, _ = ProcessorMixin.get_processor_dict(pretrained_model_name_or_path, **kwargs) + processor_class = config_dict.get("processor_class", None) + if "AutoProcessor" in config_dict.get("auto_map", {}): + processor_auto_map = config_dict["auto_map"]["AutoProcessor"] + + if processor_class is None: + # If not found, let's check whether the processor class is saved in an image processor config + preprocessor_config_file = cached_file( + pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **cached_file_kwargs + ) + if preprocessor_config_file is not None: + config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs) + processor_class = config_dict.get("processor_class", None) + if "AutoProcessor" in config_dict.get("auto_map", {}): + processor_auto_map = config_dict["auto_map"]["AutoProcessor"] + + # If not found, let's check whether the processor class is saved in a feature extractor config + if preprocessor_config_file is not None and processor_class is None: + config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict( + pretrained_model_name_or_path, **kwargs + ) + processor_class = config_dict.get("processor_class", None) + if "AutoProcessor" in config_dict.get("auto_map", {}): + processor_auto_map = config_dict["auto_map"]["AutoProcessor"] + + if processor_class is None: + # Next, let's check whether the processor class is saved in a tokenizer + tokenizer_config_file = cached_file( + pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **cached_file_kwargs + ) + if tokenizer_config_file is not None: + with open(tokenizer_config_file, encoding="utf-8") as reader: + config_dict = json.load(reader) + + processor_class = config_dict.get("processor_class", None) + if "AutoProcessor" in config_dict.get("auto_map", {}): + processor_auto_map = config_dict["auto_map"]["AutoProcessor"] + + if processor_class is None: + # Otherwise, load config, if it can be loaded. + if not isinstance(config, PretrainedConfig): + config = AutoConfig.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + + # And check if the config contains the processor class. + processor_class = getattr(config, "processor_class", None) + if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map: + processor_auto_map = config.auto_map["AutoProcessor"] + + if processor_class is not None: + processor_class = processor_class_from_name(processor_class) + + has_remote_code = processor_auto_map is not None + has_local_code = processor_class is not None or type(config) in PROCESSOR_MAPPING + trust_remote_code = resolve_trust_remote_code( + trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code + ) + + if has_remote_code and trust_remote_code: + processor_class = get_class_from_dynamic_module( + processor_auto_map, pretrained_model_name_or_path, **kwargs + ) + _ = kwargs.pop("code_revision", None) + if os.path.isdir(pretrained_model_name_or_path): + processor_class.register_for_auto_class() + return processor_class.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + elif processor_class is not None: + return processor_class.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + # Last try: we use the PROCESSOR_MAPPING. + elif type(config) in PROCESSOR_MAPPING: + return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs) + + # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a + # tokenizer. + try: + return AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + except Exception: + try: + return AutoImageProcessor.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + except Exception: + pass + + try: + return AutoFeatureExtractor.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs + ) + except Exception: + pass + + raise ValueError( + f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a " + "tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains " + "the files of at least one of those processing classes." + ) + + @staticmethod + def register(config_class, processor_class, exist_ok=False): + """ + Register a new processor for this class. + + Args: + config_class ([`PretrainedConfig`]): + The configuration corresponding to the model to register. + processor_class ([`FeatureExtractorMixin`]): The processor to register. + """ + PROCESSOR_MAPPING.register(config_class, processor_class, exist_ok=exist_ok) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/__init__.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11a9fcbdc4ed3935dc549e3cd1992b7550d9bbad --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_mistral3 import * + from .modeling_mistral3 import * + from .processing_mistral3 import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/configuration_mistral3.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/configuration_mistral3.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b27d57220e5e13edd657aa6fe87ef75ef40089 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/configuration_mistral3.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ...configuration_utils import PretrainedConfig +from ..auto import CONFIG_MAPPING, AutoConfig + + +class Mistral3Config(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`Mistral3ForConditionalGeneration`]. It is used to instantiate an + Mistral3 model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of + [mistralai/Mistral-Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `PixtralVisionConfig`): + The config object or dictionary of the vision backbone. + text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MistralConfig`): + The config object or dictionary of the text backbone. + image_token_index (`int`, *optional*, defaults to 10): + The image token index to encode the image prompt. + projector_hidden_act (`str`, *optional*, defaults to `"gelu"`): + The activation function used by the multimodal projector. + vision_feature_layer (`Union[int, List[int]]`, *optional*, defaults to -1): + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + multimodal_projector_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in the multimodal projector. + spatial_merge_size (`int`, *optional*, defaults to 2): + The downsampling factor for the spatial merge operation. + + Example: + + ```python + >>> from transformers import Mistral3ForConditionalGeneration, Mistral3Config, PixtralVisionConfig, MistralConfig + + >>> # Initializing a Pixtral-vision config + >>> vision_config = PixtralVisionConfig() + + >>> # Initializing a Mistral config + >>> text_config = MistralConfig() + + >>> # Initializing a Mistral3 configuration + >>> configuration = Mistral3Config(vision_config, text_config) + + >>> # Initializing a model from the mistral3.1 configuration + >>> model = Mistral3ForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "mistral3" + sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig} + is_composition = True + + def __init__( + self, + vision_config=None, + text_config=None, + image_token_index=10, + projector_hidden_act="gelu", + vision_feature_layer=-1, + multimodal_projector_bias=False, + spatial_merge_size=2, + **kwargs, + ): + super().__init__(**kwargs) + self.image_token_index = image_token_index + self.projector_hidden_act = projector_hidden_act + + self.vision_feature_layer = vision_feature_layer + + if isinstance(vision_config, dict): + vision_config["model_type"] = vision_config["model_type"] if "model_type" in vision_config else "pixtral" + vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) + elif vision_config is None: + vision_config = CONFIG_MAPPING["pixtral"]( + intermediate_size=4096, + hidden_size=1024, + patch_size=14, + image_size=1540, + num_hidden_layers=24, + num_attention_heads=16, + vocab_size=32000, + head_dim=64, + hidden_act="gelu", + ) + + self.vision_config = vision_config + + if isinstance(text_config, dict): + text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "mistral" + text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) + elif text_config is None: + text_config = CONFIG_MAPPING["mistral"]( + attention_dropout=0.0, + head_dim=128, + hidden_act="silu", + hidden_size=5120, + initializer_range=0.02, + intermediate_size=32768, + max_position_embeddings=131072, + model_type="mistral", + num_attention_heads=32, + num_hidden_layers=40, + num_key_value_heads=8, + rms_norm_eps=1e-05, + rope_theta=1000000000.0, + sliding_window=None, + use_cache=True, + vocab_size=131072, + ) + + self.text_config = text_config + self.multimodal_projector_bias = multimodal_projector_bias + self.spatial_merge_size = spatial_merge_size + + +__all__ = ["Mistral3Config"] diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..11b2d18f04d6f8318c32085dd60496f0f060a410 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py @@ -0,0 +1,241 @@ +# Copyright 2023 Mistral AI and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import json +import os +import re + +import torch +from safetensors.torch import load_file + +from transformers import ( + Mistral3Config, + Mistral3ForConditionalGeneration, + MistralConfig, + PixtralImageProcessorFast, + PixtralProcessor, + PixtralVisionConfig, +) +from transformers.integrations.mistral import convert_tekken_tokenizer + + +# fmt: off +STATE_DICT_MAPPING = { + # Text model keys + r"^output.weight": r"language_model.lm_head.weight", + r"^norm.weight": r"language_model.model.norm.weight", + r"^tok_embeddings.weight": r"language_model.model.embed_tokens.weight", + r"^layers.(\d+).attention_norm.weight": r"language_model.model.layers.\1.input_layernorm.weight", + r"^layers.(\d+).ffn_norm.weight": r"language_model.model.layers.\1.post_attention_layernorm.weight", + r"^layers.(\d+).attention.w(q|k|v|o).weight": r"language_model.model.layers.\1.self_attn.\2_proj.weight", + r"^layers.(\d+).feed_forward.w1.weight": r"language_model.model.layers.\1.mlp.gate_proj.weight", + r"^layers.(\d+).feed_forward.w2.weight": r"language_model.model.layers.\1.mlp.down_proj.weight", + r"^layers.(\d+).feed_forward.w3.weight": r"language_model.model.layers.\1.mlp.up_proj.weight", + + # Vision model keys + r"vision_encoder.transformer.layers.(\d+).attention_norm.weight": r"vision_tower.transformer.layers.\1.attention_norm.weight", + r"^vision_encoder.transformer.layers.(\d+).ffn_norm.weight": r"vision_tower.transformer.layers.\1.ffn_norm.weight", + r"^vision_encoder.transformer.layers.(\d+).attention.w(q|k|v|o).weight": r"vision_tower.transformer.layers.\1.attention.\2_proj.weight", + r"^vision_encoder.transformer.layers.(\d+).feed_forward.w1.weight": r"vision_tower.transformer.layers.\1.feed_forward.gate_proj.weight", + r"^vision_encoder.transformer.layers.(\d+).feed_forward.w2.weight": r"vision_tower.transformer.layers.\1.feed_forward.down_proj.weight", + r"^vision_encoder.transformer.layers.(\d+).feed_forward.w3.weight": r"vision_tower.transformer.layers.\1.feed_forward.up_proj.weight", + r"^vision_language_adapter.w_in": r"multi_modal_projector.linear_1", + r"^vision_language_adapter.w_out": r"multi_modal_projector.linear_2", + r"^vision_encoder.ln_pre.weight": r"vision_tower.ln_pre.weight", + r"^vision_encoder.patch_conv.weight": r"vision_tower.patch_conv.weight", + r"^patch_merger.merging_layer.weight": r"multi_modal_projector.patch_merger.merging_layer.weight", + r"^pre_mm_projector_norm.weight": r"multi_modal_projector.norm.weight", +} +# fmt: on + + +def map_old_key_to_new(old_key): + """Map of a key of the original state dict to the equivalent key in HF format""" + for pattern, replacement in STATE_DICT_MAPPING.items(): + new_key, n_replace = re.subn(pattern, replacement, old_key) + # Early exit of the loop + if n_replace > 0: + return new_key + + raise ValueError(f"Key: {old_key} could not be mapped (check the mapping).") + + +def read_json(path): + with open(path, "r") as f: + return json.load(f) + + +def permute_for_rope(tensor, n_heads, dim1, dim2): + """Permute the weights for the ROPE formulation.""" + tensor = tensor.view(n_heads, dim1 // n_heads // 2, 2, dim2) + tensor = tensor.transpose(1, 2) + tensor = tensor.reshape(dim1, dim2) + return tensor + + +def convert_state_dict(original_state_dict: dict, config: MistralConfig): + """Convert a state dict file, when a single `nn.Module` is never sharded in different files (usual case).""" + new_dict = {} + + for old_key, tensor in original_state_dict.items(): + new_key = map_old_key_to_new(old_key) + + if "vision" in old_key: + num_attention_heads = config.vision_config.num_attention_heads + num_key_value_heads = num_attention_heads + hidden_size = config.vision_config.hidden_size + head_dim = config.vision_config.head_dim + key_value_dim = head_dim * num_attention_heads + query_dim = head_dim * num_attention_heads + else: + num_attention_heads = config.text_config.num_attention_heads + hidden_size = config.text_config.hidden_size + head_dim = config.text_config.head_dim + num_key_value_heads = config.text_config.num_key_value_heads + key_value_dim = head_dim * num_key_value_heads + query_dim = head_dim * num_attention_heads + + if "q_proj" in new_key: + tensor = permute_for_rope(tensor, num_attention_heads, query_dim, hidden_size) + elif "k_proj" in new_key: + tensor = permute_for_rope(tensor, num_key_value_heads, key_value_dim, hidden_size) + + new_dict[new_key] = tensor + return new_dict + + +def convert_config(original_config: dict, max_position_embeddings: int = 131072): + original_vision_config = original_config.pop("vision_encoder") + original_text_config = original_config + + # Text config + text_key_mapping = { + "hidden_size": "dim", + "num_hidden_layers": "n_layers", + "intermediate_size": "hidden_dim", + "num_attention_heads": "n_heads", + "num_key_value_heads": "n_kv_heads", + "rms_norm_eps": "norm_eps", + } + similar_text_keys_to_keep = [ + "head_dim", + "vocab_size", + "rope_theta", + ] + new_text_config_kwargs = {k: original_text_config[v] for k, v in text_key_mapping.items()} + new_text_config_kwargs.update({k: v for k, v in original_text_config.items() if k in similar_text_keys_to_keep}) + # These are not always defined depending on `params.json` + new_text_config_kwargs["sliding_window"] = original_text_config.get("sliding_window", None) + new_text_config_kwargs["max_position_embeddings"] = original_text_config.get( + "max_seq_len", max_position_embeddings + ) + # This may sometimes be a string in `params.json` + if new_text_config_kwargs["sliding_window"] is not None: + new_text_config_kwargs["sliding_window"] = int(new_text_config_kwargs["sliding_window"]) + new_text_config = MistralConfig(**new_text_config_kwargs) + + # Vision config + new_vision_config = original_vision_config + adapter_bias = new_vision_config.pop("adapter_bias", False) + _ = new_vision_config.pop("mm_projector_id", None) + _ = new_vision_config.pop("add_pre_mm_projector_layer_norm", None) + spatial_merge_size = new_vision_config.pop("spatial_merge_size") + image_token_id = new_vision_config.pop("image_token_id", 10) + _ = new_vision_config.pop("image_break_token_id", 12) + _ = new_vision_config.pop("image_end_token_id", 13) + _ = new_vision_config.pop("max_image_size") + new_vision_config = PixtralVisionConfig(**new_vision_config) + + new_config = Mistral3Config( + vision_config=new_vision_config, + text_config=new_text_config, + multimodal_projector_bias=adapter_bias, + image_token_index=image_token_id, + spatial_merge_size=spatial_merge_size, + vision_feature_layer=-1, + ) + return new_config + + +def convert_and_write_model(input_dir: str, output_dir: str, max_position_embeddings: int): + """Convert the model and save it (this implicitly save the config as well).""" + params = read_json(os.path.join(input_dir, "params.json")) + config = convert_config(params, max_position_embeddings) + + full_state_dict = {} + # The model may be split between different files, but a single nn.Module is always fully present in a single file + shards = [file for file in os.listdir(input_dir) if file.endswith(".safetensors")] + for shard_file in shards: + original_state_dict = load_file(os.path.join(input_dir, shard_file)) + new_dict = convert_state_dict(original_state_dict, config) + full_state_dict.update(new_dict) + + # Load weights into model and resave them + with torch.device("meta"): + model = Mistral3ForConditionalGeneration(config) + model.load_state_dict(full_state_dict, strict=True, assign=True) + model.save_pretrained(output_dir) + + +def convert_and_write_processor(input_dir: str, output_dir: str): + """Convert the tokenizer and save it.""" + tokenizer_file = os.path.join(input_dir, "tekken.json") + tokenizer = convert_tekken_tokenizer(tokenizer_file) + tokenizer.add_special_tokens({"pad_token": ""}) + chat_template = '{%- if messages[0]["role"] == "system" %}{%- set system_message = messages[0]["content"] %}{%- set loop_messages = messages[1:] %}\n{%- else %}{%- set loop_messages = messages %}{%- endif %}{{- bos_token }}{%- for message in loop_messages %}{%- if (message[\'role\'] == \'user\') != (loop.index0 % 2 == 0) %}{{- raise_exception(\'After the optional system message, conversation roles must alternate user/assistant/user/assistant/...\') }}{%- endif %}{%- if message["role"] == "user" %}{%- if loop.last and system_message is defined %}{{- "[INST]" + system_message + "\n\n" }}{%- else %}{{ "[INST]" }}{%- endif %}{%- endif %}{%- if message["content"] is not string %}{%- for chunk in message["content"] %}{%- if chunk["type"] == "text" %}{%- if "content" in chunk %}{{- chunk["content"] }}{%- elif "text" in chunk %}{{- chunk["text"] }}{%- endif %}{%- elif chunk["type"] == "image" %}{{- "[IMG]" }}{%- else %}{{- raise_exception("Unrecognized content type!") }}{%- endif %}{%- endfor %}{%- else %}{{- message["content"] }}{%- endif %}{%- if message["role"] == "user" %}{{- "[/INST]" }}{%- elif message["role"] == "assistant" %}{{- eos_token}}{%- else %}{{- raise_exception("Only user and assistant roles are supported, with the exception of an initial optional system message!") }}{%- endif %}{%- endfor %}' + + config = read_json(os.path.join(input_dir, "params.json")) + patch_size = config["vision_encoder"]["patch_size"] + spatial_merge_size = config["vision_encoder"]["spatial_merge_size"] + max_image_size = config["vision_encoder"]["max_image_size"] + image_processor = PixtralImageProcessorFast(patch_size=patch_size, size={"longest_edge": max_image_size}) + + processor = PixtralProcessor( + tokenizer=tokenizer, + image_processor=image_processor, + image_token="[IMG]", + patch_size=patch_size, + chat_template=chat_template, + spatial_merge_size=spatial_merge_size, + ) + + # Finally save it + processor.save_pretrained(output_dir) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "input_dir", + help="Location of Mistral weights, which contains tokenizer.model and model folders", + ) + parser.add_argument( + "output_dir", + help="Location to write HF model and tokenizer", + ) + parser.add_argument( + "--max_position_embeddings", + type=int, + default=131072, + help="`max_position_embeddings` field in the config. This needs to be manually passed (not present anywhere otherwise).", + ) + + args = parser.parse_args() + + convert_and_write_model(args.input_dir, args.output_dir, args.max_position_embeddings) + convert_and_write_processor(args.input_dir, args.output_dir) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modeling_mistral3.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modeling_mistral3.py new file mode 100644 index 0000000000000000000000000000000000000000..4ded5efed626b09b60f7f312e3e2eddc0fe5204a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modeling_mistral3.py @@ -0,0 +1,553 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/mistral3/modular_mistral3.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_mistral3.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# coding=utf-8 +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import List, Optional, Tuple, Union + +import torch +from torch import nn + +from ...activations import ACT2FN +from ...generation import GenerationMixin +from ...modeling_outputs import ModelOutput +from ...modeling_utils import PreTrainedModel +from ...utils import ( + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_torchdynamo_compiling, + replace_return_docstrings, +) +from ...utils.deprecation import deprecate_kwarg +from ..auto import AutoModel, AutoModelForCausalLM +from .configuration_mistral3 import Mistral3Config + + +_CONFIG_FOR_DOC = "Mistral3Config" + + +class Mistral3RMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + Mistral3RMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class Mistral3PatchMerger(nn.Module): + """ + Learned merging of spatial_merge_size ** 2 patches + """ + + def __init__(self, config: Mistral3Config): + super().__init__() + self.config = config + + hidden_size = config.vision_config.hidden_size + self.spatial_merge_size = config.spatial_merge_size + self.patch_size = self.config.vision_config.patch_size + self.merging_layer = nn.Linear(hidden_size * self.spatial_merge_size**2, hidden_size, bias=False) + + def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor) -> torch.Tensor: + image_sizes = [ + (image_size[0] // self.patch_size, image_size[1] // self.patch_size) for image_size in image_sizes + ] + + tokens_per_image = [h * w for h, w in image_sizes] + d = image_features.shape[-1] + + permuted_tensor = [] + for image_index, image_tokens in enumerate(image_features.split(tokens_per_image)): + # Reshape image_tokens into a 2D grid + h, w = image_sizes[image_index] + image_grid = image_tokens.view(h, w, d).permute(2, 0, 1).unsqueeze(0) + grid = torch.nn.functional.unfold( + image_grid, kernel_size=self.spatial_merge_size, stride=self.spatial_merge_size + ) + grid = grid.view(d * self.spatial_merge_size**2, -1).t() + permuted_tensor.append(grid) + + image_features = torch.cat(permuted_tensor, dim=0) + image_features = self.merging_layer(image_features) + return image_features + + +class Mistral3MultiModalProjector(nn.Module): + def __init__(self, config: Mistral3Config): + super().__init__() + self.norm = Mistral3RMSNorm(config.vision_config.hidden_size) + self.patch_merger = Mistral3PatchMerger(config) + # We have hidden_size * the number of vision feature layers + num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer) + self.linear_1 = nn.Linear( + config.vision_config.hidden_size * num_feature_layers, + config.text_config.hidden_size, + bias=config.multimodal_projector_bias, + ) + self.act = ACT2FN[config.projector_hidden_act] + self.linear_2 = nn.Linear( + config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias + ) + + def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor): + image_features = self.norm(image_features) + image_features = self.patch_merger(image_features, image_sizes) + hidden_states = self.linear_1(image_features) + hidden_states = self.act(hidden_states) + hidden_states = self.linear_2(hidden_states) + return hidden_states + + +@dataclass +class Mistral3CausalLMOutputWithPast(ModelOutput): + """ + Base class for Mistral3 causal language model (or autoregressive) outputs. + + Args: + loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): + Language modeling loss (for next-token prediction). + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): + Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) + + Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see + `past_key_values` input) to speed up sequential decoding. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. + + Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. + + Attentions weights after the attention softmax, used to compute the weighted average in the self-attention + heads. + image_hidden_states (`torch.FloatTensor`, *optional*): + A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`. + image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. + """ + + loss: Optional[torch.FloatTensor] = None + logits: torch.FloatTensor = None + past_key_values: Optional[List[torch.FloatTensor]] = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + image_hidden_states: Optional[torch.FloatTensor] = None + + +MISTRAL3_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`Mistral3Config`] or [`Mistral3VisionConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + MISTRAL3_START_DOCSTRING, +) +class Mistral3PreTrainedModel(PreTrainedModel): + config_class = Mistral3Config + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["Mistral3VisionAttention"] + _skip_keys_device_placement = "past_key_values" + _supports_cache_class = True + _supports_flash_attn_2 = True + _supports_sdpa = True + _supports_quantized_cache = True + _supports_static_cache = True + + def _init_weights(self, module): + # important: this ported version of Mistral3 isn't meant for training from scratch - only + # inference and fine-tuning - so the proper init weights code has been removed - the original codebase + # https://github.com/haotian-liu/Mistral3/tree/main/mistral3 should serve for that purpose + std = ( + self.config.initializer_range + if hasattr(self.config, "initializer_range") + else self.config.text_config.initializer_range + ) + + if hasattr(module, "class_embedding"): + module.class_embedding.data.normal_(mean=0.0, std=std) + + if isinstance(module, (nn.Linear, nn.Conv2d)): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +MISTRAL3_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)): + The tensors corresponding to the input images. Pixel values can be obtained using + [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details ([]`Mistral3Processor`] uses + [`CLIPImageProcessor`] for processing images). + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + vision_feature_layer (`Union[int, List[int]], *optional*, defaults to -2`): + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`): + The feature selection strategy used to select the vision feature from the vision backbone. + Can be one of `"default"` or `"full"`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, + this tensor is not affected by padding. It is used to update the cache in the correct position and to infer + the complete sequence length. +""" + + +@add_start_docstrings( + """The MISTRAL3 model which consists of a vision backbone and a language model.""", + MISTRAL3_START_DOCSTRING, +) +class Mistral3ForConditionalGeneration(Mistral3PreTrainedModel, GenerationMixin): + def __init__(self, config: Mistral3Config): + super().__init__(config) + self.vision_tower = AutoModel.from_config(config.vision_config) + + self.multi_modal_projector = Mistral3MultiModalProjector(config) + self.vocab_size = config.text_config.vocab_size + self.language_model = AutoModelForCausalLM.from_config(config.text_config) + + if self.language_model._tied_weights_keys is not None: + self._tied_weights_keys = [f"language_model.{k}" for k in self.language_model._tied_weights_keys] + + self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1 + + self.post_init() + + def get_input_embeddings(self): + return self.language_model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.language_model.set_input_embeddings(value) + + def get_output_embeddings(self): + return self.language_model.get_output_embeddings() + + def set_output_embeddings(self, new_embeddings): + self.language_model.set_output_embeddings(new_embeddings) + + def set_decoder(self, decoder): + self.language_model.set_decoder(decoder) + + def get_decoder(self): + return self.language_model.get_decoder() + + def get_image_features( + self, + pixel_values: torch.FloatTensor, + vision_feature_layer: Union[int, List[int]], + image_sizes: torch.Tensor, + **kwargs, + ): + """ + Obtains image last hidden states from the vision tower and apply multimodal projection. + + Args: + pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`): + The tensors corresponding to the input images. + vision_feature_layer (`Union[int, List[int]]`): + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + image_sizes (`torch.Tensor`): + Tensor containing the image sizes as returned by the processor. + Returns: + image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`). + """ + kwargs = {k: v for k, v in kwargs.items() if v is not None} + # this is not memory efficient at all (output_hidden_states=True) will save all the hidden states. + image_outputs = self.vision_tower(pixel_values, image_sizes=image_sizes, output_hidden_states=True, **kwargs) + # If we have one vision feature layer, return the corresponding hidden states, + # otherwise, select the hidden states of each feature layer and concatenate them + if isinstance(vision_feature_layer, int): + selected_image_feature = image_outputs.hidden_states[vision_feature_layer] + else: + hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer] + selected_image_feature = torch.cat(hs_pool, dim=-1) + + image_features = self.multi_modal_projector(selected_image_feature.squeeze(0), image_sizes) + return image_features + + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") + @add_start_docstrings_to_model_forward(MISTRAL3_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=Mistral3CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + pixel_values: torch.FloatTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + vision_feature_layer: Optional[Union[int, List[int]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + logits_to_keep: Union[int, torch.Tensor] = 0, + image_sizes: torch.Tensor = None, + **lm_kwargs, + ) -> Union[Tuple, Mistral3CausalLMOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + logits_to_keep (`int` or `torch.Tensor`, *optional*): + If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. + This is useful when using packed tensor format (single dimension for batch and sequence length). + + + Returns: + + Example: + + ```python + >>> from PIL import Image + >>> import requests + >>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration + + >>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503") + >>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503") + + >>> prompt = "[INST][IMG]What is the image?[/INST]" + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = Image.open(requests.get(url, stream=True).raw) + + >>> inputs = processor(images=image, text=prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(**inputs, max_new_tokens=15) + >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "What is the image?The image depicts two cats lying on a pink blanket." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + vision_feature_layer = ( + vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer + ) + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if pixel_values is not None and inputs_embeds is not None: + raise ValueError( + "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one" + ) + + if inputs_embeds is None: + inputs_embeds = self.get_input_embeddings()(input_ids) + + if pixel_values is not None: + image_features = self.get_image_features( + pixel_values=pixel_values, + vision_feature_layer=vision_feature_layer, + image_sizes=image_sizes, + ) + + special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1) + special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device) + if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel(): + n_image_tokens = (input_ids == self.config.image_token_index).sum() + n_image_features = image_features.shape[0] * image_features.shape[1] + raise ValueError( + f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" + ) + image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features) + + outputs = self.language_model( + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + logits_to_keep=logits_to_keep, + **lm_kwargs, + ) + + logits = outputs[0] + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + if attention_mask is not None: + # we use the input attention mask to shift the logits and labels, because it is 2D. + # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft + shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device) + shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous() + shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous() + else: + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct( + shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device) + ) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return Mistral3CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + image_hidden_states=image_features if pixel_values is not None else None, + ) + + def prepare_inputs_for_generation( + self, + input_ids, + past_key_values=None, + inputs_embeds=None, + pixel_values=None, + attention_mask=None, + cache_position=None, + logits_to_keep=None, + **kwargs, + ): + # Overwritten -- in specific circumstances we don't want to forward image inputs to the model + + model_inputs = self.language_model.prepare_inputs_for_generation( + input_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + cache_position=cache_position, + logits_to_keep=logits_to_keep, + **kwargs, + ) + + if cache_position[0] == 0: + # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore + # Otherwise we need pixel values to be passed to model + model_inputs["pixel_values"] = pixel_values + + return model_inputs + + +__all__ = ["Mistral3PreTrainedModel", "Mistral3ForConditionalGeneration"] diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modular_mistral3.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modular_mistral3.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1edf97bd9f8a849aac08a4b930de93bdb63186 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/mistral3/modular_mistral3.py @@ -0,0 +1,286 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import List, Optional, Tuple, Union + +import torch +from torch import nn + +from ...activations import ACT2FN +from ...utils import is_torchdynamo_compiling, logging +from ..llava.modeling_llava import LlavaCausalLMOutputWithPast, LlavaForConditionalGeneration +from ..mistral.modeling_mistral import MistralRMSNorm +from .configuration_mistral3 import Mistral3Config + + +logger = logging.get_logger(__name__) + + +class Mistral3RMSNorm(MistralRMSNorm): + pass + + +class Mistral3PatchMerger(nn.Module): + """ + Learned merging of spatial_merge_size ** 2 patches + """ + + def __init__(self, config: Mistral3Config): + super().__init__() + self.config = config + + hidden_size = config.vision_config.hidden_size + self.spatial_merge_size = config.spatial_merge_size + self.patch_size = self.config.vision_config.patch_size + self.merging_layer = nn.Linear(hidden_size * self.spatial_merge_size**2, hidden_size, bias=False) + + def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor) -> torch.Tensor: + image_sizes = [ + (image_size[0] // self.patch_size, image_size[1] // self.patch_size) for image_size in image_sizes + ] + + tokens_per_image = [h * w for h, w in image_sizes] + d = image_features.shape[-1] + + permuted_tensor = [] + for image_index, image_tokens in enumerate(image_features.split(tokens_per_image)): + # Reshape image_tokens into a 2D grid + h, w = image_sizes[image_index] + image_grid = image_tokens.view(h, w, d).permute(2, 0, 1).unsqueeze(0) + grid = torch.nn.functional.unfold( + image_grid, kernel_size=self.spatial_merge_size, stride=self.spatial_merge_size + ) + grid = grid.view(d * self.spatial_merge_size**2, -1).t() + permuted_tensor.append(grid) + + image_features = torch.cat(permuted_tensor, dim=0) + image_features = self.merging_layer(image_features) + return image_features + + +class Mistral3MultiModalProjector(nn.Module): + def __init__(self, config: Mistral3Config): + super().__init__() + self.norm = Mistral3RMSNorm(config.vision_config.hidden_size) + self.patch_merger = Mistral3PatchMerger(config) + # We have hidden_size * the number of vision feature layers + num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer) + self.linear_1 = nn.Linear( + config.vision_config.hidden_size * num_feature_layers, + config.text_config.hidden_size, + bias=config.multimodal_projector_bias, + ) + self.act = ACT2FN[config.projector_hidden_act] + self.linear_2 = nn.Linear( + config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias + ) + + def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor): + image_features = self.norm(image_features) + image_features = self.patch_merger(image_features, image_sizes) + hidden_states = self.linear_1(image_features) + hidden_states = self.act(hidden_states) + hidden_states = self.linear_2(hidden_states) + return hidden_states + + +class Mistral3CausalLMOutputWithPast(LlavaCausalLMOutputWithPast): + pass + + +class Mistral3ForConditionalGeneration(LlavaForConditionalGeneration): + def get_image_features( + self, + pixel_values: torch.FloatTensor, + vision_feature_layer: Union[int, List[int]], + image_sizes: torch.Tensor, + **kwargs, + ): + """ + Obtains image last hidden states from the vision tower and apply multimodal projection. + + Args: + pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`): + The tensors corresponding to the input images. + vision_feature_layer (`Union[int, List[int]]`): + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + image_sizes (`torch.Tensor`): + Tensor containing the image sizes as returned by the processor. + Returns: + image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`). + """ + kwargs = {k: v for k, v in kwargs.items() if v is not None} + # this is not memory efficient at all (output_hidden_states=True) will save all the hidden states. + image_outputs = self.vision_tower(pixel_values, image_sizes=image_sizes, output_hidden_states=True, **kwargs) + # If we have one vision feature layer, return the corresponding hidden states, + # otherwise, select the hidden states of each feature layer and concatenate them + if isinstance(vision_feature_layer, int): + selected_image_feature = image_outputs.hidden_states[vision_feature_layer] + else: + hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer] + selected_image_feature = torch.cat(hs_pool, dim=-1) + + image_features = self.multi_modal_projector(selected_image_feature.squeeze(0), image_sizes) + return image_features + + def forward( + self, + input_ids: torch.LongTensor = None, + pixel_values: torch.FloatTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + vision_feature_layer: Optional[Union[int, List[int]]] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + logits_to_keep: Union[int, torch.Tensor] = 0, + image_sizes: torch.Tensor = None, + **lm_kwargs, + ) -> Union[Tuple, Mistral3CausalLMOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + logits_to_keep (`int` or `torch.Tensor`, *optional*): + If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. + This is useful when using packed tensor format (single dimension for batch and sequence length). + + + Returns: + + Example: + + ```python + >>> from PIL import Image + >>> import requests + >>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration + + >>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503") + >>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503") + + >>> prompt = "[INST][IMG]What is the image?[/INST]" + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = Image.open(requests.get(url, stream=True).raw) + + >>> inputs = processor(images=image, text=prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(**inputs, max_new_tokens=15) + >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "What is the image?The image depicts two cats lying on a pink blanket." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + vision_feature_layer = ( + vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer + ) + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if pixel_values is not None and inputs_embeds is not None: + raise ValueError( + "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one" + ) + + if inputs_embeds is None: + inputs_embeds = self.get_input_embeddings()(input_ids) + + if pixel_values is not None: + image_features = self.get_image_features( + pixel_values=pixel_values, + vision_feature_layer=vision_feature_layer, + image_sizes=image_sizes, + ) + + special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1) + special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device) + if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel(): + n_image_tokens = (input_ids == self.config.image_token_index).sum() + n_image_features = image_features.shape[0] * image_features.shape[1] + raise ValueError( + f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" + ) + image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features) + + outputs = self.language_model( + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + logits_to_keep=logits_to_keep, + **lm_kwargs, + ) + + logits = outputs[0] + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + if attention_mask is not None: + # we use the input attention mask to shift the logits and labels, because it is 2D. + # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft + shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device) + shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous() + shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous() + else: + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct( + shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device) + ) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return Mistral3CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + image_hidden_states=image_features if pixel_values is not None else None, + ) + + +__all__ = [ + "Mistral3PreTrainedModel", # noqa + "Mistral3ForConditionalGeneration", +] diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/image_processing_pixtral.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/image_processing_pixtral.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb452863a76f9b368759aba9e6d878a7d654dc2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/image_processing_pixtral.py @@ -0,0 +1,472 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Image processor class for Pixtral.""" + +import math +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np + +from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict +from ...image_transforms import ( + pad, + resize, + to_channel_dimension_format, +) +from ...image_utils import ( + ChannelDimension, + ImageInput, + PILImageResampling, + get_image_size, + infer_channel_dimension_format, + is_scaled_image, + make_list_of_images, + to_numpy_array, + valid_images, + validate_kwargs, + validate_preprocess_arguments, +) +from ...utils import TensorType, is_vision_available, logging +from ...utils.import_utils import requires_backends + + +logger = logging.get_logger(__name__) + + +if is_vision_available(): + import PIL + + +# Adapted from function in image_transforms.py to ensure any transparent pixels are converted to white. +def convert_to_rgb(image: ImageInput) -> ImageInput: + """ + Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image + as is. + Args: + image (Image): + The image to convert. + """ + requires_backends(convert_to_rgb, ["vision"]) + + if not isinstance(image, PIL.Image.Image): + return image + + if image.mode == "RGB": + return image + + # First we convert to RGBA to set background to white. + image = image.convert("RGBA") + + # Create a new image with a white background. + new_image = PIL.Image.new("RGBA", image.size, "WHITE") + new_image.paste(image, (0, 0), image) + new_image = new_image.convert("RGB") + return new_image + + +def _num_image_tokens(image_size: Tuple[int, int], patch_size: Tuple[int, int]) -> int: + """ + Calculate the number of image tokens given the image size and patch size. + + Args: + image_size (`Tuple[int, int]`): + The size of the image as `(height, width)`. + patch_size (`Tuple[int, int]`): + The patch size as `(height, width)`. + + Returns: + `int`: The number of image tokens. + """ + height, width = image_size + patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size) + num_width_tokens = (width - 1) // patch_width + 1 + num_height_tokens = (height - 1) // patch_height + 1 + return num_height_tokens, num_width_tokens + + +def get_resize_output_image_size( + input_image: ImageInput, + size: Union[int, Tuple[int, int], List[int], Tuple[int]], + patch_size: Union[int, Tuple[int, int], List[int], Tuple[int]], + input_data_format: Optional[Union[str, ChannelDimension]] = None, +) -> tuple: + """ + Find the target (height, width) dimension of the output image after resizing given the input image and the desired + size. + + Args: + input_image (`ImageInput`): + The image to resize. + size (`int` or `Tuple[int, int]`): + Max image size an input image can be. Must be a dictionary with the key "longest_edge". + patch_size (`int` or `Tuple[int, int]`): + The patch_size as `(height, width)` to use for resizing the image. If patch_size is an integer, `(patch_size, patch_size)` + will be used + input_data_format (`ChannelDimension`, *optional*): + The channel dimension format of the input image. If unset, will use the inferred format from the input. + + Returns: + `tuple`: The target (height, width) dimension of the output image after resizing. + """ + max_height, max_width = size if isinstance(size, (tuple, list)) else (size, size) + patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size) + height, width = get_image_size(input_image, input_data_format) + + ratio = max(height / max_height, width / max_width) + + if ratio > 1: + # Orgiginal implementation uses `round` which utilises bankers rounding, which can lead to surprising results + # Here we use floor to ensure the image is always smaller than the given "longest_edge" + height = int(math.floor(height / ratio)) + width = int(math.floor(width / ratio)) + + num_height_tokens, num_width_tokens = _num_image_tokens((height, width), (patch_height, patch_width)) + return num_height_tokens * patch_height, num_width_tokens * patch_width + + +class PixtralImageProcessor(BaseImageProcessor): + r""" + Constructs a Pixtral image processor. + + Args: + do_resize (`bool`, *optional*, defaults to `True`): + Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by + `do_resize` in the `preprocess` method. + size (`Dict[str, int]` *optional*, defaults to `{"longest_edge": 1024}`): + Size of the maximum dimension of either the height or width dimension of the image. Used to control how + images are resized. If either the height or width are greater than `size["longest_edge"]` then both the height and width are rescaled by `height / ratio`, `width /ratio` where `ratio = max(height / longest_edge, width / longest_edge)` + patch_size (`Dict[str, int]` *optional*, defaults to `{"height": 16, "width": 16}`): + Size of the patches in the model, used to calculate the output image size. Can be overridden by `patch_size` in the `preprocess` method. + resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): + Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method. + do_rescale (`bool`, *optional*, defaults to `True`): + Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in + the `preprocess` method. + rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): + Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess` + method. + do_normalize (`bool`, *optional*, defaults to `True`): + Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method. + image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`): + Mean to use if normalizing the image. This is a float or list of floats the length of the number of + channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. + image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`): + Standard deviation to use if normalizing the image. This is a float or list of floats the length of the + number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. + Can be overridden by the `image_std` parameter in the `preprocess` method. + do_convert_rgb (`bool`, *optional*, defaults to `True`): + Whether to convert the image to RGB. + """ + + model_input_names = ["pixel_values"] + + def __init__( + self, + do_resize: bool = True, + size: Dict[str, int] = None, + patch_size: Dict[str, int] = None, + resample: PILImageResampling = PILImageResampling.BICUBIC, + do_rescale: bool = True, + rescale_factor: Union[int, float] = 1 / 255, + do_normalize: bool = True, + image_mean: Optional[Union[float, List[float]]] = None, + image_std: Optional[Union[float, List[float]]] = None, + do_convert_rgb: bool = True, + **kwargs, + ) -> None: + super().__init__(**kwargs) + size = size if size is not None else {"longest_edge": 1024} + patch_size = patch_size if patch_size is not None else {"height": 16, "width": 16} + patch_size = get_size_dict(patch_size, default_to_square=True) + + self.do_resize = do_resize + self.size = size + self.patch_size = patch_size + self.resample = resample + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_normalize = do_normalize + self.image_mean = image_mean if image_mean is not None else [0.48145466, 0.4578275, 0.40821073] + self.image_std = image_std if image_std is not None else [0.26862954, 0.26130258, 0.27577711] + self.do_convert_rgb = do_convert_rgb + self._valid_processor_keys = [ + "images", + "do_resize", + "size", + "patch_size", + "resample", + "do_rescale", + "rescale_factor", + "do_normalize", + "image_mean", + "image_std", + "do_convert_rgb", + "return_tensors", + "data_format", + "input_data_format", + ] + + def resize( + self, + image: np.ndarray, + size: Dict[str, int], + patch_size: Dict[str, int], + resample: PILImageResampling = PILImageResampling.BICUBIC, + data_format: Optional[Union[str, ChannelDimension]] = None, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + **kwargs, + ) -> np.ndarray: + """ + Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge + resized to keep the input aspect ratio. + + Args: + image (`np.ndarray`): + Image to resize. + size (`Dict[str, int]`): + Dict containing the longest possible edge of the image. + patch_size (`Dict[str, int]`): + Patch size used to calculate the size of the output image. + resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): + Resampling filter to use when resiizing the image. + data_format (`str` or `ChannelDimension`, *optional*): + The channel dimension format of the image. If not provided, it will be the same as the input image. + input_data_format (`ChannelDimension` or `str`, *optional*): + The channel dimension format of the input image. If not provided, it will be inferred. + """ + if "longest_edge" in size: + size = (size["longest_edge"], size["longest_edge"]) + elif "height" in size and "width" in size: + size = (size["height"], size["width"]) + else: + raise ValueError("size must contain either 'longest_edge' or 'height' and 'width'.") + + if "height" in patch_size and "width" in patch_size: + patch_size = (patch_size["height"], patch_size["width"]) + else: + raise ValueError("patch_size must contain either 'shortest_edge' or 'height' and 'width'.") + + output_size = get_resize_output_image_size( + image, + size=size, + patch_size=patch_size, + input_data_format=input_data_format, + ) + return resize( + image, + size=output_size, + resample=resample, + data_format=data_format, + input_data_format=input_data_format, + **kwargs, + ) + + def _pad_for_batching( + self, + pixel_values: List[np.ndarray], + image_sizes: List[List[int]], + data_format: Optional[Union[str, ChannelDimension]] = None, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + ): + """ + Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches. + Args: + pixel_values (`List[np.ndarray]`): + An array of pixel values of each images of shape (`batch_size`, `height`, `width`, `channels`) + image_sizes (`List[List[int]]`): + A list of sizes for each image in `pixel_values` in (height, width) format. + data_format (`str` or `ChannelDimension`, *optional*): + The channel dimension format for the output image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + If unset, will use same as the input image. + input_data_format (`str` or `ChannelDimension`, *optional*): + The channel dimension format for the input image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + If unset, will use the inferred format of the input image. + Returns: + List[`np.ndarray`]: The padded images. + """ + + max_shape = ( + max([size[0] for size in image_sizes]), + max([size[1] for size in image_sizes]), + ) + pixel_values = [ + pad( + image, + padding=((0, max_shape[0] - size[0]), (0, max_shape[1] - size[1])), + data_format=data_format, + input_data_format=input_data_format, + ) + for image, size in zip(pixel_values, image_sizes) + ] + return pixel_values + + def preprocess( + self, + images: ImageInput, + do_resize: bool = None, + size: Dict[str, int] = None, + patch_size: Dict[str, int] = None, + resample: PILImageResampling = None, + do_rescale: bool = None, + rescale_factor: float = None, + do_normalize: bool = None, + image_mean: Optional[Union[float, List[float]]] = None, + image_std: Optional[Union[float, List[float]]] = None, + do_convert_rgb: bool = None, + return_tensors: Optional[Union[str, TensorType]] = None, + data_format: Optional[ChannelDimension] = ChannelDimension.FIRST, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + **kwargs, + ) -> PIL.Image.Image: + """ + Preprocess an image or batch of images. + + Args: + images (`ImageInput`): + Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If + passing in images with pixel values between 0 and 1, set `do_rescale=False`. + do_resize (`bool`, *optional*, defaults to `self.do_resize`): + Whether to resize the image. + size (`Dict[str, int]`, *optional*, defaults to `self.size`): + Describes the maximum input dimensions to the model. + patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`): + Patch size in the model. Used to calculate the image after resizing. + resample (`int`, *optional*, defaults to `self.resample`): + Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only + has an effect if `do_resize` is set to `True`. + do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): + Whether to rescale the image. + rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): + Rescale factor to rescale the image by if `do_rescale` is set to `True`. + do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): + Whether to normalize the image. + image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): + Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. + image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): + Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to + `True`. + do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): + Whether to convert the image to RGB. + return_tensors (`str` or `TensorType`, *optional*): + The type of tensors to return. Can be one of: + - Unset: Return a list of `np.ndarray`. + - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. + - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. + - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. + - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`. + data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): + The channel dimension format for the output image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + - Unset: Use the channel dimension format of the input image. + input_data_format (`ChannelDimension` or `str`, *optional*): + The channel dimension format for the input image. If unset, the channel dimension format is inferred + from the input image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. + """ + patch_size = patch_size if patch_size is not None else self.patch_size + patch_size = get_size_dict(patch_size, default_to_square=True) + + do_resize = do_resize if do_resize is not None else self.do_resize + size = size if size is not None else self.size + resample = resample if resample is not None else self.resample + do_rescale = do_rescale if do_rescale is not None else self.do_rescale + rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor + do_normalize = do_normalize if do_normalize is not None else self.do_normalize + image_mean = image_mean if image_mean is not None else self.image_mean + image_std = image_std if image_std is not None else self.image_std + do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb + + validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys) + + images = make_list_of_images(images) + + if not valid_images(images[0]): + raise ValueError( + "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " + "torch.Tensor, tf.Tensor or jax.ndarray." + ) + + validate_preprocess_arguments( + do_rescale=do_rescale, + rescale_factor=rescale_factor, + do_normalize=do_normalize, + image_mean=image_mean, + image_std=image_std, + do_resize=do_resize, + size=size, + resample=resample, + ) + + if do_convert_rgb: + images = [convert_to_rgb(image) for image in images] + + # All transformations expect numpy arrays. + images = [to_numpy_array(image) for image in images] + + if do_rescale and is_scaled_image(images[0]): + logger.warning_once( + "It looks like you are trying to rescale already rescaled images. If the input" + " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." + ) + + if input_data_format is None: + # We assume that all images have the same channel dimension format. + input_data_format = infer_channel_dimension_format(images[0]) + + batch_images = [] + batch_image_sizes = [] + for image in images: + if do_resize: + image = self.resize( + image=image, + size=size, + patch_size=patch_size, + resample=resample, + input_data_format=input_data_format, + ) + + if do_rescale: + image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format) + + if do_normalize: + image = self.normalize( + image=image, mean=image_mean, std=image_std, input_data_format=input_data_format + ) + + image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) + + batch_images.append(image) + batch_image_sizes.append(get_image_size(image, data_format)) + + pixel_values = self._pad_for_batching( + pixel_values=batch_images, + image_sizes=batch_image_sizes, + input_data_format=data_format, + data_format=data_format, + ) + + return BatchFeature( + data={"pixel_values": pixel_values, "image_sizes": batch_image_sizes}, tensor_type=return_tensors + ) + + +__all__ = ["PixtralImageProcessor"] diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/processing_pixtral.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/processing_pixtral.py new file mode 100644 index 0000000000000000000000000000000000000000..66da1bf9f780c0138c9dea36d63217987e73230e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/models/pixtral/processing_pixtral.py @@ -0,0 +1,241 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Processor class for Pixtral. +""" + +from typing import List, Union + +from ...feature_extraction_utils import BatchFeature +from ...image_utils import ImageInput, is_valid_image, load_image +from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order +from ...tokenization_utils_base import PreTokenizedInput, TextInput +from ...utils import logging + + +logger = logging.get_logger(__name__) + + +class PixtralProcessorKwargs(ProcessingKwargs, total=False): + _defaults = { + "text_kwargs": { + "padding": False, + }, + "images_kwargs": {}, + "common_kwargs": { + "return_tensors": "pt", + }, + } + + +# Copied from transformers.models.idefics2.processing_idefics2.is_url +def is_url(val) -> bool: + return isinstance(val, str) and val.startswith("http") + + +# Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url +def is_image_or_image_url(elem): + return is_url(elem) or is_valid_image(elem) + + +class PixtralProcessor(ProcessorMixin): + r""" + Constructs a Pixtral processor which wraps a Pixtral image processor and a Pixtral tokenizer into a single processor. + + [`PixtralProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the + [`~PixtralProcessor.__call__`] and [`~PixtralProcessor.decode`] for more information. + + Args: + image_processor ([`PixtralImageProcessor`], *optional*): + The image processor is a required input. + tokenizer ([`LlamaTokenizerFast`], *optional*): + The tokenizer is a required input. + patch_size (`int`, *optional*, defaults to 16): + Patch size from the vision tower. + spatial_merge_size (`int`, *optional*, defaults to 1): + The downsampling factor for the spatial merge operation. + chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages + in a chat into a tokenizable string. + image_token (`str`, *optional*, defaults to `"[IMG]"`): + Special token used to denote image location. + image_break_token (`str`, *optional*, defaults to `"[IMG_BREAK]"`): + Special token used to denote the end of a line of pixels in an image. + image_end_token (`str`, *optional*, defaults to `"[IMG_END]"`): + Special token used to denote the end of an image input. + """ + + attributes = ["image_processor", "tokenizer"] + valid_kwargs = [ + "chat_template", + "patch_size", + "spatial_merge_size", + "image_token", + "image_break_token", + "image_end_token", + ] + image_processor_class = "AutoImageProcessor" + tokenizer_class = "AutoTokenizer" + + def __init__( + self, + image_processor=None, + tokenizer=None, + patch_size: int = 16, + spatial_merge_size: int = 1, + chat_template=None, + image_token="[IMG]", # set the default and let users change if they have peculiar special tokens in rare cases + image_break_token="[IMG_BREAK]", + image_end_token="[IMG_END]", + **kwargs, + ): + self.patch_size = patch_size + self.spatial_merge_size = spatial_merge_size + self.image_token = image_token + self.image_break_token = image_break_token + self.image_end_token = image_end_token + super().__init__(image_processor, tokenizer, chat_template=chat_template) + + def __call__( + self, + images: ImageInput = None, + text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, + audio=None, + videos=None, + **kwargs: Unpack[PixtralProcessorKwargs], + ) -> BatchFeature: + """ + Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` + and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode + the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to + CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring + of the above two methods for more information. + + Args: + images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): + The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch + tensor. Both channels-first and channels-last formats are supported. + text (`str`, `List[str]`, `List[List[str]]`): + The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings + (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set + `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). + return_tensors (`str` or [`~utils.TensorType`], *optional*): + If set, will return tensors of a particular framework. Acceptable values are: + + - `'tf'`: Return TensorFlow `tf.constant` objects. + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return NumPy `np.ndarray` objects. + - `'jax'`: Return JAX `jnp.ndarray` objects. + + Returns: + [`BatchFeature`]: A [`BatchFeature`] with the following fields: + + - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. + - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when + `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not + `None`). + - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. + """ + # check if images and text inputs are reversed for BC + images, text = _validate_images_text_input_order(images, text) + + output_kwargs = self._merge_kwargs( + PixtralProcessorKwargs, + tokenizer_init_kwargs=self.tokenizer.init_kwargs, + **kwargs, + ) + + if images is not None: + if is_image_or_image_url(images): + images = [images] + elif isinstance(images, (list, tuple)) and is_image_or_image_url(images[0]): + pass + elif ( + isinstance(images, (list, tuple)) + and isinstance(images[0], (list, tuple)) + and is_image_or_image_url(images[0][0]) + ): + images = [image for sublist in images for image in sublist] + else: + raise ValueError( + "Invalid input images. Please provide a single image, a list of images, or a list of lists of images." + ) + images = [load_image(im) if isinstance(im, str) else im for im in images] + image_inputs = self.image_processor(images, patch_size=self.patch_size, **output_kwargs["images_kwargs"]) + else: + image_inputs = {} + + if isinstance(text, str): + text = [text] + elif not isinstance(text, list) and not isinstance(text[0], str): + raise ValueError("Invalid input text. Please provide a string, or a list of strings") + + # try to expand inputs in processing if we have the necessary parts + prompt_strings = text + if image_inputs.get("pixel_values") is not None: + # Replace the image token with the expanded image token sequence + image_sizes = iter(image_inputs["image_sizes"]) + prompt_strings = [] + replace_strings = [] + + for sample in text: + while self.image_token in sample: + height, width = next(image_sizes) + num_height_tokens = height // (self.patch_size * self.spatial_merge_size) + num_width_tokens = width // (self.patch_size * self.spatial_merge_size) + replace_tokens = [ + [self.image_token] * num_width_tokens + [self.image_break_token] + ] * num_height_tokens + # Flatten list + replace_tokens = [item for sublist in replace_tokens for item in sublist] + replace_tokens[-1] = self.image_end_token + replace_str = "".join(replace_tokens) + replace_strings.append(replace_str) + sample = sample.replace(self.image_token, "", 1) + + while "" in sample: + replace_str = replace_strings.pop(0) + sample = sample.replace("", replace_str, 1) + prompt_strings.append(sample) + + text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"]) + return BatchFeature( + data={**text_inputs, **image_inputs}, tensor_type=output_kwargs["common_kwargs"]["return_tensors"] + ) + + # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama + def batch_decode(self, *args, **kwargs): + """ + This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please + refer to the docstring of this method for more information. + """ + return self.tokenizer.batch_decode(*args, **kwargs) + + # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama + def decode(self, *args, **kwargs): + """ + This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to + the docstring of this method for more information. + """ + return self.tokenizer.decode(*args, **kwargs) + + @property + # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names + def model_input_names(self): + tokenizer_input_names = self.tokenizer.model_input_names + image_processor_input_names = self.image_processor.model_input_names + return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) + + +__all__ = ["PixtralProcessor"] diff --git a/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/utils/dummy_pt_objects.py b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/utils/dummy_pt_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..c4532ead938c3078276e40c682303dda36f25c22 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/reference/src/transformers/utils/dummy_pt_objects.py @@ -0,0 +1,10932 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class Cache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CacheConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DynamicCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderDecoderCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HQQQuantizedCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HybridCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MambaCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OffloadedCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OffloadedStaticCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QuantizedCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QuantizedCacheConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QuantoQuantizedCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SinkCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SlidingWindowCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StaticCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlueDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlueDataTrainingArguments(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LineByLineTextDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LineByLineWithRefDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LineByLineWithSOPTextDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SquadDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SquadDataTrainingArguments(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TextDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TextDatasetForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlternatingCodebooksLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BayesianDetectorConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BayesianDetectorModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeamScorer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeamSearchScorer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConstrainedBeamSearchScorer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Constraint(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConstraintListState(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DisjunctiveConstraint(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderNoRepeatNGramLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderRepetitionPenaltyLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EosTokenCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EpsilonLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EtaLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ExponentialDecayLengthPenalty(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ForcedBOSTokenLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ForcedEOSTokenLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GenerationMixin(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HammingDiversityLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InfNanRemoveLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitNormalization(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitsProcessorList(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaxLengthCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaxTimeCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinLengthLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinNewTokensLengthLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinPLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NoBadWordsLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NoRepeatNGramLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhrasalConstraint(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PrefixConstrainedLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RepetitionPenaltyLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SequenceBiasLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StoppingCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StoppingCriteriaList(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StopStringCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuppressTokensAtBeginLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuppressTokensLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkDetector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkingConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TemperatureLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TopKLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TopPLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TypicalLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UnbatchedClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WatermarkDetector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WatermarkLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperTimeStampLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TorchExportableModuleWithStaticCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def convert_and_export_with_cache(*args, **kwargs): + requires_backends(convert_and_export_with_cache, ["torch"]) + + +ROPE_INIT_FUNCTIONS = None + + +class PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlbertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_albert(*args, **kwargs): + requires_backends(load_tf_weights_in_albert, ["torch"]) + + +class AlignModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlignPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlignTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlignVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AltCLIPModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AltCLIPPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AltCLIPTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AltCLIPVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AriaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AriaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AriaTextForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AriaTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AriaTextPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ASTForAudioClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ASTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ASTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_AUDIO_XVECTOR_MAPPING = None + + +MODEL_FOR_BACKBONE_MAPPING = None + + +MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING = None + + +MODEL_FOR_CAUSAL_LM_MAPPING = None + + +MODEL_FOR_CTC_MAPPING = None + + +MODEL_FOR_DEPTH_ESTIMATION_MAPPING = None + + +MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = None + + +MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_IMAGE_MAPPING = None + + +MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = None + + +MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING = None + + +MODEL_FOR_IMAGE_TO_IMAGE_MAPPING = None + + +MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING = None + + +MODEL_FOR_KEYPOINT_DETECTION_MAPPING = None + + +MODEL_FOR_MASK_GENERATION_MAPPING = None + + +MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = None + + +MODEL_FOR_MASKED_LM_MAPPING = None + + +MODEL_FOR_MULTIPLE_CHOICE_MAPPING = None + + +MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = None + + +MODEL_FOR_OBJECT_DETECTION_MAPPING = None + + +MODEL_FOR_PRETRAINING_MAPPING = None + + +MODEL_FOR_QUESTION_ANSWERING_MAPPING = None + + +MODEL_FOR_RETRIEVAL_MAPPING = None + + +MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = None + + +MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = None + + +MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = None + + +MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = None + + +MODEL_FOR_TEXT_ENCODING_MAPPING = None + + +MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING = None + + +MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING = None + + +MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING = None + + +MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING = None + + +MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_VISION_2_SEQ_MAPPING = None + + +MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING = None + + +MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = None + + +MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING = None + + +MODEL_MAPPING = None + + +MODEL_WITH_LM_HEAD_MAPPING = None + + +class AutoBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForAudioClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForAudioXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForDocumentQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForImageSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForImageTextToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForImageToImage(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForInstanceSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForKeypointDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForMaskGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForSeq2SeqLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForSpeechSeq2Seq(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForTableQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForTextEncoding(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForTextToSpectrogram(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForTextToWaveform(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForUniversalSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForVideoClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForVision2Seq(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForVisualQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForZeroShotImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelForZeroShotObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoModelWithLMHead(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoformerForPrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AutoformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AyaVisionForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AyaVisionPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BambaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BambaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BambaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkCausalModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkCoarseModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkFineModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BarkSemanticModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BartPretrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PretrainedBartModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BeitPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_bert(*args, **kwargs): + requires_backends(load_tf_weights_in_bert, ["torch"]) + + +class BertGenerationDecoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertGenerationEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BertGenerationPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_bert_generation(*args, **kwargs): + requires_backends(load_tf_weights_in_bert_generation, ["torch"]) + + +class BigBirdForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_big_bird(*args, **kwargs): + requires_backends(load_tf_weights_in_big_bird, ["torch"]) + + +class BigBirdPegasusForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPegasusForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPegasusForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPegasusForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPegasusModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BigBirdPegasusPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BioGptForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BioGptForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BioGptForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BioGptModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BioGptPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BitBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BitForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BitPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotSmallForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotSmallForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotSmallModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlenderbotSmallPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipForImageTextRetrieval(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BlipVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2ForImageTextRetrieval(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2QFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2TextModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2VisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Blip2VisionModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BloomPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BridgeTowerForContrastiveLearning(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BridgeTowerForImageAndTextRetrieval(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BridgeTowerForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BridgeTowerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BridgeTowerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosSpadeEEForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BrosSpadeELForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CamembertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CanineForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CanineForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CanineForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CanineForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CanineModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CaninePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_canine(*args, **kwargs): + requires_backends(load_tf_weights_in_canine, ["torch"]) + + +class ChameleonForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChameleonModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChameleonPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChameleonProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChameleonVQVAE(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChineseCLIPModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChineseCLIPPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChineseCLIPTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ChineseCLIPVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapAudioModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapAudioModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapFeatureExtractor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClapTextModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPTextModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPVisionModelWithProjection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPSegForImageSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPSegModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPSegPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPSegTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CLIPSegVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpDecoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpModelForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClvpPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CodeGenForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CodeGenModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CodeGenPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CohereForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CohereModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CoherePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Cohere2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Cohere2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Cohere2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ColPaliForRetrieval(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ColPaliPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConditionalDetrForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConditionalDetrForSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConditionalDetrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConditionalDetrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_convbert(*args, **kwargs): + requires_backends(load_tf_weights_in_convbert, ["torch"]) + + +class ConvNextBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextV2Backbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextV2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ConvNextV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CpmAntForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CpmAntModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CpmAntPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CTRLForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CTRLLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CTRLModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CTRLPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CvtForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CvtModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class CvtPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DabDetrForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DabDetrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DabDetrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DacModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DacPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecAudioPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecTextPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecVisionForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecVisionForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Data2VecVisionPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DbrxForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DbrxModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DbrxPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2ForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2ForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DebertaV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DecisionTransformerGPT2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DecisionTransformerGPT2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DecisionTransformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DecisionTransformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeformableDetrForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeformableDetrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeformableDetrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeiTForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeiTForImageClassificationWithTeacher(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeiTForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeiTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DeiTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetaForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientFormerForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientFormerForImageClassificationWithTeacher(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMForInformationExtraction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTSanJapaneseForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTSanJapaneseModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTSanJapanesePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraphormerForGraphClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraphormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraphormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JukeboxModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JukeboxPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JukeboxPrior(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JukeboxVQVAE(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MCTCTForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MCTCTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MCTCTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MMBTForClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MMBTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModalEmbeddings(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NatBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NatForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NatModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NatPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NezhaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenLlamaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenLlamaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenLlamaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenLlamaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QDQBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_qdqbert(*args, **kwargs): + requires_backends(load_tf_weights_in_qdqbert, ["torch"]) + + +class RealmEmbedder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmForOpenQA(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmKnowledgeAugEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmReader(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmRetriever(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RealmScorer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_realm(*args, **kwargs): + requires_backends(load_tf_weights_in_realm, ["torch"]) + + +class RetriBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RetriBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Speech2Text2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Speech2Text2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TrajectoryTransformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TrajectoryTransformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AdaptiveEmbedding(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TransfoXLForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TransfoXLLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TransfoXLModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TransfoXLPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_transfo_xl(*args, **kwargs): + requires_backends(load_tf_weights_in_transfo_xl, ["torch"]) + + +class TvltForAudioVisualClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvltForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvltModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvltPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VanForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VanModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VanPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTHybridForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTHybridModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTHybridPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetDecoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMProphetNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DepthAnythingForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DepthAnythingPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DepthProForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DepthProModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DepthProPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetrForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetrForSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DetrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DiffLlamaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DinatBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DinatForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DinatModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DinatPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2Backbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2WithRegistersBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2WithRegistersForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2WithRegistersModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Dinov2WithRegistersPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DistilBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DonutSwinModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DonutSwinPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRContextEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRPretrainedContextEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRPretrainedQuestionEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRPretrainedReader(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRQuestionEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPRReader(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPTForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPTForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DPTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientNetForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EfficientNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ElectraPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_electra(*args, **kwargs): + requires_backends(load_tf_weights_in_electra, ["torch"]) + + +class Emu3ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Emu3ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Emu3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Emu3TextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Emu3VQVAE(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncodecModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncodecPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderDecoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErnieModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ErniePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmFoldPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmForProteinFolding(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EsmPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconMambaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconMambaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FalconMambaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FastSpeech2ConformerHifiGan(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FastSpeech2ConformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FastSpeech2ConformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FastSpeech2ConformerWithHifiGan(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertForQuestionAnsweringSimple(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlaubertWithLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaImageCodebook(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaImageModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaMultimodalModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FlavaTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FocalNetBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FocalNetForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FocalNetForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FocalNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FocalNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FSMTForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FSMTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PretrainedFSMTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelBaseModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FunnelPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_funnel(*args, **kwargs): + requires_backends(load_tf_weights_in_funnel, ["torch"]) + + +class FuyuForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class FuyuPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GemmaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GemmaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GemmaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GemmaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GemmaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma3ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma3ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Gemma3TextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GitForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GitPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GitVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlmForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlmForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlmForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlmModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlmPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GLPNForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GLPNModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GLPNPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GotOcr2ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GotOcr2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2DoubleHeadsModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2LMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPT2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_gpt2(*args, **kwargs): + requires_backends(load_tf_weights_in_gpt2, ["torch"]) + + +class GPTBigCodeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTBigCodeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTBigCodeForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTBigCodeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTBigCodePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_gpt_neo(*args, **kwargs): + requires_backends(load_tf_weights_in_gpt_neo, ["torch"]) + + +class GPTNeoXForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXJapaneseForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXJapaneseModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTNeoXJapanesePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTJForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTJForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTJForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTJModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GPTJPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GranitePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoeSharedForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoeSharedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GraniteMoeSharedPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroundingDinoForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroundingDinoModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroundingDinoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroupViTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroupViTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroupViTTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GroupViTVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HeliumForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HeliumForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HeliumForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HeliumModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HeliumPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HieraBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HieraForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HieraForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HieraModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HieraPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HubertForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HubertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HubertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class HubertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IdeficsForVisionText2Text(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IdeficsModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IdeficsPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IdeficsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics2ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics2Processor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3Processor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3VisionConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Idefics3VisionTransformer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IJepaForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IJepaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class IJepaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ImageGPTForCausalImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ImageGPTForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ImageGPTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ImageGPTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_imagegpt(*args, **kwargs): + requires_backends(load_tf_weights_in_imagegpt, ["torch"]) + + +class InformerForPrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipQFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipVideoForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipVideoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipVideoQFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InstructBlipVideoVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JambaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JambaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JambaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JambaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JetMoeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JetMoeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JetMoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class JetMoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Kosmos2ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Kosmos2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Kosmos2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv2ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv3ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv3ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv3ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv3Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LayoutLMv3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LEDForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LEDForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LEDForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LEDModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LEDPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LevitForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LevitForImageClassificationWithTeacher(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LevitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LevitPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LiltForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LiltForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LiltForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LiltModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LiltPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlamaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaNextForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaNextPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaNextVideoForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaNextVideoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaOnevisionForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LlavaOnevisionPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongT5EncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongT5ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongT5Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LongT5PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForEntityClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForEntityPairClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForEntitySpanClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LukePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LxmertVisualFeatureEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class M2M100ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class M2M100Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class M2M100PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MambaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MambaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MambaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mamba2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mamba2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mamba2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarianForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarianModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarianMTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarianPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarkupLMForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarkupLMForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarkupLMForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarkupLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MarkupLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mask2FormerForUniversalSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mask2FormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mask2FormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaskFormerForInstanceSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaskFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaskFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaskFormerSwinBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MBartPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MegatronBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MgpstrForSceneTextRecognition(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MgpstrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MgpstrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MimiModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MimiPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MistralPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mistral3ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Mistral3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MixtralPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MllamaVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForNextSentencePrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_mobilebert(*args, **kwargs): + requires_backends(load_tf_weights_in_mobilebert, ["torch"]) + + +class MobileNetV1ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileNetV1Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileNetV1PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_mobilenet_v1(*args, **kwargs): + requires_backends(load_tf_weights_in_mobilenet_v1, ["torch"]) + + +class MobileNetV2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileNetV2ForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileNetV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileNetV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_mobilenet_v2(*args, **kwargs): + requires_backends(load_tf_weights_in_mobilenet_v2, ["torch"]) + + +class MobileViTForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTV2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTV2ForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MobileViTV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModernBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModernBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModernBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModernBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ModernBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoonshineForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoonshineModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoonshinePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoshiForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoshiForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoshiModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MoshiPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MPNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MptPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MraPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5EncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MT5PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenMelodyForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenMelodyForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenMelodyModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MusicgenMelodyPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MvpPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NemotronPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NllbMoeForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NllbMoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NllbMoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NllbMoeSparseMLP(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NllbMoeTop2Router(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NystromformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Olmo2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Olmo2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Olmo2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OlmoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OmDetTurboForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OmDetTurboPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OneFormerForUniversalSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OneFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OneFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenAIGPTDoubleHeadsModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenAIGPTForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenAIGPTLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenAIGPTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OpenAIGPTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_openai_gpt(*args, **kwargs): + requires_backends(load_tf_weights_in_openai_gpt, ["torch"]) + + +class OPTForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OPTForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OPTForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OPTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OPTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Owlv2ForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Owlv2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Owlv2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Owlv2TextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Owlv2VisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OwlViTForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OwlViTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OwlViTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OwlViTTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class OwlViTVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PaliGemmaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PaliGemmaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PaliGemmaProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerForPrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerForPretraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerForRegression(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerForTimeSeriesClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSMixerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTForClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTForPrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTForPretraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTForRegression(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PatchTSTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusXForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusXModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PegasusXPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForImageClassificationConvProcessing(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForImageClassificationFourier(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForImageClassificationLearned(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForMultimodalAutoencoding(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForOpticalFlow(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PerceiverPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PersimmonForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PersimmonForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PersimmonForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PersimmonModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PersimmonPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhiForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhiForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhiForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhiModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhiPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Phi3ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Phi3ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Phi3ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Phi3Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Phi3PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhimoeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhimoeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhimoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PhimoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pix2StructForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pix2StructPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pix2StructTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pix2StructVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PixtralPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PixtralVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PLBartForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PLBartForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PLBartForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PLBartModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PLBartPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PoolFormerForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PoolFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PoolFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pop2PianoForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Pop2PianoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetDecoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ProphetNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtV2Backbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtV2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PvtV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2_5_VLForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2_5_VLModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2_5_VLPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2AudioEncoder(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2AudioForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2AudioPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoeForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoeForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2MoePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2VLForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2VLModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Qwen2VLPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RagModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RagPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RagSequenceForGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RagTokenForGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RecurrentGemmaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RecurrentGemmaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RecurrentGemmaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerModelWithLMHead(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ReformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RegNetForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RegNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RegNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RemBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_rembert(*args, **kwargs): + requires_backends(load_tf_weights_in_rembert, ["torch"]) + + +class ResNetBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ResNetForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ResNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ResNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RobertaPreLayerNormPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoCBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_roc_bert(*args, **kwargs): + requires_backends(load_tf_weights_in_roc_bert, ["torch"]) + + +class RoFormerForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RoFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_roformer(*args, **kwargs): + requires_backends(load_tf_weights_in_roformer, ["torch"]) + + +class RTDetrForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrResNetBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrResNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrV2ForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrV2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RTDetrV2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RwkvForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RwkvModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RwkvPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SamModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SamPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TCodeHifiGan(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TForSpeechToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TForSpeechToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TForTextToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TForTextToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4THifiGan(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TTextToUnitForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4TTextToUnitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2ForSpeechToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2ForSpeechToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2ForTextToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2ForTextToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SeamlessM4Tv2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegformerDecodeHead(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegformerForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegformerForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegGptForImageSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegGptModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SegGptPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWDForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWDForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWDModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SEWDPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SiglipForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SiglipModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SiglipPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SiglipTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SiglipVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Siglip2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Siglip2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Siglip2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Siglip2TextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Siglip2VisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMVisionConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SmolVLMVisionTransformer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechEncoderDecoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Speech2TextForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Speech2TextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Speech2TextPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5ForSpeechToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5ForSpeechToText(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5ForTextToSpeech(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5HifiGan(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SpeechT5PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SplinterForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SplinterForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SplinterModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SplinterPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SqueezeBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StableLmForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StableLmForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StableLmForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StableLmModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StableLmPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Starcoder2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Starcoder2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Starcoder2ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Starcoder2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Starcoder2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuperGlueForKeypointMatching(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuperGluePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuperPointForKeypointDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuperPointPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwiftFormerForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwiftFormerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwiftFormerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwinBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwinForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwinForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwinModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwinPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swin2SRForImageSuperResolution(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swin2SRModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swin2SRPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swinv2Backbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swinv2ForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swinv2ForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swinv2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Swinv2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersEncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersSparseMLP(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SwitchTransformersTop1Router(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5EncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class T5PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_t5(*args, **kwargs): + requires_backends(load_tf_weights_in_t5, ["torch"]) + + +class TableTransformerForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TableTransformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TableTransformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TapasForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TapasForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TapasForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TapasModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TapasPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_tapas(*args, **kwargs): + requires_backends(load_tf_weights_in_tapas, ["torch"]) + + +class TextNetBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TextNetForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TextNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TextNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimeSeriesTransformerForPrediction(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimeSeriesTransformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimeSeriesTransformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimesformerForVideoClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimesformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimesformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimmBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimmWrapperForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimmWrapperModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TimmWrapperPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TrOCRForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TrOCRPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvpForVideoGrounding(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvpModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TvpPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UdopEncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UdopForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UdopModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UdopPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5EncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5ForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5ForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5ForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UMT5PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UniSpeechSatPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UnivNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UperNetForSemanticSegmentation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UperNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoLlavaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoLlavaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoLlavaProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoMAEForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoMAEForVideoClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoMAEModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VideoMAEPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltForImageAndTextRetrieval(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltForImagesAndTextClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViltPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VipLlavaForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VipLlavaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisionEncoderDecoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisionTextDualEncoderModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertForRegionToPhraseAlignment(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertForVisualReasoning(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VisualBertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTForMaskedImageModeling(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMAEForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMAEModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMAEPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMSNForImageClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMSNModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ViTMSNPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitDetBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitDetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitDetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitMatteForImageMatting(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitMattePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitPoseForPoseEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitPosePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitPoseBackbone(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitPoseBackbonePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitsModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VitsPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VivitForVideoClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VivitModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class VivitPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2BertPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerForPreTraining(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Wav2Vec2ConformerPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMForAudioFrameClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMForCTC(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMForXVector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WavLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperForAudioClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperForConditionalGeneration(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XCLIPModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XCLIPPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XCLIPTextModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XCLIPVisionModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XGLMForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XGLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XGLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMForQuestionAnsweringSimple(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMWithLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLMRobertaXLPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetForQuestionAnsweringSimple(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetLMHeadModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XLNetPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def load_tf_weights_in_xlnet(*args, **kwargs): + requires_backends(load_tf_weights_in_xlnet, ["torch"]) + + +class XmodForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class XmodPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YolosForObjectDetection(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YolosModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YolosPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoForMaskedLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoForMultipleChoice(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoForQuestionAnswering(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoForTokenClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class YosoPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZambaForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZambaForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZambaModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZambaPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Zamba2ForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Zamba2ForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Zamba2Model(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Zamba2PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZoeDepthForDepthEstimation(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ZoeDepthPreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Adafactor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AdamW(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def get_constant_schedule(*args, **kwargs): + requires_backends(get_constant_schedule, ["torch"]) + + +def get_constant_schedule_with_warmup(*args, **kwargs): + requires_backends(get_constant_schedule_with_warmup, ["torch"]) + + +def get_cosine_schedule_with_warmup(*args, **kwargs): + requires_backends(get_cosine_schedule_with_warmup, ["torch"]) + + +def get_cosine_with_hard_restarts_schedule_with_warmup(*args, **kwargs): + requires_backends(get_cosine_with_hard_restarts_schedule_with_warmup, ["torch"]) + + +def get_inverse_sqrt_schedule(*args, **kwargs): + requires_backends(get_inverse_sqrt_schedule, ["torch"]) + + +def get_linear_schedule_with_warmup(*args, **kwargs): + requires_backends(get_linear_schedule_with_warmup, ["torch"]) + + +def get_polynomial_decay_schedule_with_warmup(*args, **kwargs): + requires_backends(get_polynomial_decay_schedule_with_warmup, ["torch"]) + + +def get_scheduler(*args, **kwargs): + requires_backends(get_scheduler, ["torch"]) + + +def get_wsd_schedule(*args, **kwargs): + requires_backends(get_wsd_schedule, ["torch"]) + + +class Conv1D(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def apply_chunking_to_forward(*args, **kwargs): + requires_backends(apply_chunking_to_forward, ["torch"]) + + +def prune_layer(*args, **kwargs): + requires_backends(prune_layer, ["torch"]) + + +class Trainer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def torch_distributed_zero_first(*args, **kwargs): + requires_backends(torch_distributed_zero_first, ["torch"]) + + +class Seq2SeqTrainer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) diff --git a/tasks/tasksmith-441eeab80047/solution/solve.sh b/tasks/tasksmith-441eeab80047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c6ab994599658d6e18f7ea098987b6dc569d759e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/solution/solve.sh @@ -0,0 +1,30 @@ +#!/bin/sh +set -eu +mkdir -p -- /workspace/src/transformers +cp /solution/reference/src/transformers/__init__.py /workspace/src/transformers/__init__.py +mkdir -p -- /workspace/src/transformers/models +cp /solution/reference/src/transformers/models/__init__.py /workspace/src/transformers/models/__init__.py +mkdir -p -- /workspace/src/transformers/models/auto +cp /solution/reference/src/transformers/models/auto/configuration_auto.py /workspace/src/transformers/models/auto/configuration_auto.py +mkdir -p -- /workspace/src/transformers/models/auto +cp /solution/reference/src/transformers/models/auto/image_processing_auto.py /workspace/src/transformers/models/auto/image_processing_auto.py +mkdir -p -- /workspace/src/transformers/models/auto +cp /solution/reference/src/transformers/models/auto/modeling_auto.py /workspace/src/transformers/models/auto/modeling_auto.py +mkdir -p -- /workspace/src/transformers/models/auto +cp /solution/reference/src/transformers/models/auto/processing_auto.py /workspace/src/transformers/models/auto/processing_auto.py +mkdir -p -- /workspace/src/transformers/models/mistral3 +cp /solution/reference/src/transformers/models/mistral3/__init__.py /workspace/src/transformers/models/mistral3/__init__.py +mkdir -p -- /workspace/src/transformers/models/mistral3 +cp /solution/reference/src/transformers/models/mistral3/configuration_mistral3.py /workspace/src/transformers/models/mistral3/configuration_mistral3.py +mkdir -p -- /workspace/src/transformers/models/mistral3 +cp /solution/reference/src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py /workspace/src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py +mkdir -p -- /workspace/src/transformers/models/mistral3 +cp /solution/reference/src/transformers/models/mistral3/modeling_mistral3.py /workspace/src/transformers/models/mistral3/modeling_mistral3.py +mkdir -p -- /workspace/src/transformers/models/mistral3 +cp /solution/reference/src/transformers/models/mistral3/modular_mistral3.py /workspace/src/transformers/models/mistral3/modular_mistral3.py +mkdir -p -- /workspace/src/transformers/models/pixtral +cp /solution/reference/src/transformers/models/pixtral/image_processing_pixtral.py /workspace/src/transformers/models/pixtral/image_processing_pixtral.py +mkdir -p -- /workspace/src/transformers/models/pixtral +cp /solution/reference/src/transformers/models/pixtral/processing_pixtral.py /workspace/src/transformers/models/pixtral/processing_pixtral.py +mkdir -p -- /workspace/src/transformers/utils +cp /solution/reference/src/transformers/utils/dummy_pt_objects.py /workspace/src/transformers/utils/dummy_pt_objects.py diff --git a/tasks/tasksmith-441eeab80047/task.toml b/tasks/tasksmith-441eeab80047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..93f629d6d841959383c596c123a3bfb399a8810b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/task.toml @@ -0,0 +1,127 @@ +schema_version = "1.3" + +[task] +name = "repo2rlenv/tasksmith-441eeab80047" + +[metadata.repo2env] +recipe = "tasksmith" +recipe_version = "1" +source_url = "https://github.com/huggingface/transformers/pull/36790" +source_head = "445a523e3e0ee950f3ba3f1cbe295c04ce7b6b32" +source_base = "7f5077e53682ca855afc826162b204ebf809f1f9" +workspace_strategy = "head_minus_source_patch" +source_diff_sha256 = "f5f76411487654abf9dadffe8d490b7ea28e6042847bbead3b35de4e3ccde1cb" +acceptance_profile = "practical-generation-v1" +upstream_test_policy = "replace" +reward_kinds = [ + "test_execution", +] +quality_status = "exported" +fail_to_pass_count = 20 +pass_to_pass_count = 3 +bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "verified" +stage = "complete" +reason_codes = [ + "quality_verified", +] +detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile." +checked_at = "2026-09-14T05:22:44.525419Z" +provenance = "assisted" +subject_bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" +profile = "practical-generation-v1" +source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/revisions/r0/tasksmith-441eeab80047" +source_task_toml_sha256 = "e9ea9549120b0b9e3ac5dd904d1baa9b0619b85c2f566a5707324dbc5619f22d" + +[[metadata.repo2env.evaluation.evidence]] +kind = "quality_result" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/result.json" +sha256 = "fd1f3ffab4be142481ef6b96ebb324c501d7f7bc7a77528efd62f10fea49c7de" +subject_bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" + +[[metadata.repo2env.evaluation.evidence]] +kind = "baseline" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-baseline/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-baseline/tasksmith-441eeab80047__49oyu3r/result.json" +sha256 = "ca578309d203bae7d36ef05393fb3e8fe507a2d7c1b62f709221ea1a660c3b8c" +subject_bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" +harbor_task_checksum = "8d39621f5b5606c9f214f2d6d1a1021fa85e2ca173245a5b69d6a4791f0ce2c8" + +[[metadata.repo2env.evaluation.evidence]] +kind = "oracle" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-oracle/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-oracle/tasksmith-441eeab80047__77XP9eH/result.json" +sha256 = "2d6362e2ce4da7c7ce9e271376c2aae8e5d8d7ceae7af20a9cb89f9237b791cb" +subject_bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" +harbor_task_checksum = "8d39621f5b5606c9f214f2d6d1a1021fa85e2ca173245a5b69d6a4791f0ce2c8" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-probe0/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-probe0/tasksmith-441eeab80047__2ySQxFi/result.json" +sha256 = "59c8ada5564004d32ed88669ca63313a874737323a9bf758177b5a7c0396e5cf" +subject_bundle_hash = "sha256:a0712266bceb20236a5bc170911eb2e89799db7a44b7bedbdddf44463b8b3dbb" +harbor_task_checksum = "43749009234f603a36aff7b1ef74b940874f28db9635c6af91a1b84aaca154f7" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-probe1/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-probe1/tasksmith-441eeab80047__YA2vXUD/result.json" +sha256 = "1f3fc8ed1d099dd16e1b85dd35c5f57954e6ceb3bdb6dc886ed1b5427af3dafc" +subject_bundle_hash = "sha256:cd07bd379906e62cb5dde3a3ab7ded52ee248d7cd774150e9002f81cbc17106d" +harbor_task_checksum = "78b4b4155ab889ef3ce6f7a56d8686c9fef52fdf0dd18ca90bf7de2c891c8468" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-probe2/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-probe2/tasksmith-441eeab80047__jM4pF9R/result.json" +sha256 = "44139997b9d868c08a0aabd7688a19731081d24b438852b53d35606ac8fb48ec" +subject_bundle_hash = "sha256:0a55f0ced655afec3d716700bd4d7241a4fe944ccd3b4b16267b9bff9ea70578" +harbor_task_checksum = "9a784c98c78c219e097ae8b4dc3fd18b2551c5c61679a204e1140e7af3b7de72" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-probe3/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-probe3/tasksmith-441eeab80047__xNkKNZB/result.json" +sha256 = "15744d3c8f9b779814261f754db86da1a94531c82e6d0d59f8707adea520d337" +subject_bundle_hash = "sha256:52b61de056466e5473931f1c6195c93ba93be730d60892268b7812619f0de063" +harbor_task_checksum = "9d94609ccda35be7f453ca60bfeb0ab84127221ddddde7631559ee2ddef424ba" + +[[metadata.repo2env.evaluation.evidence]] +kind = "rollout" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/38439b13ed3f/candidates/441eeab80047/quality/trials/r0-rollout/tsbatch-63b11d77dad4-38439b13ed3f-q-441eeab8-r0-rollout/tasksmith-441eeab80047__NB288D9/result.json" +sha256 = "80c848277752ee9fb5611ccdabfbe5b2f189c0fca4b18894af7952c57621f3d3" +subject_bundle_hash = "sha256:cecc885b0a7cc4fe60637cfd61d18401b3812a6e3c9635cc8f0988bd230064aa" +harbor_task_checksum = "8d39621f5b5606c9f214f2d6d1a1021fa85e2ca173245a5b69d6a4791f0ce2c8" + +[metadata.repo2env.quality_requirements] +probe_focus = [ + "model_behavior", +] + +[environment] +cpus = 1 +memory_mb = 2048 +build_timeout_sec = 600 +network_mode = "no-network" + +[agent] +timeout_sec = 600 +user = "learner" +network_mode = "no-network" + +[verifier] +timeout_sec = 330 +user = "root" +network_mode = "no-network" +environment_mode = "separate" + +[verifier.environment] +network_mode = "no-network" +cpus = 1 +memory_mb = 2048 + +[[artifacts]] +source = "/workspace/src/transformers" +exclude = [ + "__pycache__", + "*.pyc", + ".pytest_cache", +] diff --git a/tasks/tasksmith-441eeab80047/tests/Dockerfile b/tasks/tasksmith-441eeab80047/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df6d520b84d9921fde2b809e3389e84d703874cd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.12-slim +WORKDIR /workspace +RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu torchvision==0.26.0+cpu numpy==2.5.3 packaging==26.3 parameterized==0.9.0 Pillow==10.4.0 pytest==8.4.2 pyyaml==6.0.2 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 tokenizers==0.21.4 huggingface-hub==0.36.2 tqdm==4.67.1 wheel==0.48.0 filelock==3.16.1 datasets==3.6.0 fsspec==2025.3.0 +COPY source /workspace +RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 +RUN useradd -m -u 1001 grader +COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/ +RUN chmod 755 /tests && chmod 644 /tests/* diff --git a/tasks/tasksmith-441eeab80047/tests/contract.json b/tasks/tasksmith-441eeab80047/tests/contract.json new file mode 100644 index 0000000000000000000000000000000000000000..297486a55142f5a198734f495500fa16a23cb218 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/contract.json @@ -0,0 +1 @@ +{"expected_passes": ["tests.tasksmith_behavior.TestMistral3Config::test_custom_values_stored", "tests.tasksmith_behavior.TestMistral3Config::test_defaults", "tests.tasksmith_behavior.TestMistral3Config::test_dict_text_config_instantiated", "tests.tasksmith_behavior.TestMistral3Config::test_dict_vision_config_instantiated", "tests.tasksmith_behavior.TestMistral3Config::test_round_trip_json", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_loss_computed_with_labels", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_multimodal_forward", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_save_load_roundtrip", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_text_only_forward", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_tuple_output_mode", "tests.tasksmith_behavior.TestMistral3MultiModalProjector::test_output_is_finite", "tests.tasksmith_behavior.TestMistral3MultiModalProjector::test_output_shape", "tests.tasksmith_behavior.TestMistral3PatchMerger::test_multi_image_batch", "tests.tasksmith_behavior.TestMistral3PatchMerger::test_numerical_matches_manual_unfold", "tests.tasksmith_behavior.TestMistral3PatchMerger::test_output_shape_reduces_token_count", "tests.tasksmith_behavior.TestMistral3PatchMerger::test_single_block_shape", "tests.tasksmith_behavior.TestPixtralImageResizeFloor::test_floor_semantics_secondary_dimension", "tests.tasksmith_behavior.TestPixtralProcessorSpatialMergeSize::test_custom_spatial_merge_size_stored", "tests.tasksmith_behavior.TestPixtralProcessorSpatialMergeSize::test_default_spatial_merge_size_is_one", "tests.tasksmith_behavior.TestPixtralProcessorSpatialMergeSize::test_token_count_halved_per_dimension_with_sms_2", "tests.tasksmith_behavior.TestPixtralAdjacentBehavior::test_pixtral_image_resize_no_downscale", "tests.tasksmith_behavior.TestPixtralAdjacentBehavior::test_pixtral_processor_basic_init", "tests.tasksmith_behavior.TestPixtralImageResizeFloor::test_output_does_not_exceed_longest_edge", "tests.tasksmith_behavior.TestMistral3ForConditionalGeneration::test_image_features_inserted_at_requested_positions"], "immutable_assets": {"src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp": "55c0869bd22bbe056f9b266dd0ac8fd7a43e38d99b7a0e9b2b071c3fa29a74bd", "src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h": "9ef56c2a3f6769b43b21a358e1d8b9c55c7abbed252227d0bcb836242a318a29", "src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu": "94e65769398aca8fac9353421719263ea54249cd50fbe753f533c7c8c24a3891", "src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh": "8b53dd1e599400659175104e087008d33f5267fb8f746e7dc439637e3b79ad83", "src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h": "c713f5eda7abf92894f49e4048b1ddb4b2328459870b988b70f20f356db192b8", "src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh": "d9babd28bb17c497c0f4b8ed4b714958f25d3d1d9376aeb878cc7409b989d643", "src/transformers/kernels/deformable_detr/ms_deform_attn.h": "3a57af9dd16066f1fa347a070d087caaa87c1416e0b9ac448950b5bc05c01615", "src/transformers/kernels/deformable_detr/vision.cpp": "f11bd9cbb3ff30cc79404b33a3f33034e0dd7492d0f2629c9a631f80b602fc70", "src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp": "55c0869bd22bbe056f9b266dd0ac8fd7a43e38d99b7a0e9b2b071c3fa29a74bd", "src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h": "9ef56c2a3f6769b43b21a358e1d8b9c55c7abbed252227d0bcb836242a318a29", "src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu": "339f9b5bd839cfeba94c530d3c87e7c8b02a293c463028c03ea06bd069961d7f", "src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh": "872801db4561dd1b6d392742b93173f15d1ddc25cda7e43cf71db6ad8983db9f", "src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.h": "acf58e38ca3743215d07990c89ec690292c567876746dc780a5b84006c2c7cef", "src/transformers/kernels/deta/cuda/ms_deform_im2col_cuda.cuh": "05137cfb27d21d8f0284b8a3f23165dbfcf62cbd0b1052ae545e81ca2f982c06", "src/transformers/kernels/deta/ms_deform_attn.h": "1f66c15c6ca5d11fafd83a86573d756aca11bf16e367d89607d763a26653a606", "src/transformers/kernels/deta/vision.cpp": "f11bd9cbb3ff30cc79404b33a3f33034e0dd7492d0f2629c9a631f80b602fc70", "src/transformers/kernels/mra/cuda_kernel.cu": "2f1c51613ca64a80444295971c0d0f333c19c29a257305fb985023c14f3e64c7", "src/transformers/kernels/mra/cuda_kernel.h": "509bd8abf303ce1729d3b6d9a5870e067f1918571ffc0c757729ee8954c1be60", "src/transformers/kernels/mra/cuda_launch.cu": "3b1e4c4c00ab882df4086ca7fa0d4a6f912041230065268de9fa62b77c4b1567", "src/transformers/kernels/mra/cuda_launch.h": "4550a437f7ae6acbe03cad33003351bd160659de1a87997d5feed41bf01c747f", "src/transformers/kernels/mra/torch_extension.cpp": "37461d04b557d2565a6dc909cd5fd16131d2d9ab4236f9f5dc4e08be86eddb98", "src/transformers/kernels/rwkv/wkv_cuda.cu": "12f694ac49f0feaaf612330a3fe3eaed53f315f1a53099c585d1cd2ed9f57cf5", "src/transformers/kernels/rwkv/wkv_cuda_bf16.cu": "0c6f614ed38096b9e90c56a18edf8c9a73b18ccba1194e7918fb26576d47b6b4", "src/transformers/kernels/rwkv/wkv_op.cpp": "a9213184a753ea9de1c9a4efe52ca90a71ff73b126697e876e14dc0a7b6f6568", "src/transformers/kernels/yoso/common.h": "4eadab394b44f18e0344052b4484afc08c15237bbc2417f6d568164806220e54", "src/transformers/kernels/yoso/common_cuda.h": "4a38bbd00b9572e652a2d2c5ec6a2d9ae9fd309b8e1e8f30124c62cca5cb46d7", "src/transformers/kernels/yoso/common_cuda_device.h": "cba59480089aa6730aaad851312e6cf8331258d5646abfe2f20e0a3c5bea8ae9", "src/transformers/kernels/yoso/fast_lsh_cumulation.cu": "2c0e0b18d8325d3de8b08c90b4505c45a9d2c8d4169bccaa9a9cfb01e2cfedcc", "src/transformers/kernels/yoso/fast_lsh_cumulation.h": "d5c4d66633a6ef9d471a2101e4ff943c9f1213554eed74725e6060cb1603ca32", "src/transformers/kernels/yoso/fast_lsh_cumulation_cuda.cu": "1ca18b5a5f96173e415e36803c74cd4db1ba2149098e105dbc57f62bb86b0d54", "src/transformers/kernels/yoso/fast_lsh_cumulation_cuda.h": "fca188f0741b545b423792807121a9ca22767e81a2dba44a7a7d77f0251cd9f6", "src/transformers/kernels/yoso/fast_lsh_cumulation_torch.cpp": "f9187ba37f59debb4e3f036710cf9ce754c2ab2c2955d2b4595680ed546b5db4", "src/transformers/models/deprecated/graphormer/algos_graphormer.pyx": "6ff4259b584a0879c0ab1ea838b182f4b922bc05742bf0194468174fd32605ab", "src/transformers/models/gpt2/CONVERSION.md": "b6cbcef5426171f9d976db671b3d123377a52f6f8b886d9e609f5c62260cd414", "src/transformers/models/t5/download_from_gcp.sh": "fc84d95897732720e883acd21482316ecaed3ab5d5209c288442e0bac7beef39"}, "optional_files": ["src/transformers/models/mistral3/__init__.py", "src/transformers/models/mistral3/configuration_mistral3.py", "src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py", "src/transformers/models/mistral3/modeling_mistral3.py", "src/transformers/models/mistral3/modular_mistral3.py"], "submitted_files": ["src/transformers/__init__.py", "src/transformers/activations.py", "src/transformers/activations_tf.py", "src/transformers/agents/__init__.py", "src/transformers/agents/agent_types.py", "src/transformers/agents/agents.py", "src/transformers/agents/default_tools.py", "src/transformers/agents/document_question_answering.py", "src/transformers/agents/evaluate_agent.py", "src/transformers/agents/image_question_answering.py", "src/transformers/agents/llm_engine.py", "src/transformers/agents/monitoring.py", "src/transformers/agents/prompts.py", "src/transformers/agents/python_interpreter.py", "src/transformers/agents/search.py", "src/transformers/agents/speech_to_text.py", "src/transformers/agents/text_to_speech.py", "src/transformers/agents/tools.py", "src/transformers/agents/translation.py", "src/transformers/audio_utils.py", "src/transformers/cache_utils.py", "src/transformers/commands/__init__.py", "src/transformers/commands/add_fast_image_processor.py", "src/transformers/commands/add_new_model_like.py", "src/transformers/commands/chat.py", "src/transformers/commands/convert.py", "src/transformers/commands/download.py", "src/transformers/commands/env.py", "src/transformers/commands/run.py", "src/transformers/commands/serving.py", "src/transformers/commands/train.py", "src/transformers/commands/transformers_cli.py", "src/transformers/configuration_utils.py", "src/transformers/convert_graph_to_onnx.py", "src/transformers/convert_pytorch_checkpoint_to_tf2.py", "src/transformers/convert_slow_tokenizer.py", "src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py", "src/transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py", "src/transformers/data/__init__.py", "src/transformers/data/data_collator.py", "src/transformers/data/datasets/__init__.py", "src/transformers/data/datasets/glue.py", "src/transformers/data/datasets/language_modeling.py", "src/transformers/data/datasets/squad.py", "src/transformers/data/metrics/__init__.py", "src/transformers/data/metrics/squad_metrics.py", "src/transformers/data/processors/__init__.py", "src/transformers/data/processors/glue.py", "src/transformers/data/processors/squad.py", "src/transformers/data/processors/utils.py", "src/transformers/data/processors/xnli.py", "src/transformers/debug_utils.py", "src/transformers/dependency_versions_check.py", "src/transformers/dependency_versions_table.py", "src/transformers/dynamic_module_utils.py", "src/transformers/feature_extraction_sequence_utils.py", "src/transformers/feature_extraction_utils.py", "src/transformers/file_utils.py", "src/transformers/generation/__init__.py", "src/transformers/generation/beam_constraints.py", "src/transformers/generation/beam_search.py", "src/transformers/generation/candidate_generator.py", "src/transformers/generation/configuration_utils.py", "src/transformers/generation/flax_logits_process.py", "src/transformers/generation/flax_utils.py", "src/transformers/generation/logits_process.py", "src/transformers/generation/stopping_criteria.py", "src/transformers/generation/streamers.py", "src/transformers/generation/tf_logits_process.py", "src/transformers/generation/tf_utils.py", "src/transformers/generation/utils.py", "src/transformers/generation/watermarking.py", "src/transformers/hf_argparser.py", "src/transformers/hyperparameter_search.py", "src/transformers/image_processing_base.py", "src/transformers/image_processing_utils.py", "src/transformers/image_processing_utils_fast.py", "src/transformers/image_transforms.py", "src/transformers/image_utils.py", "src/transformers/integrations/__init__.py", "src/transformers/integrations/aqlm.py", "src/transformers/integrations/awq.py", "src/transformers/integrations/bitnet.py", "src/transformers/integrations/bitsandbytes.py", "src/transformers/integrations/deepspeed.py", "src/transformers/integrations/eetq.py", "src/transformers/integrations/executorch.py", "src/transformers/integrations/fbgemm_fp8.py", "src/transformers/integrations/finegrained_fp8.py", "src/transformers/integrations/flash_attention.py", "src/transformers/integrations/flex_attention.py", "src/transformers/integrations/fsdp.py", "src/transformers/integrations/ggml.py", "src/transformers/integrations/higgs.py", "src/transformers/integrations/hqq.py", "src/transformers/integrations/integration_utils.py", "src/transformers/integrations/mistral.py", "src/transformers/integrations/peft.py", "src/transformers/integrations/quanto.py", "src/transformers/integrations/sdpa_attention.py", "src/transformers/integrations/spqr.py", "src/transformers/integrations/tensor_parallel.py", "src/transformers/integrations/tiktoken.py", "src/transformers/integrations/tpu.py", "src/transformers/integrations/vptq.py", "src/transformers/keras_callbacks.py", "src/transformers/kernels/__init__.py", "src/transformers/kernels/falcon_mamba/__init__.py", "src/transformers/kernels/falcon_mamba/selective_scan_with_ln_interface.py", "src/transformers/loss/__init__.py", "src/transformers/loss/loss_deformable_detr.py", "src/transformers/loss/loss_for_object_detection.py", "src/transformers/loss/loss_grounding_dino.py", "src/transformers/loss/loss_rt_detr.py", "src/transformers/loss/loss_utils.py", "src/transformers/modelcard.py", "src/transformers/modeling_attn_mask_utils.py", "src/transformers/modeling_flash_attention_utils.py", "src/transformers/modeling_flax_outputs.py", "src/transformers/modeling_flax_pytorch_utils.py", "src/transformers/modeling_flax_utils.py", "src/transformers/modeling_gguf_pytorch_utils.py", "src/transformers/modeling_outputs.py", "src/transformers/modeling_rope_utils.py", "src/transformers/modeling_tf_outputs.py", "src/transformers/modeling_tf_pytorch_utils.py", "src/transformers/modeling_tf_utils.py", "src/transformers/modeling_utils.py", "src/transformers/models/__init__.py", "src/transformers/models/albert/__init__.py", "src/transformers/models/albert/configuration_albert.py", "src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/albert/modeling_albert.py", "src/transformers/models/albert/modeling_flax_albert.py", "src/transformers/models/albert/modeling_tf_albert.py", "src/transformers/models/albert/tokenization_albert.py", "src/transformers/models/albert/tokenization_albert_fast.py", "src/transformers/models/align/__init__.py", "src/transformers/models/align/configuration_align.py", "src/transformers/models/align/convert_align_tf_to_hf.py", "src/transformers/models/align/modeling_align.py", "src/transformers/models/align/processing_align.py", "src/transformers/models/altclip/__init__.py", "src/transformers/models/altclip/configuration_altclip.py", "src/transformers/models/altclip/modeling_altclip.py", "src/transformers/models/altclip/processing_altclip.py", "src/transformers/models/aria/__init__.py", "src/transformers/models/aria/configuration_aria.py", "src/transformers/models/aria/convert_aria_weights_to_hf.py", "src/transformers/models/aria/image_processing_aria.py", "src/transformers/models/aria/modeling_aria.py", "src/transformers/models/aria/modular_aria.py", "src/transformers/models/aria/processing_aria.py", "src/transformers/models/audio_spectrogram_transformer/__init__.py", "src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py", "src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py", "src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py", "src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py", "src/transformers/models/auto/__init__.py", "src/transformers/models/auto/auto_factory.py", "src/transformers/models/auto/configuration_auto.py", "src/transformers/models/auto/feature_extraction_auto.py", "src/transformers/models/auto/image_processing_auto.py", "src/transformers/models/auto/modeling_auto.py", "src/transformers/models/auto/modeling_flax_auto.py", "src/transformers/models/auto/modeling_tf_auto.py", "src/transformers/models/auto/processing_auto.py", "src/transformers/models/auto/tokenization_auto.py", "src/transformers/models/autoformer/__init__.py", "src/transformers/models/autoformer/configuration_autoformer.py", "src/transformers/models/autoformer/modeling_autoformer.py", "src/transformers/models/aya_vision/__init__.py", "src/transformers/models/aya_vision/configuration_aya_vision.py", "src/transformers/models/aya_vision/modeling_aya_vision.py", "src/transformers/models/aya_vision/processing_aya_vision.py", "src/transformers/models/bamba/__init__.py", "src/transformers/models/bamba/configuration_bamba.py", "src/transformers/models/bamba/convert_mamba_ssm_checkpoint.py", "src/transformers/models/bamba/modeling_bamba.py", "src/transformers/models/bamba/modular_bamba.py", "src/transformers/models/bark/__init__.py", "src/transformers/models/bark/configuration_bark.py", "src/transformers/models/bark/convert_suno_to_hf.py", "src/transformers/models/bark/generation_configuration_bark.py", "src/transformers/models/bark/modeling_bark.py", "src/transformers/models/bark/processing_bark.py", "src/transformers/models/bart/__init__.py", "src/transformers/models/bart/configuration_bart.py", "src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/bart/modeling_bart.py", "src/transformers/models/bart/modeling_flax_bart.py", "src/transformers/models/bart/modeling_tf_bart.py", "src/transformers/models/bart/tokenization_bart.py", "src/transformers/models/bart/tokenization_bart_fast.py", "src/transformers/models/barthez/__init__.py", "src/transformers/models/barthez/tokenization_barthez.py", "src/transformers/models/barthez/tokenization_barthez_fast.py", "src/transformers/models/bartpho/__init__.py", "src/transformers/models/bartpho/tokenization_bartpho.py", "src/transformers/models/beit/__init__.py", "src/transformers/models/beit/configuration_beit.py", "src/transformers/models/beit/convert_beit_unilm_to_pytorch.py", "src/transformers/models/beit/feature_extraction_beit.py", "src/transformers/models/beit/image_processing_beit.py", "src/transformers/models/beit/modeling_beit.py", "src/transformers/models/beit/modeling_flax_beit.py", "src/transformers/models/bert/__init__.py", "src/transformers/models/bert/configuration_bert.py", "src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py", "src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py", "src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py", "src/transformers/models/bert/modeling_bert.py", "src/transformers/models/bert/modeling_flax_bert.py", "src/transformers/models/bert/modeling_tf_bert.py", "src/transformers/models/bert/tokenization_bert.py", "src/transformers/models/bert/tokenization_bert_fast.py", "src/transformers/models/bert/tokenization_bert_tf.py", "src/transformers/models/bert_generation/__init__.py", "src/transformers/models/bert_generation/configuration_bert_generation.py", "src/transformers/models/bert_generation/modeling_bert_generation.py", "src/transformers/models/bert_generation/tokenization_bert_generation.py", "src/transformers/models/bert_japanese/__init__.py", "src/transformers/models/bert_japanese/tokenization_bert_japanese.py", "src/transformers/models/bertweet/__init__.py", "src/transformers/models/bertweet/tokenization_bertweet.py", "src/transformers/models/big_bird/__init__.py", "src/transformers/models/big_bird/configuration_big_bird.py", "src/transformers/models/big_bird/convert_bigbird_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/big_bird/modeling_big_bird.py", "src/transformers/models/big_bird/modeling_flax_big_bird.py", "src/transformers/models/big_bird/tokenization_big_bird.py", "src/transformers/models/big_bird/tokenization_big_bird_fast.py", "src/transformers/models/bigbird_pegasus/__init__.py", "src/transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py", "src/transformers/models/bigbird_pegasus/convert_bigbird_pegasus_tf_to_pytorch.py", "src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py", "src/transformers/models/biogpt/__init__.py", "src/transformers/models/biogpt/configuration_biogpt.py", "src/transformers/models/biogpt/convert_biogpt_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/biogpt/modeling_biogpt.py", "src/transformers/models/biogpt/tokenization_biogpt.py", "src/transformers/models/bit/__init__.py", "src/transformers/models/bit/configuration_bit.py", "src/transformers/models/bit/convert_bit_to_pytorch.py", "src/transformers/models/bit/image_processing_bit.py", "src/transformers/models/bit/modeling_bit.py", "src/transformers/models/blenderbot/__init__.py", "src/transformers/models/blenderbot/configuration_blenderbot.py", "src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/blenderbot/modeling_blenderbot.py", "src/transformers/models/blenderbot/modeling_flax_blenderbot.py", "src/transformers/models/blenderbot/modeling_tf_blenderbot.py", "src/transformers/models/blenderbot/tokenization_blenderbot.py", "src/transformers/models/blenderbot/tokenization_blenderbot_fast.py", "src/transformers/models/blenderbot_small/__init__.py", "src/transformers/models/blenderbot_small/configuration_blenderbot_small.py", "src/transformers/models/blenderbot_small/modeling_blenderbot_small.py", "src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py", "src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py", "src/transformers/models/blenderbot_small/tokenization_blenderbot_small.py", "src/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py", "src/transformers/models/blip/__init__.py", "src/transformers/models/blip/configuration_blip.py", "src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py", "src/transformers/models/blip/image_processing_blip.py", "src/transformers/models/blip/image_processing_blip_fast.py", "src/transformers/models/blip/modeling_blip.py", "src/transformers/models/blip/modeling_blip_text.py", "src/transformers/models/blip/modeling_tf_blip.py", "src/transformers/models/blip/modeling_tf_blip_text.py", "src/transformers/models/blip/processing_blip.py", "src/transformers/models/blip_2/__init__.py", "src/transformers/models/blip_2/configuration_blip_2.py", "src/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py", "src/transformers/models/blip_2/modeling_blip_2.py", "src/transformers/models/blip_2/processing_blip_2.py", "src/transformers/models/bloom/__init__.py", "src/transformers/models/bloom/configuration_bloom.py", "src/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py", "src/transformers/models/bloom/modeling_bloom.py", "src/transformers/models/bloom/modeling_flax_bloom.py", "src/transformers/models/bloom/tokenization_bloom_fast.py", "src/transformers/models/bridgetower/__init__.py", "src/transformers/models/bridgetower/configuration_bridgetower.py", "src/transformers/models/bridgetower/image_processing_bridgetower.py", "src/transformers/models/bridgetower/modeling_bridgetower.py", "src/transformers/models/bridgetower/processing_bridgetower.py", "src/transformers/models/bros/__init__.py", "src/transformers/models/bros/configuration_bros.py", "src/transformers/models/bros/convert_bros_to_pytorch.py", "src/transformers/models/bros/modeling_bros.py", "src/transformers/models/bros/processing_bros.py", "src/transformers/models/byt5/__init__.py", "src/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/byt5/tokenization_byt5.py", "src/transformers/models/camembert/__init__.py", "src/transformers/models/camembert/configuration_camembert.py", "src/transformers/models/camembert/modeling_camembert.py", "src/transformers/models/camembert/modeling_tf_camembert.py", "src/transformers/models/camembert/tokenization_camembert.py", "src/transformers/models/camembert/tokenization_camembert_fast.py", "src/transformers/models/canine/__init__.py", "src/transformers/models/canine/configuration_canine.py", "src/transformers/models/canine/convert_canine_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/canine/modeling_canine.py", "src/transformers/models/canine/tokenization_canine.py", "src/transformers/models/chameleon/__init__.py", "src/transformers/models/chameleon/configuration_chameleon.py", "src/transformers/models/chameleon/convert_chameleon_weights_to_hf.py", "src/transformers/models/chameleon/image_processing_chameleon.py", "src/transformers/models/chameleon/modeling_chameleon.py", "src/transformers/models/chameleon/processing_chameleon.py", "src/transformers/models/chinese_clip/__init__.py", "src/transformers/models/chinese_clip/configuration_chinese_clip.py", "src/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py", "src/transformers/models/chinese_clip/feature_extraction_chinese_clip.py", "src/transformers/models/chinese_clip/image_processing_chinese_clip.py", "src/transformers/models/chinese_clip/modeling_chinese_clip.py", "src/transformers/models/chinese_clip/processing_chinese_clip.py", "src/transformers/models/clap/__init__.py", "src/transformers/models/clap/configuration_clap.py", "src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py", "src/transformers/models/clap/feature_extraction_clap.py", "src/transformers/models/clap/modeling_clap.py", "src/transformers/models/clap/processing_clap.py", "src/transformers/models/clip/__init__.py", "src/transformers/models/clip/configuration_clip.py", "src/transformers/models/clip/convert_clip_original_pytorch_to_hf.py", "src/transformers/models/clip/feature_extraction_clip.py", "src/transformers/models/clip/image_processing_clip.py", "src/transformers/models/clip/image_processing_clip_fast.py", "src/transformers/models/clip/modeling_clip.py", "src/transformers/models/clip/modeling_flax_clip.py", "src/transformers/models/clip/modeling_tf_clip.py", "src/transformers/models/clip/processing_clip.py", "src/transformers/models/clip/tokenization_clip.py", "src/transformers/models/clip/tokenization_clip_fast.py", "src/transformers/models/clipseg/__init__.py", "src/transformers/models/clipseg/configuration_clipseg.py", "src/transformers/models/clipseg/convert_clipseg_original_pytorch_to_hf.py", "src/transformers/models/clipseg/modeling_clipseg.py", "src/transformers/models/clipseg/processing_clipseg.py", "src/transformers/models/clvp/__init__.py", "src/transformers/models/clvp/configuration_clvp.py", "src/transformers/models/clvp/convert_clvp_to_hf.py", "src/transformers/models/clvp/feature_extraction_clvp.py", "src/transformers/models/clvp/modeling_clvp.py", "src/transformers/models/clvp/number_normalizer.py", "src/transformers/models/clvp/processing_clvp.py", "src/transformers/models/clvp/tokenization_clvp.py", "src/transformers/models/code_llama/__init__.py", "src/transformers/models/code_llama/tokenization_code_llama.py", "src/transformers/models/code_llama/tokenization_code_llama_fast.py", "src/transformers/models/codegen/__init__.py", "src/transformers/models/codegen/configuration_codegen.py", "src/transformers/models/codegen/modeling_codegen.py", "src/transformers/models/codegen/tokenization_codegen.py", "src/transformers/models/codegen/tokenization_codegen_fast.py", "src/transformers/models/cohere/__init__.py", "src/transformers/models/cohere/configuration_cohere.py", "src/transformers/models/cohere/modeling_cohere.py", "src/transformers/models/cohere/modular_cohere.py", "src/transformers/models/cohere/tokenization_cohere_fast.py", "src/transformers/models/cohere2/__init__.py", "src/transformers/models/cohere2/configuration_cohere2.py", "src/transformers/models/cohere2/modeling_cohere2.py", "src/transformers/models/cohere2/modular_cohere2.py", "src/transformers/models/colpali/__init__.py", "src/transformers/models/colpali/configuration_colpali.py", "src/transformers/models/colpali/convert_colpali_weights_to_hf.py", "src/transformers/models/colpali/modeling_colpali.py", "src/transformers/models/colpali/modular_colpali.py", "src/transformers/models/colpali/processing_colpali.py", "src/transformers/models/conditional_detr/__init__.py", "src/transformers/models/conditional_detr/configuration_conditional_detr.py", "src/transformers/models/conditional_detr/convert_conditional_detr_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/conditional_detr/feature_extraction_conditional_detr.py", "src/transformers/models/conditional_detr/image_processing_conditional_detr.py", "src/transformers/models/conditional_detr/modeling_conditional_detr.py", "src/transformers/models/convbert/__init__.py", "src/transformers/models/convbert/configuration_convbert.py", "src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py", "src/transformers/models/convbert/modeling_convbert.py", "src/transformers/models/convbert/modeling_tf_convbert.py", "src/transformers/models/convbert/tokenization_convbert.py", "src/transformers/models/convbert/tokenization_convbert_fast.py", "src/transformers/models/convnext/__init__.py", "src/transformers/models/convnext/configuration_convnext.py", "src/transformers/models/convnext/convert_convnext_to_pytorch.py", "src/transformers/models/convnext/feature_extraction_convnext.py", "src/transformers/models/convnext/image_processing_convnext.py", "src/transformers/models/convnext/image_processing_convnext_fast.py", "src/transformers/models/convnext/modeling_convnext.py", "src/transformers/models/convnext/modeling_tf_convnext.py", "src/transformers/models/convnextv2/__init__.py", "src/transformers/models/convnextv2/configuration_convnextv2.py", "src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py", "src/transformers/models/convnextv2/modeling_convnextv2.py", "src/transformers/models/convnextv2/modeling_tf_convnextv2.py", "src/transformers/models/cpm/__init__.py", "src/transformers/models/cpm/tokenization_cpm.py", "src/transformers/models/cpm/tokenization_cpm_fast.py", "src/transformers/models/cpmant/__init__.py", "src/transformers/models/cpmant/configuration_cpmant.py", "src/transformers/models/cpmant/modeling_cpmant.py", "src/transformers/models/cpmant/tokenization_cpmant.py", "src/transformers/models/ctrl/__init__.py", "src/transformers/models/ctrl/configuration_ctrl.py", "src/transformers/models/ctrl/modeling_ctrl.py", "src/transformers/models/ctrl/modeling_tf_ctrl.py", "src/transformers/models/ctrl/tokenization_ctrl.py", "src/transformers/models/cvt/__init__.py", "src/transformers/models/cvt/configuration_cvt.py", "src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/cvt/modeling_cvt.py", "src/transformers/models/cvt/modeling_tf_cvt.py", "src/transformers/models/dab_detr/__init__.py", "src/transformers/models/dab_detr/configuration_dab_detr.py", "src/transformers/models/dab_detr/convert_dab_detr_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/dab_detr/modeling_dab_detr.py", "src/transformers/models/dac/__init__.py", "src/transformers/models/dac/configuration_dac.py", "src/transformers/models/dac/convert_dac_checkpoint.py", "src/transformers/models/dac/feature_extraction_dac.py", "src/transformers/models/dac/modeling_dac.py", "src/transformers/models/data2vec/__init__.py", "src/transformers/models/data2vec/configuration_data2vec_audio.py", "src/transformers/models/data2vec/configuration_data2vec_text.py", "src/transformers/models/data2vec/configuration_data2vec_vision.py", "src/transformers/models/data2vec/convert_data2vec_audio_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/data2vec/convert_data2vec_text_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/data2vec/convert_data2vec_vision_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/data2vec/modeling_data2vec_audio.py", "src/transformers/models/data2vec/modeling_data2vec_text.py", "src/transformers/models/data2vec/modeling_data2vec_vision.py", "src/transformers/models/data2vec/modeling_tf_data2vec_vision.py", "src/transformers/models/dbrx/__init__.py", "src/transformers/models/dbrx/configuration_dbrx.py", "src/transformers/models/dbrx/modeling_dbrx.py", "src/transformers/models/deberta/__init__.py", "src/transformers/models/deberta/configuration_deberta.py", "src/transformers/models/deberta/modeling_deberta.py", "src/transformers/models/deberta/modeling_tf_deberta.py", "src/transformers/models/deberta/tokenization_deberta.py", "src/transformers/models/deberta/tokenization_deberta_fast.py", "src/transformers/models/deberta_v2/__init__.py", "src/transformers/models/deberta_v2/configuration_deberta_v2.py", "src/transformers/models/deberta_v2/modeling_deberta_v2.py", "src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py", "src/transformers/models/deberta_v2/tokenization_deberta_v2.py", "src/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py", "src/transformers/models/decision_transformer/__init__.py", "src/transformers/models/decision_transformer/configuration_decision_transformer.py", "src/transformers/models/decision_transformer/modeling_decision_transformer.py", "src/transformers/models/deformable_detr/__init__.py", "src/transformers/models/deformable_detr/configuration_deformable_detr.py", "src/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py", "src/transformers/models/deformable_detr/feature_extraction_deformable_detr.py", "src/transformers/models/deformable_detr/image_processing_deformable_detr.py", "src/transformers/models/deformable_detr/image_processing_deformable_detr_fast.py", "src/transformers/models/deformable_detr/load_custom.py", "src/transformers/models/deformable_detr/modeling_deformable_detr.py", "src/transformers/models/deformable_detr/modular_deformable_detr.py", "src/transformers/models/deit/__init__.py", "src/transformers/models/deit/configuration_deit.py", "src/transformers/models/deit/convert_deit_timm_to_pytorch.py", "src/transformers/models/deit/feature_extraction_deit.py", "src/transformers/models/deit/image_processing_deit.py", "src/transformers/models/deit/image_processing_deit_fast.py", "src/transformers/models/deit/modeling_deit.py", "src/transformers/models/deit/modeling_tf_deit.py", "src/transformers/models/deprecated/__init__.py", "src/transformers/models/deprecated/bort/__init__.py", "src/transformers/models/deprecated/bort/convert_bort_original_gluonnlp_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/deta/__init__.py", "src/transformers/models/deprecated/deta/configuration_deta.py", "src/transformers/models/deprecated/deta/convert_deta_resnet_to_pytorch.py", "src/transformers/models/deprecated/deta/convert_deta_swin_to_pytorch.py", "src/transformers/models/deprecated/deta/image_processing_deta.py", "src/transformers/models/deprecated/deta/modeling_deta.py", "src/transformers/models/deprecated/efficientformer/__init__.py", "src/transformers/models/deprecated/efficientformer/configuration_efficientformer.py", "src/transformers/models/deprecated/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py", "src/transformers/models/deprecated/efficientformer/modeling_efficientformer.py", "src/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py", "src/transformers/models/deprecated/ernie_m/__init__.py", "src/transformers/models/deprecated/ernie_m/configuration_ernie_m.py", "src/transformers/models/deprecated/ernie_m/modeling_ernie_m.py", "src/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py", "src/transformers/models/deprecated/gptsan_japanese/__init__.py", "src/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py", "src/transformers/models/deprecated/gptsan_japanese/convert_gptsan_tf_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py", "src/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py", "src/transformers/models/deprecated/graphormer/__init__.py", "src/transformers/models/deprecated/graphormer/collating_graphormer.py", "src/transformers/models/deprecated/graphormer/configuration_graphormer.py", "src/transformers/models/deprecated/graphormer/modeling_graphormer.py", "src/transformers/models/deprecated/jukebox/__init__.py", "src/transformers/models/deprecated/jukebox/configuration_jukebox.py", "src/transformers/models/deprecated/jukebox/convert_jukebox.py", "src/transformers/models/deprecated/jukebox/modeling_jukebox.py", "src/transformers/models/deprecated/jukebox/tokenization_jukebox.py", "src/transformers/models/deprecated/mctct/__init__.py", "src/transformers/models/deprecated/mctct/configuration_mctct.py", "src/transformers/models/deprecated/mctct/feature_extraction_mctct.py", "src/transformers/models/deprecated/mctct/modeling_mctct.py", "src/transformers/models/deprecated/mctct/processing_mctct.py", "src/transformers/models/deprecated/mega/__init__.py", "src/transformers/models/deprecated/mega/configuration_mega.py", "src/transformers/models/deprecated/mega/convert_mega_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/mega/modeling_mega.py", "src/transformers/models/deprecated/mmbt/__init__.py", "src/transformers/models/deprecated/mmbt/configuration_mmbt.py", "src/transformers/models/deprecated/mmbt/modeling_mmbt.py", "src/transformers/models/deprecated/nat/__init__.py", "src/transformers/models/deprecated/nat/configuration_nat.py", "src/transformers/models/deprecated/nat/modeling_nat.py", "src/transformers/models/deprecated/nezha/__init__.py", "src/transformers/models/deprecated/nezha/configuration_nezha.py", "src/transformers/models/deprecated/nezha/modeling_nezha.py", "src/transformers/models/deprecated/open_llama/__init__.py", "src/transformers/models/deprecated/open_llama/configuration_open_llama.py", "src/transformers/models/deprecated/open_llama/modeling_open_llama.py", "src/transformers/models/deprecated/qdqbert/__init__.py", "src/transformers/models/deprecated/qdqbert/configuration_qdqbert.py", "src/transformers/models/deprecated/qdqbert/modeling_qdqbert.py", "src/transformers/models/deprecated/realm/__init__.py", "src/transformers/models/deprecated/realm/configuration_realm.py", "src/transformers/models/deprecated/realm/modeling_realm.py", "src/transformers/models/deprecated/realm/retrieval_realm.py", "src/transformers/models/deprecated/realm/tokenization_realm.py", "src/transformers/models/deprecated/realm/tokenization_realm_fast.py", "src/transformers/models/deprecated/retribert/__init__.py", "src/transformers/models/deprecated/retribert/configuration_retribert.py", "src/transformers/models/deprecated/retribert/modeling_retribert.py", "src/transformers/models/deprecated/retribert/tokenization_retribert.py", "src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py", "src/transformers/models/deprecated/speech_to_text_2/__init__.py", "src/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py", "src/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py", "src/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py", "src/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py", "src/transformers/models/deprecated/tapex/__init__.py", "src/transformers/models/deprecated/tapex/tokenization_tapex.py", "src/transformers/models/deprecated/trajectory_transformer/__init__.py", "src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py", "src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py", "src/transformers/models/deprecated/transfo_xl/__init__.py", "src/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py", "src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py", "src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py", "src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py", "src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py", "src/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py", "src/transformers/models/deprecated/tvlt/__init__.py", "src/transformers/models/deprecated/tvlt/configuration_tvlt.py", "src/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py", "src/transformers/models/deprecated/tvlt/image_processing_tvlt.py", "src/transformers/models/deprecated/tvlt/modeling_tvlt.py", "src/transformers/models/deprecated/tvlt/processing_tvlt.py", "src/transformers/models/deprecated/van/__init__.py", "src/transformers/models/deprecated/van/configuration_van.py", "src/transformers/models/deprecated/van/convert_van_to_pytorch.py", "src/transformers/models/deprecated/van/modeling_van.py", "src/transformers/models/deprecated/vit_hybrid/__init__.py", "src/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py", "src/transformers/models/deprecated/vit_hybrid/convert_vit_hybrid_timm_to_pytorch.py", "src/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py", "src/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py", "src/transformers/models/deprecated/xlm_prophetnet/__init__.py", "src/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py", "src/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py", "src/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py", "src/transformers/models/depth_anything/__init__.py", "src/transformers/models/depth_anything/configuration_depth_anything.py", "src/transformers/models/depth_anything/convert_depth_anything_to_hf.py", "src/transformers/models/depth_anything/modeling_depth_anything.py", "src/transformers/models/depth_pro/__init__.py", "src/transformers/models/depth_pro/configuration_depth_pro.py", "src/transformers/models/depth_pro/convert_depth_pro_weights_to_hf.py", "src/transformers/models/depth_pro/image_processing_depth_pro.py", "src/transformers/models/depth_pro/image_processing_depth_pro_fast.py", "src/transformers/models/depth_pro/modeling_depth_pro.py", "src/transformers/models/detr/__init__.py", "src/transformers/models/detr/configuration_detr.py", "src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/detr/convert_detr_to_pytorch.py", "src/transformers/models/detr/feature_extraction_detr.py", "src/transformers/models/detr/image_processing_detr.py", "src/transformers/models/detr/image_processing_detr_fast.py", "src/transformers/models/detr/modeling_detr.py", "src/transformers/models/dialogpt/__init__.py", "src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/diffllama/__init__.py", "src/transformers/models/diffllama/configuration_diffllama.py", "src/transformers/models/diffllama/modeling_diffllama.py", "src/transformers/models/diffllama/modular_diffllama.py", "src/transformers/models/dinat/__init__.py", "src/transformers/models/dinat/configuration_dinat.py", "src/transformers/models/dinat/modeling_dinat.py", "src/transformers/models/dinov2/__init__.py", "src/transformers/models/dinov2/configuration_dinov2.py", "src/transformers/models/dinov2/convert_dinov2_to_hf.py", "src/transformers/models/dinov2/modeling_dinov2.py", "src/transformers/models/dinov2/modeling_flax_dinov2.py", "src/transformers/models/dinov2_with_registers/__init__.py", "src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py", "src/transformers/models/dinov2_with_registers/convert_dinov2_with_registers_to_hf.py", "src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py", "src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py", "src/transformers/models/distilbert/__init__.py", "src/transformers/models/distilbert/configuration_distilbert.py", "src/transformers/models/distilbert/modeling_distilbert.py", "src/transformers/models/distilbert/modeling_flax_distilbert.py", "src/transformers/models/distilbert/modeling_tf_distilbert.py", "src/transformers/models/distilbert/tokenization_distilbert.py", "src/transformers/models/distilbert/tokenization_distilbert_fast.py", "src/transformers/models/dit/__init__.py", "src/transformers/models/dit/convert_dit_unilm_to_pytorch.py", "src/transformers/models/donut/__init__.py", "src/transformers/models/donut/configuration_donut_swin.py", "src/transformers/models/donut/convert_donut_to_pytorch.py", "src/transformers/models/donut/feature_extraction_donut.py", "src/transformers/models/donut/image_processing_donut.py", "src/transformers/models/donut/modeling_donut_swin.py", "src/transformers/models/donut/processing_donut.py", "src/transformers/models/dpr/__init__.py", "src/transformers/models/dpr/configuration_dpr.py", "src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py", "src/transformers/models/dpr/modeling_dpr.py", "src/transformers/models/dpr/modeling_tf_dpr.py", "src/transformers/models/dpr/tokenization_dpr.py", "src/transformers/models/dpr/tokenization_dpr_fast.py", "src/transformers/models/dpt/__init__.py", "src/transformers/models/dpt/configuration_dpt.py", "src/transformers/models/dpt/convert_dinov2_depth_to_hf.py", "src/transformers/models/dpt/convert_dpt_beit_to_hf.py", "src/transformers/models/dpt/convert_dpt_hybrid_to_pytorch.py", "src/transformers/models/dpt/convert_dpt_swinv2_to_hf.py", "src/transformers/models/dpt/convert_dpt_to_pytorch.py", "src/transformers/models/dpt/feature_extraction_dpt.py", "src/transformers/models/dpt/image_processing_dpt.py", "src/transformers/models/dpt/modeling_dpt.py", "src/transformers/models/efficientnet/__init__.py", "src/transformers/models/efficientnet/configuration_efficientnet.py", "src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py", "src/transformers/models/efficientnet/image_processing_efficientnet.py", "src/transformers/models/efficientnet/modeling_efficientnet.py", "src/transformers/models/electra/__init__.py", "src/transformers/models/electra/configuration_electra.py", "src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/electra/modeling_electra.py", "src/transformers/models/electra/modeling_flax_electra.py", "src/transformers/models/electra/modeling_tf_electra.py", "src/transformers/models/electra/tokenization_electra.py", "src/transformers/models/electra/tokenization_electra_fast.py", "src/transformers/models/emu3/__init__.py", "src/transformers/models/emu3/configuration_emu3.py", "src/transformers/models/emu3/convert_emu3_weights_to_hf.py", "src/transformers/models/emu3/image_processing_emu3.py", "src/transformers/models/emu3/modeling_emu3.py", "src/transformers/models/emu3/modular_emu3.py", "src/transformers/models/emu3/processing_emu3.py", "src/transformers/models/encodec/__init__.py", "src/transformers/models/encodec/configuration_encodec.py", "src/transformers/models/encodec/convert_encodec_checkpoint_to_pytorch.py", "src/transformers/models/encodec/feature_extraction_encodec.py", "src/transformers/models/encodec/modeling_encodec.py", "src/transformers/models/encoder_decoder/__init__.py", "src/transformers/models/encoder_decoder/configuration_encoder_decoder.py", "src/transformers/models/encoder_decoder/modeling_encoder_decoder.py", "src/transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py", "src/transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py", "src/transformers/models/ernie/__init__.py", "src/transformers/models/ernie/configuration_ernie.py", "src/transformers/models/ernie/modeling_ernie.py", "src/transformers/models/esm/__init__.py", "src/transformers/models/esm/configuration_esm.py", "src/transformers/models/esm/convert_esm.py", "src/transformers/models/esm/modeling_esm.py", "src/transformers/models/esm/modeling_esmfold.py", "src/transformers/models/esm/modeling_tf_esm.py", "src/transformers/models/esm/openfold_utils/__init__.py", "src/transformers/models/esm/openfold_utils/chunk_utils.py", "src/transformers/models/esm/openfold_utils/data_transforms.py", "src/transformers/models/esm/openfold_utils/feats.py", "src/transformers/models/esm/openfold_utils/loss.py", "src/transformers/models/esm/openfold_utils/protein.py", "src/transformers/models/esm/openfold_utils/residue_constants.py", "src/transformers/models/esm/openfold_utils/rigid_utils.py", "src/transformers/models/esm/openfold_utils/tensor_utils.py", "src/transformers/models/esm/tokenization_esm.py", "src/transformers/models/falcon/__init__.py", "src/transformers/models/falcon/configuration_falcon.py", "src/transformers/models/falcon/convert_custom_code_checkpoint.py", "src/transformers/models/falcon/modeling_falcon.py", "src/transformers/models/falcon_mamba/__init__.py", "src/transformers/models/falcon_mamba/configuration_falcon_mamba.py", "src/transformers/models/falcon_mamba/modeling_falcon_mamba.py", "src/transformers/models/fastspeech2_conformer/__init__.py", "src/transformers/models/fastspeech2_conformer/configuration_fastspeech2_conformer.py", "src/transformers/models/fastspeech2_conformer/convert_fastspeech2_conformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/fastspeech2_conformer/convert_hifigan.py", "src/transformers/models/fastspeech2_conformer/convert_model_with_hifigan.py", "src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py", "src/transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py", "src/transformers/models/flaubert/__init__.py", "src/transformers/models/flaubert/configuration_flaubert.py", "src/transformers/models/flaubert/modeling_flaubert.py", "src/transformers/models/flaubert/modeling_tf_flaubert.py", "src/transformers/models/flaubert/tokenization_flaubert.py", "src/transformers/models/flava/__init__.py", "src/transformers/models/flava/configuration_flava.py", "src/transformers/models/flava/convert_dalle_to_flava_codebook.py", "src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py", "src/transformers/models/flava/feature_extraction_flava.py", "src/transformers/models/flava/image_processing_flava.py", "src/transformers/models/flava/modeling_flava.py", "src/transformers/models/flava/processing_flava.py", "src/transformers/models/fnet/__init__.py", "src/transformers/models/fnet/configuration_fnet.py", "src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py", "src/transformers/models/fnet/modeling_fnet.py", "src/transformers/models/fnet/tokenization_fnet.py", "src/transformers/models/fnet/tokenization_fnet_fast.py", "src/transformers/models/focalnet/__init__.py", "src/transformers/models/focalnet/configuration_focalnet.py", "src/transformers/models/focalnet/convert_focalnet_to_hf_format.py", "src/transformers/models/focalnet/modeling_focalnet.py", "src/transformers/models/fsmt/__init__.py", "src/transformers/models/fsmt/configuration_fsmt.py", "src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/fsmt/modeling_fsmt.py", "src/transformers/models/fsmt/tokenization_fsmt.py", "src/transformers/models/funnel/__init__.py", "src/transformers/models/funnel/configuration_funnel.py", "src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/funnel/modeling_funnel.py", "src/transformers/models/funnel/modeling_tf_funnel.py", "src/transformers/models/funnel/tokenization_funnel.py", "src/transformers/models/funnel/tokenization_funnel_fast.py", "src/transformers/models/fuyu/__init__.py", "src/transformers/models/fuyu/configuration_fuyu.py", "src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py", "src/transformers/models/fuyu/image_processing_fuyu.py", "src/transformers/models/fuyu/modeling_fuyu.py", "src/transformers/models/fuyu/processing_fuyu.py", "src/transformers/models/gemma/__init__.py", "src/transformers/models/gemma/configuration_gemma.py", "src/transformers/models/gemma/convert_gemma_weights_to_hf.py", "src/transformers/models/gemma/modeling_flax_gemma.py", "src/transformers/models/gemma/modeling_gemma.py", "src/transformers/models/gemma/modular_gemma.py", "src/transformers/models/gemma/tokenization_gemma.py", "src/transformers/models/gemma/tokenization_gemma_fast.py", "src/transformers/models/gemma2/__init__.py", "src/transformers/models/gemma2/configuration_gemma2.py", "src/transformers/models/gemma2/convert_gemma2_weights_to_hf.py", "src/transformers/models/gemma2/modeling_gemma2.py", "src/transformers/models/gemma2/modular_gemma2.py", "src/transformers/models/gemma3/__init__.py", "src/transformers/models/gemma3/configuration_gemma3.py", "src/transformers/models/gemma3/convert_gemma3_weights_orbax_to_hf.py", "src/transformers/models/gemma3/image_processing_gemma3.py", "src/transformers/models/gemma3/image_processing_gemma3_fast.py", "src/transformers/models/gemma3/modeling_gemma3.py", "src/transformers/models/gemma3/modular_gemma3.py", "src/transformers/models/gemma3/processing_gemma3.py", "src/transformers/models/git/__init__.py", "src/transformers/models/git/configuration_git.py", "src/transformers/models/git/convert_git_to_pytorch.py", "src/transformers/models/git/modeling_git.py", "src/transformers/models/git/processing_git.py", "src/transformers/models/glm/__init__.py", "src/transformers/models/glm/configuration_glm.py", "src/transformers/models/glm/convert_glm_weights_to_hf.py", "src/transformers/models/glm/modeling_glm.py", "src/transformers/models/glm/modular_glm.py", "src/transformers/models/glpn/__init__.py", "src/transformers/models/glpn/configuration_glpn.py", "src/transformers/models/glpn/convert_glpn_to_pytorch.py", "src/transformers/models/glpn/feature_extraction_glpn.py", "src/transformers/models/glpn/image_processing_glpn.py", "src/transformers/models/glpn/modeling_glpn.py", "src/transformers/models/got_ocr2/__init__.py", "src/transformers/models/got_ocr2/configuration_got_ocr2.py", "src/transformers/models/got_ocr2/convert_got_ocr2_weights_to_hf.py", "src/transformers/models/got_ocr2/image_processing_got_ocr2.py", "src/transformers/models/got_ocr2/image_processing_got_ocr2_fast.py", "src/transformers/models/got_ocr2/modeling_got_ocr2.py", "src/transformers/models/got_ocr2/modular_got_ocr2.py", "src/transformers/models/got_ocr2/processing_got_ocr2.py", "src/transformers/models/gpt2/__init__.py", "src/transformers/models/gpt2/configuration_gpt2.py", "src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/gpt2/modeling_flax_gpt2.py", "src/transformers/models/gpt2/modeling_gpt2.py", "src/transformers/models/gpt2/modeling_tf_gpt2.py", "src/transformers/models/gpt2/tokenization_gpt2.py", "src/transformers/models/gpt2/tokenization_gpt2_fast.py", "src/transformers/models/gpt2/tokenization_gpt2_tf.py", "src/transformers/models/gpt_bigcode/__init__.py", "src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py", "src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py", "src/transformers/models/gpt_neo/__init__.py", "src/transformers/models/gpt_neo/configuration_gpt_neo.py", "src/transformers/models/gpt_neo/convert_gpt_neo_mesh_tf_to_pytorch.py", "src/transformers/models/gpt_neo/modeling_flax_gpt_neo.py", "src/transformers/models/gpt_neo/modeling_gpt_neo.py", "src/transformers/models/gpt_neox/__init__.py", "src/transformers/models/gpt_neox/configuration_gpt_neox.py", "src/transformers/models/gpt_neox/modeling_gpt_neox.py", "src/transformers/models/gpt_neox/modular_gpt_neox.py", "src/transformers/models/gpt_neox/tokenization_gpt_neox_fast.py", "src/transformers/models/gpt_neox_japanese/__init__.py", "src/transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py", "src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py", "src/transformers/models/gpt_neox_japanese/tokenization_gpt_neox_japanese.py", "src/transformers/models/gpt_sw3/__init__.py", "src/transformers/models/gpt_sw3/convert_megatron_to_pytorch.py", "src/transformers/models/gpt_sw3/tokenization_gpt_sw3.py", "src/transformers/models/gptj/__init__.py", "src/transformers/models/gptj/configuration_gptj.py", "src/transformers/models/gptj/modeling_flax_gptj.py", "src/transformers/models/gptj/modeling_gptj.py", "src/transformers/models/gptj/modeling_tf_gptj.py", "src/transformers/models/granite/__init__.py", "src/transformers/models/granite/configuration_granite.py", "src/transformers/models/granite/modeling_granite.py", "src/transformers/models/granite/modular_granite.py", "src/transformers/models/granitemoe/__init__.py", "src/transformers/models/granitemoe/configuration_granitemoe.py", "src/transformers/models/granitemoe/modeling_granitemoe.py", "src/transformers/models/granitemoeshared/__init__.py", "src/transformers/models/granitemoeshared/configuration_granitemoeshared.py", "src/transformers/models/granitemoeshared/modeling_granitemoeshared.py", "src/transformers/models/granitemoeshared/modular_granitemoeshared.py", "src/transformers/models/grounding_dino/__init__.py", "src/transformers/models/grounding_dino/configuration_grounding_dino.py", "src/transformers/models/grounding_dino/convert_grounding_dino_to_hf.py", "src/transformers/models/grounding_dino/image_processing_grounding_dino.py", "src/transformers/models/grounding_dino/modeling_grounding_dino.py", "src/transformers/models/grounding_dino/processing_grounding_dino.py", "src/transformers/models/groupvit/__init__.py", "src/transformers/models/groupvit/configuration_groupvit.py", "src/transformers/models/groupvit/convert_groupvit_nvlab_to_hf.py", "src/transformers/models/groupvit/modeling_groupvit.py", "src/transformers/models/groupvit/modeling_tf_groupvit.py", "src/transformers/models/helium/__init__.py", "src/transformers/models/helium/configuration_helium.py", "src/transformers/models/helium/modeling_helium.py", "src/transformers/models/helium/modular_helium.py", "src/transformers/models/herbert/__init__.py", "src/transformers/models/herbert/tokenization_herbert.py", "src/transformers/models/herbert/tokenization_herbert_fast.py", "src/transformers/models/hiera/__init__.py", "src/transformers/models/hiera/configuration_hiera.py", "src/transformers/models/hiera/convert_hiera_to_hf.py", "src/transformers/models/hiera/modeling_hiera.py", "src/transformers/models/hubert/__init__.py", "src/transformers/models/hubert/configuration_hubert.py", "src/transformers/models/hubert/convert_distilhubert_original_s3prl_checkpoint_to_pytorch.py", "src/transformers/models/hubert/convert_hubert_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/hubert/convert_hubert_original_s3prl_checkpoint_to_pytorch.py", "src/transformers/models/hubert/modeling_hubert.py", "src/transformers/models/hubert/modeling_tf_hubert.py", "src/transformers/models/ibert/__init__.py", "src/transformers/models/ibert/configuration_ibert.py", "src/transformers/models/ibert/modeling_ibert.py", "src/transformers/models/ibert/quant_modules.py", "src/transformers/models/idefics/__init__.py", "src/transformers/models/idefics/configuration_idefics.py", "src/transformers/models/idefics/image_processing_idefics.py", "src/transformers/models/idefics/modeling_idefics.py", "src/transformers/models/idefics/modeling_tf_idefics.py", "src/transformers/models/idefics/perceiver.py", "src/transformers/models/idefics/perceiver_tf.py", "src/transformers/models/idefics/processing_idefics.py", "src/transformers/models/idefics/vision.py", "src/transformers/models/idefics/vision_tf.py", "src/transformers/models/idefics2/__init__.py", "src/transformers/models/idefics2/configuration_idefics2.py", "src/transformers/models/idefics2/convert_idefics2_weights_to_hf.py", "src/transformers/models/idefics2/image_processing_idefics2.py", "src/transformers/models/idefics2/modeling_idefics2.py", "src/transformers/models/idefics2/processing_idefics2.py", "src/transformers/models/idefics3/__init__.py", "src/transformers/models/idefics3/configuration_idefics3.py", "src/transformers/models/idefics3/convert_idefics3_weights_to_hf.py", "src/transformers/models/idefics3/image_processing_idefics3.py", "src/transformers/models/idefics3/modeling_idefics3.py", "src/transformers/models/idefics3/processing_idefics3.py", "src/transformers/models/ijepa/__init__.py", "src/transformers/models/ijepa/configuration_ijepa.py", "src/transformers/models/ijepa/convert_ijepa_to_hf.py", "src/transformers/models/ijepa/modeling_ijepa.py", "src/transformers/models/ijepa/modular_ijepa.py", "src/transformers/models/imagegpt/__init__.py", "src/transformers/models/imagegpt/configuration_imagegpt.py", "src/transformers/models/imagegpt/convert_imagegpt_original_tf2_to_pytorch.py", "src/transformers/models/imagegpt/feature_extraction_imagegpt.py", "src/transformers/models/imagegpt/image_processing_imagegpt.py", "src/transformers/models/imagegpt/modeling_imagegpt.py", "src/transformers/models/informer/__init__.py", "src/transformers/models/informer/configuration_informer.py", "src/transformers/models/informer/modeling_informer.py", "src/transformers/models/instructblip/__init__.py", "src/transformers/models/instructblip/configuration_instructblip.py", "src/transformers/models/instructblip/convert_instructblip_original_to_pytorch.py", "src/transformers/models/instructblip/modeling_instructblip.py", "src/transformers/models/instructblip/processing_instructblip.py", "src/transformers/models/instructblipvideo/__init__.py", "src/transformers/models/instructblipvideo/configuration_instructblipvideo.py", "src/transformers/models/instructblipvideo/convert_instructblipvideo_original_to_pytorch.py", "src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py", "src/transformers/models/instructblipvideo/modeling_instructblipvideo.py", "src/transformers/models/instructblipvideo/modular_instructblipvideo.py", "src/transformers/models/instructblipvideo/processing_instructblipvideo.py", "src/transformers/models/jamba/__init__.py", "src/transformers/models/jamba/configuration_jamba.py", "src/transformers/models/jamba/modeling_jamba.py", "src/transformers/models/jetmoe/__init__.py", "src/transformers/models/jetmoe/configuration_jetmoe.py", "src/transformers/models/jetmoe/modeling_jetmoe.py", "src/transformers/models/kosmos2/__init__.py", "src/transformers/models/kosmos2/configuration_kosmos2.py", "src/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/kosmos2/modeling_kosmos2.py", "src/transformers/models/kosmos2/processing_kosmos2.py", "src/transformers/models/layoutlm/__init__.py", "src/transformers/models/layoutlm/configuration_layoutlm.py", "src/transformers/models/layoutlm/modeling_layoutlm.py", "src/transformers/models/layoutlm/modeling_tf_layoutlm.py", "src/transformers/models/layoutlm/tokenization_layoutlm.py", "src/transformers/models/layoutlm/tokenization_layoutlm_fast.py", "src/transformers/models/layoutlmv2/__init__.py", "src/transformers/models/layoutlmv2/configuration_layoutlmv2.py", "src/transformers/models/layoutlmv2/feature_extraction_layoutlmv2.py", "src/transformers/models/layoutlmv2/image_processing_layoutlmv2.py", "src/transformers/models/layoutlmv2/modeling_layoutlmv2.py", "src/transformers/models/layoutlmv2/processing_layoutlmv2.py", "src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py", "src/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py", "src/transformers/models/layoutlmv3/__init__.py", "src/transformers/models/layoutlmv3/configuration_layoutlmv3.py", "src/transformers/models/layoutlmv3/feature_extraction_layoutlmv3.py", "src/transformers/models/layoutlmv3/image_processing_layoutlmv3.py", "src/transformers/models/layoutlmv3/modeling_layoutlmv3.py", "src/transformers/models/layoutlmv3/modeling_tf_layoutlmv3.py", "src/transformers/models/layoutlmv3/processing_layoutlmv3.py", "src/transformers/models/layoutlmv3/tokenization_layoutlmv3.py", "src/transformers/models/layoutlmv3/tokenization_layoutlmv3_fast.py", "src/transformers/models/layoutxlm/__init__.py", "src/transformers/models/layoutxlm/processing_layoutxlm.py", "src/transformers/models/layoutxlm/tokenization_layoutxlm.py", "src/transformers/models/layoutxlm/tokenization_layoutxlm_fast.py", "src/transformers/models/led/__init__.py", "src/transformers/models/led/configuration_led.py", "src/transformers/models/led/modeling_led.py", "src/transformers/models/led/modeling_tf_led.py", "src/transformers/models/led/tokenization_led.py", "src/transformers/models/led/tokenization_led_fast.py", "src/transformers/models/levit/__init__.py", "src/transformers/models/levit/configuration_levit.py", "src/transformers/models/levit/convert_levit_timm_to_pytorch.py", "src/transformers/models/levit/feature_extraction_levit.py", "src/transformers/models/levit/image_processing_levit.py", "src/transformers/models/levit/modeling_levit.py", "src/transformers/models/lilt/__init__.py", "src/transformers/models/lilt/configuration_lilt.py", "src/transformers/models/lilt/modeling_lilt.py", "src/transformers/models/llama/__init__.py", "src/transformers/models/llama/configuration_llama.py", "src/transformers/models/llama/convert_llama_weights_to_hf.py", "src/transformers/models/llama/modeling_flax_llama.py", "src/transformers/models/llama/modeling_llama.py", "src/transformers/models/llama/tokenization_llama.py", "src/transformers/models/llama/tokenization_llama_fast.py", "src/transformers/models/llava/__init__.py", "src/transformers/models/llava/configuration_llava.py", "src/transformers/models/llava/convert_llava_weights_to_hf.py", "src/transformers/models/llava/image_processing_llava.py", "src/transformers/models/llava/image_processing_llava_fast.py", "src/transformers/models/llava/modeling_llava.py", "src/transformers/models/llava/processing_llava.py", "src/transformers/models/llava_next/__init__.py", "src/transformers/models/llava_next/configuration_llava_next.py", "src/transformers/models/llava_next/convert_llava_next_weights_to_hf.py", "src/transformers/models/llava_next/image_processing_llava_next.py", "src/transformers/models/llava_next/image_processing_llava_next_fast.py", "src/transformers/models/llava_next/modeling_llava_next.py", "src/transformers/models/llava_next/processing_llava_next.py", "src/transformers/models/llava_next_video/__init__.py", "src/transformers/models/llava_next_video/configuration_llava_next_video.py", "src/transformers/models/llava_next_video/convert_llava_next_video_weights_to_hf.py", "src/transformers/models/llava_next_video/image_processing_llava_next_video.py", "src/transformers/models/llava_next_video/modeling_llava_next_video.py", "src/transformers/models/llava_next_video/modular_llava_next_video.py", "src/transformers/models/llava_next_video/processing_llava_next_video.py", "src/transformers/models/llava_onevision/__init__.py", "src/transformers/models/llava_onevision/configuration_llava_onevision.py", "src/transformers/models/llava_onevision/convert_llava_onevision_weights_to_hf.py", "src/transformers/models/llava_onevision/image_processing_llava_onevision.py", "src/transformers/models/llava_onevision/image_processing_llava_onevision_fast.py", "src/transformers/models/llava_onevision/modeling_llava_onevision.py", "src/transformers/models/llava_onevision/modular_llava_onevision.py", "src/transformers/models/llava_onevision/processing_llava_onevision.py", "src/transformers/models/llava_onevision/video_processing_llava_onevision.py", "src/transformers/models/longformer/__init__.py", "src/transformers/models/longformer/configuration_longformer.py", "src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py", "src/transformers/models/longformer/modeling_longformer.py", "src/transformers/models/longformer/modeling_tf_longformer.py", "src/transformers/models/longformer/tokenization_longformer.py", "src/transformers/models/longformer/tokenization_longformer_fast.py", "src/transformers/models/longt5/__init__.py", "src/transformers/models/longt5/configuration_longt5.py", "src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py", "src/transformers/models/longt5/modeling_flax_longt5.py", "src/transformers/models/longt5/modeling_longt5.py", "src/transformers/models/luke/__init__.py", "src/transformers/models/luke/configuration_luke.py", "src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/luke/modeling_luke.py", "src/transformers/models/luke/tokenization_luke.py", "src/transformers/models/lxmert/__init__.py", "src/transformers/models/lxmert/configuration_lxmert.py", "src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/lxmert/modeling_lxmert.py", "src/transformers/models/lxmert/modeling_tf_lxmert.py", "src/transformers/models/lxmert/tokenization_lxmert.py", "src/transformers/models/lxmert/tokenization_lxmert_fast.py", "src/transformers/models/m2m_100/__init__.py", "src/transformers/models/m2m_100/configuration_m2m_100.py", "src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py", "src/transformers/models/m2m_100/modeling_m2m_100.py", "src/transformers/models/m2m_100/tokenization_m2m_100.py", "src/transformers/models/mamba/__init__.py", "src/transformers/models/mamba/configuration_mamba.py", "src/transformers/models/mamba/convert_mamba_ssm_checkpoint_to_pytorch.py", "src/transformers/models/mamba/modeling_mamba.py", "src/transformers/models/mamba2/__init__.py", "src/transformers/models/mamba2/configuration_mamba2.py", "src/transformers/models/mamba2/convert_mamba2_ssm_checkpoint_to_pytorch.py", "src/transformers/models/mamba2/modeling_mamba2.py", "src/transformers/models/marian/__init__.py", "src/transformers/models/marian/configuration_marian.py", "src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py", "src/transformers/models/marian/convert_marian_to_pytorch.py", "src/transformers/models/marian/modeling_flax_marian.py", "src/transformers/models/marian/modeling_marian.py", "src/transformers/models/marian/modeling_tf_marian.py", "src/transformers/models/marian/tokenization_marian.py", "src/transformers/models/markuplm/__init__.py", "src/transformers/models/markuplm/configuration_markuplm.py", "src/transformers/models/markuplm/feature_extraction_markuplm.py", "src/transformers/models/markuplm/modeling_markuplm.py", "src/transformers/models/markuplm/processing_markuplm.py", "src/transformers/models/markuplm/tokenization_markuplm.py", "src/transformers/models/markuplm/tokenization_markuplm_fast.py", "src/transformers/models/mask2former/__init__.py", "src/transformers/models/mask2former/configuration_mask2former.py", "src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/mask2former/image_processing_mask2former.py", "src/transformers/models/mask2former/modeling_mask2former.py", "src/transformers/models/maskformer/__init__.py", "src/transformers/models/maskformer/configuration_maskformer.py", "src/transformers/models/maskformer/configuration_maskformer_swin.py", "src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/maskformer/convert_maskformer_resnet_to_pytorch.py", "src/transformers/models/maskformer/convert_maskformer_swin_to_pytorch.py", "src/transformers/models/maskformer/feature_extraction_maskformer.py", "src/transformers/models/maskformer/image_processing_maskformer.py", "src/transformers/models/maskformer/modeling_maskformer.py", "src/transformers/models/maskformer/modeling_maskformer_swin.py", "src/transformers/models/mbart/__init__.py", "src/transformers/models/mbart/configuration_mbart.py", "src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py", "src/transformers/models/mbart/modeling_flax_mbart.py", "src/transformers/models/mbart/modeling_mbart.py", "src/transformers/models/mbart/modeling_tf_mbart.py", "src/transformers/models/mbart/tokenization_mbart.py", "src/transformers/models/mbart/tokenization_mbart_fast.py", "src/transformers/models/mbart50/__init__.py", "src/transformers/models/mbart50/tokenization_mbart50.py", "src/transformers/models/mbart50/tokenization_mbart50_fast.py", "src/transformers/models/megatron_bert/__init__.py", "src/transformers/models/megatron_bert/configuration_megatron_bert.py", "src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py", "src/transformers/models/megatron_bert/modeling_megatron_bert.py", "src/transformers/models/megatron_gpt2/__init__.py", "src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py", "src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py", "src/transformers/models/mgp_str/__init__.py", "src/transformers/models/mgp_str/configuration_mgp_str.py", "src/transformers/models/mgp_str/modeling_mgp_str.py", "src/transformers/models/mgp_str/processing_mgp_str.py", "src/transformers/models/mgp_str/tokenization_mgp_str.py", "src/transformers/models/mimi/__init__.py", "src/transformers/models/mimi/configuration_mimi.py", "src/transformers/models/mimi/convert_mimi_checkpoint_to_pytorch.py", "src/transformers/models/mimi/modeling_mimi.py", "src/transformers/models/mistral/__init__.py", "src/transformers/models/mistral/configuration_mistral.py", "src/transformers/models/mistral/convert_mistral_weights_to_hf.py", "src/transformers/models/mistral/modeling_flax_mistral.py", "src/transformers/models/mistral/modeling_mistral.py", "src/transformers/models/mistral/modeling_tf_mistral.py", "src/transformers/models/mistral/modular_mistral.py", "src/transformers/models/mistral3/__init__.py", "src/transformers/models/mistral3/configuration_mistral3.py", "src/transformers/models/mistral3/convert_mistral3_weights_to_hf.py", "src/transformers/models/mistral3/modeling_mistral3.py", "src/transformers/models/mistral3/modular_mistral3.py", "src/transformers/models/mixtral/__init__.py", "src/transformers/models/mixtral/configuration_mixtral.py", "src/transformers/models/mixtral/convert_mixtral_weights_to_hf.py", "src/transformers/models/mixtral/modeling_mixtral.py", "src/transformers/models/mixtral/modular_mixtral.py", "src/transformers/models/mllama/__init__.py", "src/transformers/models/mllama/configuration_mllama.py", "src/transformers/models/mllama/convert_mllama_weights_to_hf.py", "src/transformers/models/mllama/image_processing_mllama.py", "src/transformers/models/mllama/modeling_mllama.py", "src/transformers/models/mllama/processing_mllama.py", "src/transformers/models/mluke/__init__.py", "src/transformers/models/mluke/convert_mluke_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/mluke/tokenization_mluke.py", "src/transformers/models/mobilebert/__init__.py", "src/transformers/models/mobilebert/configuration_mobilebert.py", "src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/mobilebert/modeling_mobilebert.py", "src/transformers/models/mobilebert/modeling_tf_mobilebert.py", "src/transformers/models/mobilebert/tokenization_mobilebert.py", "src/transformers/models/mobilebert/tokenization_mobilebert_fast.py", "src/transformers/models/mobilenet_v1/__init__.py", "src/transformers/models/mobilenet_v1/configuration_mobilenet_v1.py", "src/transformers/models/mobilenet_v1/convert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/mobilenet_v1/feature_extraction_mobilenet_v1.py", "src/transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py", "src/transformers/models/mobilenet_v1/modeling_mobilenet_v1.py", "src/transformers/models/mobilenet_v2/__init__.py", "src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py", "src/transformers/models/mobilenet_v2/convert_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/mobilenet_v2/feature_extraction_mobilenet_v2.py", "src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py", "src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py", "src/transformers/models/mobilevit/__init__.py", "src/transformers/models/mobilevit/configuration_mobilevit.py", "src/transformers/models/mobilevit/convert_mlcvnets_to_pytorch.py", "src/transformers/models/mobilevit/feature_extraction_mobilevit.py", "src/transformers/models/mobilevit/image_processing_mobilevit.py", "src/transformers/models/mobilevit/modeling_mobilevit.py", "src/transformers/models/mobilevit/modeling_tf_mobilevit.py", "src/transformers/models/mobilevitv2/__init__.py", "src/transformers/models/mobilevitv2/configuration_mobilevitv2.py", "src/transformers/models/mobilevitv2/convert_mlcvnets_to_pytorch.py", "src/transformers/models/mobilevitv2/modeling_mobilevitv2.py", "src/transformers/models/modernbert/__init__.py", "src/transformers/models/modernbert/configuration_modernbert.py", "src/transformers/models/modernbert/modeling_modernbert.py", "src/transformers/models/modernbert/modular_modernbert.py", "src/transformers/models/moonshine/__init__.py", "src/transformers/models/moonshine/configuration_moonshine.py", "src/transformers/models/moonshine/convert_usefulsensors_to_hf.py", "src/transformers/models/moonshine/modeling_moonshine.py", "src/transformers/models/moonshine/modular_moonshine.py", "src/transformers/models/moshi/__init__.py", "src/transformers/models/moshi/configuration_moshi.py", "src/transformers/models/moshi/convert_moshi_transformers.py", "src/transformers/models/moshi/modeling_moshi.py", "src/transformers/models/mpnet/__init__.py", "src/transformers/models/mpnet/configuration_mpnet.py", "src/transformers/models/mpnet/modeling_mpnet.py", "src/transformers/models/mpnet/modeling_tf_mpnet.py", "src/transformers/models/mpnet/tokenization_mpnet.py", "src/transformers/models/mpnet/tokenization_mpnet_fast.py", "src/transformers/models/mpt/__init__.py", "src/transformers/models/mpt/configuration_mpt.py", "src/transformers/models/mpt/modeling_mpt.py", "src/transformers/models/mra/__init__.py", "src/transformers/models/mra/configuration_mra.py", "src/transformers/models/mra/convert_mra_pytorch_to_pytorch.py", "src/transformers/models/mra/modeling_mra.py", "src/transformers/models/mt5/__init__.py", "src/transformers/models/mt5/configuration_mt5.py", "src/transformers/models/mt5/modeling_flax_mt5.py", "src/transformers/models/mt5/modeling_mt5.py", "src/transformers/models/mt5/modeling_tf_mt5.py", "src/transformers/models/mt5/tokenization_mt5.py", "src/transformers/models/mt5/tokenization_mt5_fast.py", "src/transformers/models/musicgen/__init__.py", "src/transformers/models/musicgen/configuration_musicgen.py", "src/transformers/models/musicgen/convert_musicgen_transformers.py", "src/transformers/models/musicgen/modeling_musicgen.py", "src/transformers/models/musicgen/processing_musicgen.py", "src/transformers/models/musicgen_melody/__init__.py", "src/transformers/models/musicgen_melody/configuration_musicgen_melody.py", "src/transformers/models/musicgen_melody/convert_musicgen_melody_transformers.py", "src/transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py", "src/transformers/models/musicgen_melody/modeling_musicgen_melody.py", "src/transformers/models/musicgen_melody/processing_musicgen_melody.py", "src/transformers/models/mvp/__init__.py", "src/transformers/models/mvp/configuration_mvp.py", "src/transformers/models/mvp/modeling_mvp.py", "src/transformers/models/mvp/tokenization_mvp.py", "src/transformers/models/mvp/tokenization_mvp_fast.py", "src/transformers/models/myt5/__init__.py", "src/transformers/models/myt5/convert_myt5_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/myt5/tokenization_myt5.py", "src/transformers/models/nemotron/__init__.py", "src/transformers/models/nemotron/configuration_nemotron.py", "src/transformers/models/nemotron/convert_nemotron_nemo_to_hf.py", "src/transformers/models/nemotron/modeling_nemotron.py", "src/transformers/models/nllb/__init__.py", "src/transformers/models/nllb/tokenization_nllb.py", "src/transformers/models/nllb/tokenization_nllb_fast.py", "src/transformers/models/nllb_moe/__init__.py", "src/transformers/models/nllb_moe/configuration_nllb_moe.py", "src/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py", "src/transformers/models/nllb_moe/modeling_nllb_moe.py", "src/transformers/models/nougat/__init__.py", "src/transformers/models/nougat/convert_nougat_to_hf.py", "src/transformers/models/nougat/image_processing_nougat.py", "src/transformers/models/nougat/processing_nougat.py", "src/transformers/models/nougat/tokenization_nougat_fast.py", "src/transformers/models/nystromformer/__init__.py", "src/transformers/models/nystromformer/configuration_nystromformer.py", "src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/nystromformer/modeling_nystromformer.py", "src/transformers/models/olmo/__init__.py", "src/transformers/models/olmo/configuration_olmo.py", "src/transformers/models/olmo/convert_olmo_weights_to_hf.py", "src/transformers/models/olmo/modeling_olmo.py", "src/transformers/models/olmo/modular_olmo.py", "src/transformers/models/olmo2/__init__.py", "src/transformers/models/olmo2/configuration_olmo2.py", "src/transformers/models/olmo2/convert_olmo2_weights_to_hf.py", "src/transformers/models/olmo2/modeling_olmo2.py", "src/transformers/models/olmo2/modular_olmo2.py", "src/transformers/models/olmoe/__init__.py", "src/transformers/models/olmoe/configuration_olmoe.py", "src/transformers/models/olmoe/convert_olmoe_weights_to_hf.py", "src/transformers/models/olmoe/modeling_olmoe.py", "src/transformers/models/omdet_turbo/__init__.py", "src/transformers/models/omdet_turbo/configuration_omdet_turbo.py", "src/transformers/models/omdet_turbo/convert_omdet_turbo_to_hf.py", "src/transformers/models/omdet_turbo/modeling_omdet_turbo.py", "src/transformers/models/omdet_turbo/processing_omdet_turbo.py", "src/transformers/models/oneformer/__init__.py", "src/transformers/models/oneformer/configuration_oneformer.py", "src/transformers/models/oneformer/convert_to_hf_oneformer.py", "src/transformers/models/oneformer/image_processing_oneformer.py", "src/transformers/models/oneformer/modeling_oneformer.py", "src/transformers/models/oneformer/processing_oneformer.py", "src/transformers/models/openai/__init__.py", "src/transformers/models/openai/configuration_openai.py", "src/transformers/models/openai/convert_openai_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/openai/modeling_openai.py", "src/transformers/models/openai/modeling_tf_openai.py", "src/transformers/models/openai/tokenization_openai.py", "src/transformers/models/openai/tokenization_openai_fast.py", "src/transformers/models/opt/__init__.py", "src/transformers/models/opt/configuration_opt.py", "src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/opt/modeling_flax_opt.py", "src/transformers/models/opt/modeling_opt.py", "src/transformers/models/opt/modeling_tf_opt.py", "src/transformers/models/owlv2/__init__.py", "src/transformers/models/owlv2/configuration_owlv2.py", "src/transformers/models/owlv2/convert_owlv2_to_hf.py", "src/transformers/models/owlv2/image_processing_owlv2.py", "src/transformers/models/owlv2/modeling_owlv2.py", "src/transformers/models/owlv2/processing_owlv2.py", "src/transformers/models/owlvit/__init__.py", "src/transformers/models/owlvit/configuration_owlvit.py", "src/transformers/models/owlvit/convert_owlvit_original_flax_to_hf.py", "src/transformers/models/owlvit/feature_extraction_owlvit.py", "src/transformers/models/owlvit/image_processing_owlvit.py", "src/transformers/models/owlvit/modeling_owlvit.py", "src/transformers/models/owlvit/processing_owlvit.py", "src/transformers/models/paligemma/__init__.py", "src/transformers/models/paligemma/configuration_paligemma.py", "src/transformers/models/paligemma/convert_paligemma2_weights_to_hf.py", "src/transformers/models/paligemma/convert_paligemma_weights_to_hf.py", "src/transformers/models/paligemma/modeling_paligemma.py", "src/transformers/models/paligemma/processing_paligemma.py", "src/transformers/models/patchtsmixer/__init__.py", "src/transformers/models/patchtsmixer/configuration_patchtsmixer.py", "src/transformers/models/patchtsmixer/modeling_patchtsmixer.py", "src/transformers/models/patchtst/__init__.py", "src/transformers/models/patchtst/configuration_patchtst.py", "src/transformers/models/patchtst/modeling_patchtst.py", "src/transformers/models/pegasus/__init__.py", "src/transformers/models/pegasus/configuration_pegasus.py", "src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py", "src/transformers/models/pegasus/modeling_flax_pegasus.py", "src/transformers/models/pegasus/modeling_pegasus.py", "src/transformers/models/pegasus/modeling_tf_pegasus.py", "src/transformers/models/pegasus/tokenization_pegasus.py", "src/transformers/models/pegasus/tokenization_pegasus_fast.py", "src/transformers/models/pegasus_x/__init__.py", "src/transformers/models/pegasus_x/configuration_pegasus_x.py", "src/transformers/models/pegasus_x/modeling_pegasus_x.py", "src/transformers/models/perceiver/__init__.py", "src/transformers/models/perceiver/configuration_perceiver.py", "src/transformers/models/perceiver/convert_perceiver_haiku_to_pytorch.py", "src/transformers/models/perceiver/feature_extraction_perceiver.py", "src/transformers/models/perceiver/image_processing_perceiver.py", "src/transformers/models/perceiver/modeling_perceiver.py", "src/transformers/models/perceiver/tokenization_perceiver.py", "src/transformers/models/persimmon/__init__.py", "src/transformers/models/persimmon/configuration_persimmon.py", "src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py", "src/transformers/models/persimmon/modeling_persimmon.py", "src/transformers/models/phi/__init__.py", "src/transformers/models/phi/configuration_phi.py", "src/transformers/models/phi/convert_phi_weights_to_hf.py", "src/transformers/models/phi/modeling_phi.py", "src/transformers/models/phi/modular_phi.py", "src/transformers/models/phi3/__init__.py", "src/transformers/models/phi3/configuration_phi3.py", "src/transformers/models/phi3/modeling_phi3.py", "src/transformers/models/phi3/modular_phi3.py", "src/transformers/models/phimoe/__init__.py", "src/transformers/models/phimoe/configuration_phimoe.py", "src/transformers/models/phimoe/modeling_phimoe.py", "src/transformers/models/phobert/__init__.py", "src/transformers/models/phobert/tokenization_phobert.py", "src/transformers/models/pix2struct/__init__.py", "src/transformers/models/pix2struct/configuration_pix2struct.py", "src/transformers/models/pix2struct/convert_pix2struct_original_pytorch_to_hf.py", "src/transformers/models/pix2struct/image_processing_pix2struct.py", "src/transformers/models/pix2struct/modeling_pix2struct.py", "src/transformers/models/pix2struct/processing_pix2struct.py", "src/transformers/models/pixtral/__init__.py", "src/transformers/models/pixtral/configuration_pixtral.py", "src/transformers/models/pixtral/convert_pixtral_weights_to_hf.py", "src/transformers/models/pixtral/image_processing_pixtral.py", "src/transformers/models/pixtral/image_processing_pixtral_fast.py", "src/transformers/models/pixtral/modeling_pixtral.py", "src/transformers/models/pixtral/processing_pixtral.py", "src/transformers/models/plbart/__init__.py", "src/transformers/models/plbart/configuration_plbart.py", "src/transformers/models/plbart/convert_plbart_original_checkpoint_to_torch.py", "src/transformers/models/plbart/modeling_plbart.py", "src/transformers/models/plbart/tokenization_plbart.py", "src/transformers/models/poolformer/__init__.py", "src/transformers/models/poolformer/configuration_poolformer.py", "src/transformers/models/poolformer/convert_poolformer_original_to_pytorch.py", "src/transformers/models/poolformer/feature_extraction_poolformer.py", "src/transformers/models/poolformer/image_processing_poolformer.py", "src/transformers/models/poolformer/modeling_poolformer.py", "src/transformers/models/pop2piano/__init__.py", "src/transformers/models/pop2piano/configuration_pop2piano.py", "src/transformers/models/pop2piano/convert_pop2piano_weights_to_hf.py", "src/transformers/models/pop2piano/feature_extraction_pop2piano.py", "src/transformers/models/pop2piano/modeling_pop2piano.py", "src/transformers/models/pop2piano/processing_pop2piano.py", "src/transformers/models/pop2piano/tokenization_pop2piano.py", "src/transformers/models/prophetnet/__init__.py", "src/transformers/models/prophetnet/configuration_prophetnet.py", "src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/prophetnet/modeling_prophetnet.py", "src/transformers/models/prophetnet/tokenization_prophetnet.py", "src/transformers/models/pvt/__init__.py", "src/transformers/models/pvt/configuration_pvt.py", "src/transformers/models/pvt/convert_pvt_to_pytorch.py", "src/transformers/models/pvt/image_processing_pvt.py", "src/transformers/models/pvt/modeling_pvt.py", "src/transformers/models/pvt_v2/__init__.py", "src/transformers/models/pvt_v2/configuration_pvt_v2.py", "src/transformers/models/pvt_v2/convert_pvt_v2_to_pytorch.py", "src/transformers/models/pvt_v2/modeling_pvt_v2.py", "src/transformers/models/qwen2/__init__.py", "src/transformers/models/qwen2/configuration_qwen2.py", "src/transformers/models/qwen2/modeling_qwen2.py", "src/transformers/models/qwen2/modular_qwen2.py", "src/transformers/models/qwen2/tokenization_qwen2.py", "src/transformers/models/qwen2/tokenization_qwen2_fast.py", "src/transformers/models/qwen2_5_vl/__init__.py", "src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py", "src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py", "src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py", "src/transformers/models/qwen2_5_vl/processing_qwen2_5_vl.py", "src/transformers/models/qwen2_audio/__init__.py", "src/transformers/models/qwen2_audio/configuration_qwen2_audio.py", "src/transformers/models/qwen2_audio/modeling_qwen2_audio.py", "src/transformers/models/qwen2_audio/processing_qwen2_audio.py", "src/transformers/models/qwen2_moe/__init__.py", "src/transformers/models/qwen2_moe/configuration_qwen2_moe.py", "src/transformers/models/qwen2_moe/modeling_qwen2_moe.py", "src/transformers/models/qwen2_vl/__init__.py", "src/transformers/models/qwen2_vl/configuration_qwen2_vl.py", "src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py", "src/transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py", "src/transformers/models/qwen2_vl/modeling_qwen2_vl.py", "src/transformers/models/qwen2_vl/processing_qwen2_vl.py", "src/transformers/models/rag/__init__.py", "src/transformers/models/rag/configuration_rag.py", "src/transformers/models/rag/modeling_rag.py", "src/transformers/models/rag/modeling_tf_rag.py", "src/transformers/models/rag/retrieval_rag.py", "src/transformers/models/rag/tokenization_rag.py", "src/transformers/models/recurrent_gemma/__init__.py", "src/transformers/models/recurrent_gemma/configuration_recurrent_gemma.py", "src/transformers/models/recurrent_gemma/convert_recurrent_gemma_to_hf.py", "src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py", "src/transformers/models/reformer/__init__.py", "src/transformers/models/reformer/configuration_reformer.py", "src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py", "src/transformers/models/reformer/modeling_reformer.py", "src/transformers/models/reformer/tokenization_reformer.py", "src/transformers/models/reformer/tokenization_reformer_fast.py", "src/transformers/models/regnet/__init__.py", "src/transformers/models/regnet/configuration_regnet.py", "src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py", "src/transformers/models/regnet/convert_regnet_to_pytorch.py", "src/transformers/models/regnet/modeling_flax_regnet.py", "src/transformers/models/regnet/modeling_regnet.py", "src/transformers/models/regnet/modeling_tf_regnet.py", "src/transformers/models/rembert/__init__.py", "src/transformers/models/rembert/configuration_rembert.py", "src/transformers/models/rembert/convert_rembert_tf_checkpoint_to_pytorch.py", "src/transformers/models/rembert/modeling_rembert.py", "src/transformers/models/rembert/modeling_tf_rembert.py", "src/transformers/models/rembert/tokenization_rembert.py", "src/transformers/models/rembert/tokenization_rembert_fast.py", "src/transformers/models/resnet/__init__.py", "src/transformers/models/resnet/configuration_resnet.py", "src/transformers/models/resnet/convert_resnet_to_pytorch.py", "src/transformers/models/resnet/modeling_flax_resnet.py", "src/transformers/models/resnet/modeling_resnet.py", "src/transformers/models/resnet/modeling_tf_resnet.py", "src/transformers/models/roberta/__init__.py", "src/transformers/models/roberta/configuration_roberta.py", "src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/roberta/modeling_flax_roberta.py", "src/transformers/models/roberta/modeling_roberta.py", "src/transformers/models/roberta/modeling_tf_roberta.py", "src/transformers/models/roberta/tokenization_roberta.py", "src/transformers/models/roberta/tokenization_roberta_fast.py", "src/transformers/models/roberta_prelayernorm/__init__.py", "src/transformers/models/roberta_prelayernorm/configuration_roberta_prelayernorm.py", "src/transformers/models/roberta_prelayernorm/convert_roberta_prelayernorm_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py", "src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py", "src/transformers/models/roberta_prelayernorm/modeling_tf_roberta_prelayernorm.py", "src/transformers/models/roc_bert/__init__.py", "src/transformers/models/roc_bert/configuration_roc_bert.py", "src/transformers/models/roc_bert/modeling_roc_bert.py", "src/transformers/models/roc_bert/tokenization_roc_bert.py", "src/transformers/models/roformer/__init__.py", "src/transformers/models/roformer/configuration_roformer.py", "src/transformers/models/roformer/convert_roformer_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/roformer/modeling_flax_roformer.py", "src/transformers/models/roformer/modeling_roformer.py", "src/transformers/models/roformer/modeling_tf_roformer.py", "src/transformers/models/roformer/tokenization_roformer.py", "src/transformers/models/roformer/tokenization_roformer_fast.py", "src/transformers/models/roformer/tokenization_utils.py", "src/transformers/models/rt_detr/__init__.py", "src/transformers/models/rt_detr/configuration_rt_detr.py", "src/transformers/models/rt_detr/configuration_rt_detr_resnet.py", "src/transformers/models/rt_detr/convert_rt_detr_original_pytorch_checkpoint_to_hf.py", "src/transformers/models/rt_detr/image_processing_rt_detr.py", "src/transformers/models/rt_detr/image_processing_rt_detr_fast.py", "src/transformers/models/rt_detr/modeling_rt_detr.py", "src/transformers/models/rt_detr/modeling_rt_detr_resnet.py", "src/transformers/models/rt_detr/modular_rt_detr.py", "src/transformers/models/rt_detr_v2/__init__.py", "src/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py", "src/transformers/models/rt_detr_v2/convert_rt_detr_v2_weights_to_hf.py", "src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py", "src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py", "src/transformers/models/rwkv/__init__.py", "src/transformers/models/rwkv/configuration_rwkv.py", "src/transformers/models/rwkv/convert_rwkv_checkpoint_to_hf.py", "src/transformers/models/rwkv/modeling_rwkv.py", "src/transformers/models/sam/__init__.py", "src/transformers/models/sam/configuration_sam.py", "src/transformers/models/sam/convert_sam_to_hf.py", "src/transformers/models/sam/image_processing_sam.py", "src/transformers/models/sam/modeling_sam.py", "src/transformers/models/sam/modeling_tf_sam.py", "src/transformers/models/sam/processing_sam.py", "src/transformers/models/seamless_m4t/__init__.py", "src/transformers/models/seamless_m4t/configuration_seamless_m4t.py", "src/transformers/models/seamless_m4t/convert_fairseq2_to_hf.py", "src/transformers/models/seamless_m4t/feature_extraction_seamless_m4t.py", "src/transformers/models/seamless_m4t/modeling_seamless_m4t.py", "src/transformers/models/seamless_m4t/processing_seamless_m4t.py", "src/transformers/models/seamless_m4t/tokenization_seamless_m4t.py", "src/transformers/models/seamless_m4t/tokenization_seamless_m4t_fast.py", "src/transformers/models/seamless_m4t_v2/__init__.py", "src/transformers/models/seamless_m4t_v2/configuration_seamless_m4t_v2.py", "src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py", "src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py", "src/transformers/models/segformer/__init__.py", "src/transformers/models/segformer/configuration_segformer.py", "src/transformers/models/segformer/convert_segformer_original_to_pytorch.py", "src/transformers/models/segformer/feature_extraction_segformer.py", "src/transformers/models/segformer/image_processing_segformer.py", "src/transformers/models/segformer/modeling_segformer.py", "src/transformers/models/segformer/modeling_tf_segformer.py", "src/transformers/models/seggpt/__init__.py", "src/transformers/models/seggpt/configuration_seggpt.py", "src/transformers/models/seggpt/convert_seggpt_to_hf.py", "src/transformers/models/seggpt/image_processing_seggpt.py", "src/transformers/models/seggpt/modeling_seggpt.py", "src/transformers/models/sew/__init__.py", "src/transformers/models/sew/configuration_sew.py", "src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/sew/modeling_sew.py", "src/transformers/models/sew_d/__init__.py", "src/transformers/models/sew_d/configuration_sew_d.py", "src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/sew_d/modeling_sew_d.py", "src/transformers/models/siglip/__init__.py", "src/transformers/models/siglip/configuration_siglip.py", "src/transformers/models/siglip/convert_siglip_to_hf.py", "src/transformers/models/siglip/image_processing_siglip.py", "src/transformers/models/siglip/image_processing_siglip_fast.py", "src/transformers/models/siglip/modeling_siglip.py", "src/transformers/models/siglip/processing_siglip.py", "src/transformers/models/siglip/tokenization_siglip.py", "src/transformers/models/siglip2/__init__.py", "src/transformers/models/siglip2/configuration_siglip2.py", "src/transformers/models/siglip2/convert_siglip2_to_hf.py", "src/transformers/models/siglip2/image_processing_siglip2.py", "src/transformers/models/siglip2/image_processing_siglip2_fast.py", "src/transformers/models/siglip2/modeling_siglip2.py", "src/transformers/models/siglip2/modular_siglip2.py", "src/transformers/models/siglip2/processing_siglip2.py", "src/transformers/models/smolvlm/__init__.py", "src/transformers/models/smolvlm/configuration_smolvlm.py", "src/transformers/models/smolvlm/image_processing_smolvlm.py", "src/transformers/models/smolvlm/modeling_smolvlm.py", "src/transformers/models/smolvlm/modular_smolvlm.py", "src/transformers/models/smolvlm/processing_smolvlm.py", "src/transformers/models/smolvlm/video_processing_smolvlm.py", "src/transformers/models/speech_encoder_decoder/__init__.py", "src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py", "src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py", "src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py", "src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py", "src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py", "src/transformers/models/speech_to_text/__init__.py", "src/transformers/models/speech_to_text/configuration_speech_to_text.py", "src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py", "src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py", "src/transformers/models/speech_to_text/modeling_speech_to_text.py", "src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py", "src/transformers/models/speech_to_text/processing_speech_to_text.py", "src/transformers/models/speech_to_text/tokenization_speech_to_text.py", "src/transformers/models/speecht5/__init__.py", "src/transformers/models/speecht5/configuration_speecht5.py", "src/transformers/models/speecht5/convert_hifigan.py", "src/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/speecht5/feature_extraction_speecht5.py", "src/transformers/models/speecht5/modeling_speecht5.py", "src/transformers/models/speecht5/number_normalizer.py", "src/transformers/models/speecht5/processing_speecht5.py", "src/transformers/models/speecht5/tokenization_speecht5.py", "src/transformers/models/splinter/__init__.py", "src/transformers/models/splinter/configuration_splinter.py", "src/transformers/models/splinter/modeling_splinter.py", "src/transformers/models/splinter/tokenization_splinter.py", "src/transformers/models/splinter/tokenization_splinter_fast.py", "src/transformers/models/squeezebert/__init__.py", "src/transformers/models/squeezebert/configuration_squeezebert.py", "src/transformers/models/squeezebert/modeling_squeezebert.py", "src/transformers/models/squeezebert/tokenization_squeezebert.py", "src/transformers/models/squeezebert/tokenization_squeezebert_fast.py", "src/transformers/models/stablelm/__init__.py", "src/transformers/models/stablelm/configuration_stablelm.py", "src/transformers/models/stablelm/modeling_stablelm.py", "src/transformers/models/starcoder2/__init__.py", "src/transformers/models/starcoder2/configuration_starcoder2.py", "src/transformers/models/starcoder2/modeling_starcoder2.py", "src/transformers/models/starcoder2/modular_starcoder2.py", "src/transformers/models/superglue/__init__.py", "src/transformers/models/superglue/configuration_superglue.py", "src/transformers/models/superglue/convert_superglue_to_hf.py", "src/transformers/models/superglue/image_processing_superglue.py", "src/transformers/models/superglue/modeling_superglue.py", "src/transformers/models/superpoint/__init__.py", "src/transformers/models/superpoint/configuration_superpoint.py", "src/transformers/models/superpoint/convert_superpoint_to_pytorch.py", "src/transformers/models/superpoint/image_processing_superpoint.py", "src/transformers/models/superpoint/modeling_superpoint.py", "src/transformers/models/swiftformer/__init__.py", "src/transformers/models/swiftformer/configuration_swiftformer.py", "src/transformers/models/swiftformer/convert_swiftformer_original_to_hf.py", "src/transformers/models/swiftformer/modeling_swiftformer.py", "src/transformers/models/swiftformer/modeling_tf_swiftformer.py", "src/transformers/models/swin/__init__.py", "src/transformers/models/swin/configuration_swin.py", "src/transformers/models/swin/convert_swin_simmim_to_pytorch.py", "src/transformers/models/swin/convert_swin_timm_to_pytorch.py", "src/transformers/models/swin/modeling_swin.py", "src/transformers/models/swin/modeling_tf_swin.py", "src/transformers/models/swin2sr/__init__.py", "src/transformers/models/swin2sr/configuration_swin2sr.py", "src/transformers/models/swin2sr/convert_swin2sr_original_to_pytorch.py", "src/transformers/models/swin2sr/image_processing_swin2sr.py", "src/transformers/models/swin2sr/modeling_swin2sr.py", "src/transformers/models/swinv2/__init__.py", "src/transformers/models/swinv2/configuration_swinv2.py", "src/transformers/models/swinv2/convert_swinv2_timm_to_pytorch.py", "src/transformers/models/swinv2/modeling_swinv2.py", "src/transformers/models/switch_transformers/__init__.py", "src/transformers/models/switch_transformers/configuration_switch_transformers.py", "src/transformers/models/switch_transformers/convert_big_switch.py", "src/transformers/models/switch_transformers/convert_switch_transformers_original_flax_checkpoint_to_pytorch.py", "src/transformers/models/switch_transformers/modeling_switch_transformers.py", "src/transformers/models/t5/__init__.py", "src/transformers/models/t5/configuration_t5.py", "src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py", "src/transformers/models/t5/convert_t5x_checkpoint_to_pytorch.py", "src/transformers/models/t5/modeling_flax_t5.py", "src/transformers/models/t5/modeling_t5.py", "src/transformers/models/t5/modeling_tf_t5.py", "src/transformers/models/t5/tokenization_t5.py", "src/transformers/models/t5/tokenization_t5_fast.py", "src/transformers/models/table_transformer/__init__.py", "src/transformers/models/table_transformer/configuration_table_transformer.py", "src/transformers/models/table_transformer/convert_table_transformer_to_hf.py", "src/transformers/models/table_transformer/convert_table_transformer_to_hf_no_timm.py", "src/transformers/models/table_transformer/modeling_table_transformer.py", "src/transformers/models/tapas/__init__.py", "src/transformers/models/tapas/configuration_tapas.py", "src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/tapas/modeling_tapas.py", "src/transformers/models/tapas/modeling_tf_tapas.py", "src/transformers/models/tapas/tokenization_tapas.py", "src/transformers/models/textnet/__init__.py", "src/transformers/models/textnet/configuration_textnet.py", "src/transformers/models/textnet/convert_textnet_to_hf.py", "src/transformers/models/textnet/image_processing_textnet.py", "src/transformers/models/textnet/modeling_textnet.py", "src/transformers/models/time_series_transformer/__init__.py", "src/transformers/models/time_series_transformer/configuration_time_series_transformer.py", "src/transformers/models/time_series_transformer/modeling_time_series_transformer.py", "src/transformers/models/timesformer/__init__.py", "src/transformers/models/timesformer/configuration_timesformer.py", "src/transformers/models/timesformer/convert_timesformer_to_pytorch.py", "src/transformers/models/timesformer/modeling_timesformer.py", "src/transformers/models/timm_backbone/__init__.py", "src/transformers/models/timm_backbone/configuration_timm_backbone.py", "src/transformers/models/timm_backbone/modeling_timm_backbone.py", "src/transformers/models/timm_wrapper/__init__.py", "src/transformers/models/timm_wrapper/configuration_timm_wrapper.py", "src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py", "src/transformers/models/timm_wrapper/modeling_timm_wrapper.py", "src/transformers/models/trocr/__init__.py", "src/transformers/models/trocr/configuration_trocr.py", "src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py", "src/transformers/models/trocr/modeling_trocr.py", "src/transformers/models/trocr/processing_trocr.py", "src/transformers/models/tvp/__init__.py", "src/transformers/models/tvp/configuration_tvp.py", "src/transformers/models/tvp/image_processing_tvp.py", "src/transformers/models/tvp/modeling_tvp.py", "src/transformers/models/tvp/processing_tvp.py", "src/transformers/models/udop/__init__.py", "src/transformers/models/udop/configuration_udop.py", "src/transformers/models/udop/convert_udop_to_hf.py", "src/transformers/models/udop/modeling_udop.py", "src/transformers/models/udop/processing_udop.py", "src/transformers/models/udop/tokenization_udop.py", "src/transformers/models/udop/tokenization_udop_fast.py", "src/transformers/models/umt5/__init__.py", "src/transformers/models/umt5/configuration_umt5.py", "src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py", "src/transformers/models/umt5/modeling_umt5.py", "src/transformers/models/unispeech/__init__.py", "src/transformers/models/unispeech/configuration_unispeech.py", "src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/unispeech/modeling_unispeech.py", "src/transformers/models/unispeech_sat/__init__.py", "src/transformers/models/unispeech_sat/configuration_unispeech_sat.py", "src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py", "src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/unispeech_sat/modeling_unispeech_sat.py", "src/transformers/models/univnet/__init__.py", "src/transformers/models/univnet/configuration_univnet.py", "src/transformers/models/univnet/convert_univnet.py", "src/transformers/models/univnet/feature_extraction_univnet.py", "src/transformers/models/univnet/modeling_univnet.py", "src/transformers/models/upernet/__init__.py", "src/transformers/models/upernet/configuration_upernet.py", "src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py", "src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py", "src/transformers/models/upernet/modeling_upernet.py", "src/transformers/models/video_llava/__init__.py", "src/transformers/models/video_llava/configuration_video_llava.py", "src/transformers/models/video_llava/convert_video_llava_weights_to_hf.py", "src/transformers/models/video_llava/image_processing_video_llava.py", "src/transformers/models/video_llava/modeling_video_llava.py", "src/transformers/models/video_llava/processing_video_llava.py", "src/transformers/models/videomae/__init__.py", "src/transformers/models/videomae/configuration_videomae.py", "src/transformers/models/videomae/convert_videomae_to_pytorch.py", "src/transformers/models/videomae/feature_extraction_videomae.py", "src/transformers/models/videomae/image_processing_videomae.py", "src/transformers/models/videomae/modeling_videomae.py", "src/transformers/models/vilt/__init__.py", "src/transformers/models/vilt/configuration_vilt.py", "src/transformers/models/vilt/convert_vilt_original_to_pytorch.py", "src/transformers/models/vilt/feature_extraction_vilt.py", "src/transformers/models/vilt/image_processing_vilt.py", "src/transformers/models/vilt/modeling_vilt.py", "src/transformers/models/vilt/processing_vilt.py", "src/transformers/models/vipllava/__init__.py", "src/transformers/models/vipllava/configuration_vipllava.py", "src/transformers/models/vipllava/convert_vipllava_weights_to_hf.py", "src/transformers/models/vipllava/modeling_vipllava.py", "src/transformers/models/vision_encoder_decoder/__init__.py", "src/transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py", "src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py", "src/transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py", "src/transformers/models/vision_encoder_decoder/modeling_vision_encoder_decoder.py", "src/transformers/models/vision_text_dual_encoder/__init__.py", "src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py", "src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py", "src/transformers/models/vision_text_dual_encoder/modeling_tf_vision_text_dual_encoder.py", "src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py", "src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py", "src/transformers/models/visual_bert/__init__.py", "src/transformers/models/visual_bert/configuration_visual_bert.py", "src/transformers/models/visual_bert/convert_visual_bert_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/visual_bert/modeling_visual_bert.py", "src/transformers/models/vit/__init__.py", "src/transformers/models/vit/configuration_vit.py", "src/transformers/models/vit/convert_dino_to_pytorch.py", "src/transformers/models/vit/convert_vit_timm_to_pytorch.py", "src/transformers/models/vit/feature_extraction_vit.py", "src/transformers/models/vit/image_processing_vit.py", "src/transformers/models/vit/image_processing_vit_fast.py", "src/transformers/models/vit/modeling_flax_vit.py", "src/transformers/models/vit/modeling_tf_vit.py", "src/transformers/models/vit/modeling_vit.py", "src/transformers/models/vit_mae/__init__.py", "src/transformers/models/vit_mae/configuration_vit_mae.py", "src/transformers/models/vit_mae/convert_vit_mae_to_pytorch.py", "src/transformers/models/vit_mae/modeling_tf_vit_mae.py", "src/transformers/models/vit_mae/modeling_vit_mae.py", "src/transformers/models/vit_msn/__init__.py", "src/transformers/models/vit_msn/configuration_vit_msn.py", "src/transformers/models/vit_msn/convert_msn_to_pytorch.py", "src/transformers/models/vit_msn/modeling_vit_msn.py", "src/transformers/models/vitdet/__init__.py", "src/transformers/models/vitdet/configuration_vitdet.py", "src/transformers/models/vitdet/modeling_vitdet.py", "src/transformers/models/vitmatte/__init__.py", "src/transformers/models/vitmatte/configuration_vitmatte.py", "src/transformers/models/vitmatte/convert_vitmatte_to_hf.py", "src/transformers/models/vitmatte/image_processing_vitmatte.py", "src/transformers/models/vitmatte/modeling_vitmatte.py", "src/transformers/models/vitpose/__init__.py", "src/transformers/models/vitpose/configuration_vitpose.py", "src/transformers/models/vitpose/convert_vitpose_to_hf.py", "src/transformers/models/vitpose/image_processing_vitpose.py", "src/transformers/models/vitpose/modeling_vitpose.py", "src/transformers/models/vitpose_backbone/__init__.py", "src/transformers/models/vitpose_backbone/configuration_vitpose_backbone.py", "src/transformers/models/vitpose_backbone/modeling_vitpose_backbone.py", "src/transformers/models/vits/__init__.py", "src/transformers/models/vits/configuration_vits.py", "src/transformers/models/vits/convert_original_checkpoint.py", "src/transformers/models/vits/modeling_vits.py", "src/transformers/models/vits/tokenization_vits.py", "src/transformers/models/vivit/__init__.py", "src/transformers/models/vivit/configuration_vivit.py", "src/transformers/models/vivit/convert_vivit_flax_to_pytorch.py", "src/transformers/models/vivit/image_processing_vivit.py", "src/transformers/models/vivit/modeling_vivit.py", "src/transformers/models/wav2vec2/__init__.py", "src/transformers/models/wav2vec2/configuration_wav2vec2.py", "src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py", "src/transformers/models/wav2vec2/feature_extraction_wav2vec2.py", "src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py", "src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py", "src/transformers/models/wav2vec2/modeling_wav2vec2.py", "src/transformers/models/wav2vec2/processing_wav2vec2.py", "src/transformers/models/wav2vec2/tokenization_wav2vec2.py", "src/transformers/models/wav2vec2_bert/__init__.py", "src/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py", "src/transformers/models/wav2vec2_bert/convert_wav2vec2_seamless_checkpoint.py", "src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py", "src/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py", "src/transformers/models/wav2vec2_conformer/__init__.py", "src/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py", "src/transformers/models/wav2vec2_conformer/convert_wav2vec2_conformer_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py", "src/transformers/models/wav2vec2_phoneme/__init__.py", "src/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py", "src/transformers/models/wav2vec2_with_lm/__init__.py", "src/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py", "src/transformers/models/wavlm/__init__.py", "src/transformers/models/wavlm/configuration_wavlm.py", "src/transformers/models/wavlm/convert_wavlm_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/wavlm/convert_wavlm_original_s3prl_checkpoint_to_pytorch.py", "src/transformers/models/wavlm/modeling_wavlm.py", "src/transformers/models/whisper/__init__.py", "src/transformers/models/whisper/configuration_whisper.py", "src/transformers/models/whisper/convert_openai_to_hf.py", "src/transformers/models/whisper/english_normalizer.py", "src/transformers/models/whisper/feature_extraction_whisper.py", "src/transformers/models/whisper/generation_whisper.py", "src/transformers/models/whisper/modeling_flax_whisper.py", "src/transformers/models/whisper/modeling_tf_whisper.py", "src/transformers/models/whisper/modeling_whisper.py", "src/transformers/models/whisper/processing_whisper.py", "src/transformers/models/whisper/tokenization_whisper.py", "src/transformers/models/whisper/tokenization_whisper_fast.py", "src/transformers/models/x_clip/__init__.py", "src/transformers/models/x_clip/configuration_x_clip.py", "src/transformers/models/x_clip/convert_x_clip_original_pytorch_to_hf.py", "src/transformers/models/x_clip/modeling_x_clip.py", "src/transformers/models/x_clip/processing_x_clip.py", "src/transformers/models/xglm/__init__.py", "src/transformers/models/xglm/configuration_xglm.py", "src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py", "src/transformers/models/xglm/modeling_flax_xglm.py", "src/transformers/models/xglm/modeling_tf_xglm.py", "src/transformers/models/xglm/modeling_xglm.py", "src/transformers/models/xglm/tokenization_xglm.py", "src/transformers/models/xglm/tokenization_xglm_fast.py", "src/transformers/models/xlm/__init__.py", "src/transformers/models/xlm/configuration_xlm.py", "src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/xlm/modeling_tf_xlm.py", "src/transformers/models/xlm/modeling_xlm.py", "src/transformers/models/xlm/tokenization_xlm.py", "src/transformers/models/xlm_roberta/__init__.py", "src/transformers/models/xlm_roberta/configuration_xlm_roberta.py", "src/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py", "src/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py", "src/transformers/models/xlm_roberta/modeling_xlm_roberta.py", "src/transformers/models/xlm_roberta/tokenization_xlm_roberta.py", "src/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py", "src/transformers/models/xlm_roberta_xl/__init__.py", "src/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py", "src/transformers/models/xlm_roberta_xl/convert_xlm_roberta_xl_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py", "src/transformers/models/xlnet/__init__.py", "src/transformers/models/xlnet/configuration_xlnet.py", "src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py", "src/transformers/models/xlnet/modeling_tf_xlnet.py", "src/transformers/models/xlnet/modeling_xlnet.py", "src/transformers/models/xlnet/tokenization_xlnet.py", "src/transformers/models/xlnet/tokenization_xlnet_fast.py", "src/transformers/models/xmod/__init__.py", "src/transformers/models/xmod/configuration_xmod.py", "src/transformers/models/xmod/convert_xmod_original_pytorch_checkpoint_to_pytorch.py", "src/transformers/models/xmod/modeling_xmod.py", "src/transformers/models/yolos/__init__.py", "src/transformers/models/yolos/configuration_yolos.py", "src/transformers/models/yolos/convert_yolos_to_pytorch.py", "src/transformers/models/yolos/feature_extraction_yolos.py", "src/transformers/models/yolos/image_processing_yolos.py", "src/transformers/models/yolos/modeling_yolos.py", "src/transformers/models/yoso/__init__.py", "src/transformers/models/yoso/configuration_yoso.py", "src/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py", "src/transformers/models/yoso/modeling_yoso.py", "src/transformers/models/zamba/__init__.py", "src/transformers/models/zamba/configuration_zamba.py", "src/transformers/models/zamba/modeling_zamba.py", "src/transformers/models/zamba2/__init__.py", "src/transformers/models/zamba2/configuration_zamba2.py", "src/transformers/models/zamba2/modeling_zamba2.py", "src/transformers/models/zamba2/modular_zamba2.py", "src/transformers/models/zoedepth/__init__.py", "src/transformers/models/zoedepth/configuration_zoedepth.py", "src/transformers/models/zoedepth/convert_zoedepth_to_hf.py", "src/transformers/models/zoedepth/image_processing_zoedepth.py", "src/transformers/models/zoedepth/modeling_zoedepth.py", "src/transformers/onnx/__init__.py", "src/transformers/onnx/__main__.py", "src/transformers/onnx/config.py", "src/transformers/onnx/convert.py", "src/transformers/onnx/features.py", "src/transformers/onnx/utils.py", "src/transformers/optimization.py", "src/transformers/optimization_tf.py", "src/transformers/pipelines/__init__.py", "src/transformers/pipelines/audio_classification.py", "src/transformers/pipelines/audio_utils.py", "src/transformers/pipelines/automatic_speech_recognition.py", "src/transformers/pipelines/base.py", "src/transformers/pipelines/depth_estimation.py", "src/transformers/pipelines/document_question_answering.py", "src/transformers/pipelines/feature_extraction.py", "src/transformers/pipelines/fill_mask.py", "src/transformers/pipelines/image_classification.py", "src/transformers/pipelines/image_feature_extraction.py", "src/transformers/pipelines/image_segmentation.py", "src/transformers/pipelines/image_text_to_text.py", "src/transformers/pipelines/image_to_image.py", "src/transformers/pipelines/image_to_text.py", "src/transformers/pipelines/mask_generation.py", "src/transformers/pipelines/object_detection.py", "src/transformers/pipelines/pt_utils.py", "src/transformers/pipelines/question_answering.py", "src/transformers/pipelines/table_question_answering.py", "src/transformers/pipelines/text2text_generation.py", "src/transformers/pipelines/text_classification.py", "src/transformers/pipelines/text_generation.py", "src/transformers/pipelines/text_to_audio.py", "src/transformers/pipelines/token_classification.py", "src/transformers/pipelines/video_classification.py", "src/transformers/pipelines/visual_question_answering.py", "src/transformers/pipelines/zero_shot_audio_classification.py", "src/transformers/pipelines/zero_shot_classification.py", "src/transformers/pipelines/zero_shot_image_classification.py", "src/transformers/pipelines/zero_shot_object_detection.py", "src/transformers/processing_utils.py", "src/transformers/pytorch_utils.py", "src/transformers/quantizers/__init__.py", "src/transformers/quantizers/auto.py", "src/transformers/quantizers/base.py", "src/transformers/quantizers/quantizer_aqlm.py", "src/transformers/quantizers/quantizer_awq.py", "src/transformers/quantizers/quantizer_bitnet.py", "src/transformers/quantizers/quantizer_bnb_4bit.py", "src/transformers/quantizers/quantizer_bnb_8bit.py", "src/transformers/quantizers/quantizer_compressed_tensors.py", "src/transformers/quantizers/quantizer_eetq.py", "src/transformers/quantizers/quantizer_fbgemm_fp8.py", "src/transformers/quantizers/quantizer_finegrained_fp8.py", "src/transformers/quantizers/quantizer_gptq.py", "src/transformers/quantizers/quantizer_higgs.py", "src/transformers/quantizers/quantizer_hqq.py", "src/transformers/quantizers/quantizer_quanto.py", "src/transformers/quantizers/quantizer_spqr.py", "src/transformers/quantizers/quantizer_torchao.py", "src/transformers/quantizers/quantizer_vptq.py", "src/transformers/quantizers/quantizers_utils.py", "src/transformers/safetensors_conversion.py", "src/transformers/sagemaker/__init__.py", "src/transformers/sagemaker/trainer_sm.py", "src/transformers/sagemaker/training_args_sm.py", "src/transformers/testing_utils.py", "src/transformers/tf_utils.py", "src/transformers/time_series_utils.py", "src/transformers/tokenization_utils.py", "src/transformers/tokenization_utils_base.py", "src/transformers/tokenization_utils_fast.py", "src/transformers/trainer.py", "src/transformers/trainer_callback.py", "src/transformers/trainer_pt_utils.py", "src/transformers/trainer_seq2seq.py", "src/transformers/trainer_utils.py", "src/transformers/training_args.py", "src/transformers/training_args_seq2seq.py", "src/transformers/training_args_tf.py", "src/transformers/utils/__init__.py", "src/transformers/utils/backbone_utils.py", "src/transformers/utils/bitsandbytes.py", "src/transformers/utils/chat_template_utils.py", "src/transformers/utils/constants.py", "src/transformers/utils/deprecation.py", "src/transformers/utils/doc.py", "src/transformers/utils/dummy_detectron2_objects.py", "src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py", "src/transformers/utils/dummy_flax_objects.py", "src/transformers/utils/dummy_keras_nlp_objects.py", "src/transformers/utils/dummy_music_objects.py", "src/transformers/utils/dummy_pt_objects.py", "src/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py", "src/transformers/utils/dummy_sentencepiece_objects.py", "src/transformers/utils/dummy_speech_objects.py", "src/transformers/utils/dummy_tensorflow_text_objects.py", "src/transformers/utils/dummy_tf_objects.py", "src/transformers/utils/dummy_timm_and_torchvision_objects.py", "src/transformers/utils/dummy_tokenizers_objects.py", "src/transformers/utils/dummy_torchaudio_objects.py", "src/transformers/utils/dummy_torchvision_objects.py", "src/transformers/utils/dummy_vision_objects.py", "src/transformers/utils/fx.py", "src/transformers/utils/generic.py", "src/transformers/utils/hp_naming.py", "src/transformers/utils/hub.py", "src/transformers/utils/import_utils.py", "src/transformers/utils/logging.py", "src/transformers/utils/model_parallel_utils.py", "src/transformers/utils/notebook.py", "src/transformers/utils/peft_utils.py", "src/transformers/utils/quantization_config.py", "src/transformers/utils/sentencepiece_model_pb2.py", "src/transformers/utils/sentencepiece_model_pb2_new.py", "src/transformers/utils/versions.py"], "submitted_roots": ["src/transformers"], "test_paths": ["tests/tasksmith_behavior.py"], "timeout_sec": 300} \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/grade.py b/tasks/tasksmith-441eeab80047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..7e060dd2eaf372c0e83ae8f5aea784e5bd622402 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/grade.py @@ -0,0 +1,188 @@ +"""Standalone trusted entry point; copied into each separate verifier image. + +No Repo2RLEnv installation is needed to grade an exported task. Submitted Python +runs as an unprivileged user; this parent owns the result parser and reward file. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import signal +import stat +import subprocess +import sys +import tempfile +from pathlib import Path + + +def child_environment(temporary: str) -> dict[str, str]: + """Preserve prepared runtime assets without inheriting controller credentials.""" + return { + **{ + key: os.environ[key] + for key in ( + "LD_LIBRARY_PATH", + "CUDA_VISIBLE_DEVICES", + "NVIDIA_VISIBLE_DEVICES", + "NVIDIA_DRIVER_CAPABILITIES", + "NCCL_SOCKET_IFNAME", + "GLOO_SOCKET_IFNAME", + "HF_HOME", + "HF_HUB_CACHE", + "HF_HUB_OFFLINE", + "TRANSFORMERS_OFFLINE", + "HF_DATASETS_OFFLINE", + ) + if key in os.environ + }, + "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin", + "HOME": temporary, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", + } + + +def validate_submission(workspace: Path, contract: dict) -> None: + """Validate private staging and remove inert backups before importing Python.""" + submitted = set(contract["submitted_files"]) + backups: set[str] = set() + optional = submitted & set(contract.get("optional_files", [])) + paths = submitted - optional + for relative in optional: + path = workspace / relative + if any(component.is_symlink() for component in (path, *path.parents)): + raise ValueError("Submitted source contains a symlink") + # Added standalone modules may be absent in the baseline. If supplied, + # apply the same regular-file and size checks as every required module. + if path.exists(): + paths.add(relative) + roots = contract.get("submitted_roots", []) + immutable = contract.get("immutable_assets", {}) + paths.update(immutable) + for relative in roots: + root = workspace / relative + if root.is_symlink() or not root.is_dir(): + raise ValueError("Submitted source root is missing or linked") + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if path.is_dir(): + continue + name = path.relative_to(workspace).as_posix() + if path.suffix != ".py" and name not in immutable: + if name not in submitted and path.name.endswith((".py.bak", ".py~")): + backups.add(name) + else: + raise ValueError("Only Python source files may be added") + paths.add(name) + for relative in sorted(paths): + path = workspace / relative + for component in (path, *path.parents): + if component.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if ( + not path.is_file() + or not stat.S_ISREG(path.stat().st_mode) + or path.stat().st_size > 8 * 1024 * 1024 + ): + raise ValueError("Submitted source is not a bounded regular file") + if ( + relative in immutable + and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative] + ): + raise ValueError("Non-Python source assets must remain unchanged") + if relative not in backups: + os.chown(path, 0, 0) + path.chmod(0o644) + # Only the verifier's collected copy is cleaned. The learner workspace and + # archived submission retain their bytes. Validate every path first so a + # backup cannot bypass linked, oversized, required, or immutable file checks. + for relative in sorted(backups): + (workspace / relative).unlink() + + +def main() -> None: + directory = Path("/tests") + parser_spec = importlib.util.spec_from_file_location( + "test_results", directory / "test_results.py" + ) + parser = importlib.util.module_from_spec(parser_spec) + sys.modules[parser_spec.name] = parser + parser_spec.loader.exec_module(parser) + contract = json.loads((directory / "contract.json").read_text()) + logs = Path("/logs/verifier") + logs.mkdir(parents=True, exist_ok=True) + logs.chmod(0o755) + reward = logs / "reward.txt" + reward.write_text("0\n") + reward.chmod(0o644) + try: + validate_submission(Path("/workspace"), contract) + except (ValueError, OSError) as exc: + (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)})) + return + with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary: + working = Path(temporary) + os.chown(working, 1001, 1001) + working.chmod(0o700) + report = working / "results.xml" + command = [ + sys.executable, + "-I", + "/tests/test_driver.py", + *contract["test_paths"], + "-q", + "--tb=short", + "-p", + "no:cacheprovider", + f"--junitxml={report}", + ] + with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr: + process = subprocess.Popen( + command, + cwd="/workspace", + stdout=stdout, + stderr=stderr, + user=1001, + group=1001, + extra_groups=[], + start_new_session=True, + env=child_environment(temporary), + ) + try: + code = process.wait(timeout=contract["timeout_sec"]) + finally: + # Terminate descendants too: they must not keep modifying the + # child-owned report while the trusted parent checks it. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"}) + ) + return + text = report.read_text() + (logs / "results.xml").write_text(text) + try: + parsed = parser.parse_junit(text, returncode=code) + except ValueError as exc: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": str(exc)}) + ) + return + expected = set(contract["expected_passes"]) + passed = code == 0 and bool(expected) and parsed.passed == expected + (logs / "result.json").write_text( + json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses}) + ) + reward.write_text("1\n" if passed else "0\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-441eeab80047/tests/source/.circleci/TROUBLESHOOT.md b/tasks/tasksmith-441eeab80047/tests/source/.circleci/TROUBLESHOOT.md new file mode 100644 index 0000000000000000000000000000000000000000..484d62b46a87f43e3df240823bd9227d8ebd11bc --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.circleci/TROUBLESHOOT.md @@ -0,0 +1,7 @@ +# Troubleshooting + +This is a document explaining how to deal with various issues on Circle-CI. The entries may include actual solutions or pointers to Issues that cover those. + +## Circle CI + +* pytest worker runs out of resident RAM and gets killed by `cgroups`: https://github.com/huggingface/transformers/issues/11408 diff --git a/tasks/tasksmith-441eeab80047/tests/source/.circleci/config.yml b/tasks/tasksmith-441eeab80047/tests/source/.circleci/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..108e319d2cc72642f61f73265a992eba4953bbef --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.circleci/config.yml @@ -0,0 +1,224 @@ +version: 2.1 +setup: true +orbs: + continuation: circleci/continuation@0.1.0 + +parameters: + nightly: + type: boolean + default: false + +jobs: + # Ensure running with CircleCI/huggingface + check_circleci_user: + docker: + - image: python:3.10-slim + resource_class: small + parallelism: 1 + steps: + - run: echo $CIRCLE_PROJECT_USERNAME + - run: | + if [ "$CIRCLE_PROJECT_USERNAME" = "huggingface" ]; then + exit 0 + else + echo "The CI is running under $CIRCLE_PROJECT_USERNAME personal account. Please follow https://support.circleci.com/hc/en-us/articles/360008097173-Troubleshooting-why-pull-requests-are-not-triggering-jobs-on-my-organization- to fix it."; exit -1 + fi + # Fetch the tests to run + fetch_tests: + working_directory: ~/transformers + docker: + - image: huggingface/transformers-quality + parallelism: 1 + steps: + - checkout + - run: if [[ "$CIRCLE_PULL_REQUEST" == "" && "$CIRCLE_BRANCH" != "main" && "$CIRCLE_BRANCH" != *-release ]]; then echo "Not a PR, not the main branch and not a release branch, skip test!"; circleci-agent step halt; fi + - run: 'curl -L -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pulls/${CIRCLE_PULL_REQUEST##*/} >> github.txt' + - run: cat github.txt + - run: (python3 -c 'import json; from datetime import datetime; fp = open("github.txt"); data = json.load(fp); fp.close(); f = "%Y-%m-%dT%H:%M:%SZ"; created = datetime.strptime(data["created_at"], f); updated = datetime.strptime(data["updated_at"], f); s = (updated - created).total_seconds(); print(int(s))' || true) > elapsed.txt + - run: if [ "$(cat elapsed.txt)" == "" ]; then echo 60 > elapsed.txt; fi + - run: cat elapsed.txt + - run: if [ "$(cat elapsed.txt)" -lt "30" ]; then echo "PR is just opened, wait some actions from GitHub"; sleep 30; fi + - run: 'if grep -q "\"draft\": true," github.txt; then echo "draft mode, skip test!"; circleci-agent step halt; fi' + - run: uv pip install -U -e . + - run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV" + - run: mkdir -p test_preparation + - run: python utils/tests_fetcher.py | tee tests_fetched_summary.txt + - run: python utils/tests_fetcher.py --filter_tests + - run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation + - run: | + if [ ! -s test_preparation/generated_config.yml ]; then + echo "No tests to run, exiting early!" + circleci-agent step halt + fi + + - store_artifacts: + path: test_preparation + + - run: + name: "Retrieve Artifact Paths" + # [reference] https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts + # `CIRCLE_TOKEN` is defined as an environment variables set within a context, see `https://circleci.com/docs/contexts/` + command: | + project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}" + job_number=${CIRCLE_BUILD_NUM} + url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts" + curl -o test_preparation/artifacts.json ${url} --header "Circle-Token: $CIRCLE_TOKEN" + - run: + name: "Prepare pipeline parameters" + command: | + python utils/process_test_artifacts.py + + # To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters. + # Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation. + # We used: + + # https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts + # We could not pass a nested dict, which is why we create the test_file_... parameters for every single job + + - store_artifacts: + path: test_preparation/transformed_artifacts.json + - store_artifacts: + path: test_preparation/artifacts.json + - continuation/continue: + parameters: test_preparation/transformed_artifacts.json + configuration_path: test_preparation/generated_config.yml + + # To run all tests for the nightly build + fetch_all_tests: + working_directory: ~/transformers + docker: + - image: huggingface/transformers-quality + parallelism: 1 + steps: + - checkout + - run: uv pip install -U -e . + - run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV" + - run: mkdir -p test_preparation + - run: python utils/tests_fetcher.py --fetch_all | tee tests_fetched_summary.txt + - run: python utils/tests_fetcher.py --filter_tests + - run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation + - run: | + if [ ! -s test_preparation/generated_config.yml ]; then + echo "No tests to run, exiting early!" + circleci-agent step halt + fi + + - store_artifacts: + path: test_preparation + + - run: + name: "Retrieve Artifact Paths" + env: + CIRCLE_TOKEN: ${{ secrets.CI_ARTIFACT_TOKEN }} + command: | + project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}" + job_number=${CIRCLE_BUILD_NUM} + url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts" + curl -o test_preparation/artifacts.json ${url} + - run: + name: "Prepare pipeline parameters" + command: | + python utils/process_test_artifacts.py + + # To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters. + # Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation. + # We used: + + # https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts + # We could not pass a nested dict, which is why we create the test_file_... parameters for every single job + + - store_artifacts: + path: test_preparation/transformed_artifacts.json + - store_artifacts: + path: test_preparation/artifacts.json + - continuation/continue: + parameters: test_preparation/transformed_artifacts.json + configuration_path: test_preparation/generated_config.yml + + check_code_quality: + working_directory: ~/transformers + docker: + - image: huggingface/transformers-quality + resource_class: large + environment: + TRANSFORMERS_IS_CI: yes + PYTEST_TIMEOUT: 120 + parallelism: 1 + steps: + - checkout + - run: uv pip install -e ".[quality]" + - run: + name: Show installed libraries and their versions + command: pip freeze | tee installed.txt + - store_artifacts: + path: ~/transformers/installed.txt + - run: python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) + - run: ruff check examples tests src utils + - run: ruff format tests src utils --check + - run: python utils/custom_init_isort.py --check_only + - run: python utils/sort_auto_mappings.py --check_only + - run: python utils/check_doc_toc.py + - run: python utils/check_docstrings.py --check_all + + check_repository_consistency: + working_directory: ~/transformers + docker: + - image: huggingface/transformers-consistency + resource_class: large + environment: + TRANSFORMERS_IS_CI: yes + PYTEST_TIMEOUT: 120 + parallelism: 1 + steps: + - checkout + - run: uv pip install -e ".[quality]" + - run: + name: Show installed libraries and their versions + command: pip freeze | tee installed.txt + - store_artifacts: + path: ~/transformers/installed.txt + - run: python utils/check_copies.py + - run: python utils/check_modular_conversion.py + - run: python utils/check_dummies.py + - run: python utils/check_repo.py + - run: python utils/check_inits.py + - run: python utils/check_config_docstrings.py + - run: python utils/check_config_attributes.py + - run: python utils/check_doctest_list.py + - run: make deps_table_check_updated + - run: python utils/update_metadata.py --check-only + - run: python utils/check_docstrings.py + +workflows: + version: 2 + setup_and_quality: + when: + and: + - equal: [<>, https://github.com/huggingface/transformers] + - not: <> + jobs: + - check_circleci_user + - check_code_quality + - check_repository_consistency + - fetch_tests + + setup_and_quality_2: + when: + not: + equal: [<>, https://github.com/huggingface/transformers] + jobs: + - check_circleci_user + - check_code_quality + - check_repository_consistency + - fetch_tests: + # [reference] https://circleci.com/docs/contexts/ + context: + - TRANSFORMERS_CONTEXT + + nightly: + when: <> + jobs: + - check_circleci_user + - check_code_quality + - check_repository_consistency + - fetch_all_tests diff --git a/tasks/tasksmith-441eeab80047/tests/source/.circleci/create_circleci_config.py b/tasks/tasksmith-441eeab80047/tests/source/.circleci/create_circleci_config.py new file mode 100644 index 0000000000000000000000000000000000000000..156765d30f30a41331df433f819f6245ba7a2e31 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.circleci/create_circleci_config.py @@ -0,0 +1,389 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import copy +import os +import random +from dataclasses import dataclass +from typing import Any, Dict, List, Optional +import glob +import yaml + + +COMMON_ENV_VARIABLES = { + "OMP_NUM_THREADS": 1, + "TRANSFORMERS_IS_CI": True, + "PYTEST_TIMEOUT": 120, + "RUN_PIPELINE_TESTS": False, +} +# Disable the use of {"s": None} as the output is way too long, causing the navigation on CircleCI impractical +COMMON_PYTEST_OPTIONS = {"max-worker-restart": 0, "dist": "loadfile", "vvv": None, "rsfE":None} +DEFAULT_DOCKER_IMAGE = [{"image": "cimg/python:3.8.12"}] + + +class EmptyJob: + job_name = "empty" + + def to_dict(self): + steps = [{"run": 'ls -la'}] + if self.job_name == "collection_job": + steps.extend( + [ + "checkout", + {"run": "pip install requests || true"}, + {"run": """while [[ $(curl --location --request GET "https://circleci.com/api/v2/workflow/$CIRCLE_WORKFLOW_ID/job" --header "Circle-Token: $CCI_TOKEN"| jq -r '.items[]|select(.name != "collection_job")|.status' | grep -c "running") -gt 0 ]]; do sleep 5; done || true"""}, + {"run": 'python utils/process_circleci_workflow_test_reports.py --workflow_id $CIRCLE_WORKFLOW_ID || true'}, + {"store_artifacts": {"path": "outputs"}}, + {"run": 'echo "All required jobs have now completed"'}, + ] + ) + + return { + "docker": copy.deepcopy(DEFAULT_DOCKER_IMAGE), + "resource_class": "small", + "steps": steps, + } + + +@dataclass +class CircleCIJob: + name: str + additional_env: Dict[str, Any] = None + docker_image: List[Dict[str, str]] = None + install_steps: List[str] = None + marker: Optional[str] = None + parallelism: Optional[int] = 0 + pytest_num_workers: int = 8 + pytest_options: Dict[str, Any] = None + resource_class: Optional[str] = "xlarge" + tests_to_run: Optional[List[str]] = None + num_test_files_per_worker: Optional[int] = 10 + # This should be only used for doctest job! + command_timeout: Optional[int] = None + + def __post_init__(self): + # Deal with defaults for mutable attributes. + if self.additional_env is None: + self.additional_env = {} + if self.docker_image is None: + # Let's avoid changing the default list and make a copy. + self.docker_image = copy.deepcopy(DEFAULT_DOCKER_IMAGE) + else: + # BIG HACK WILL REMOVE ONCE FETCHER IS UPDATED + print(os.environ.get("GIT_COMMIT_MESSAGE")) + if "[build-ci-image]" in os.environ.get("GIT_COMMIT_MESSAGE", "") or os.environ.get("GIT_COMMIT_MESSAGE", "") == "dev-ci": + self.docker_image[0]["image"] = f"{self.docker_image[0]['image']}:dev" + print(f"Using {self.docker_image} docker image") + if self.install_steps is None: + self.install_steps = ["uv venv && uv pip install ."] + if self.pytest_options is None: + self.pytest_options = {} + if isinstance(self.tests_to_run, str): + self.tests_to_run = [self.tests_to_run] + else: + test_file = os.path.join("test_preparation" , f"{self.job_name}_test_list.txt") + print("Looking for ", test_file) + if os.path.exists(test_file): + with open(test_file) as f: + expanded_tests = f.read().strip().split("\n") + self.tests_to_run = expanded_tests + print("Found:", expanded_tests) + else: + self.tests_to_run = [] + print("not Found") + + def to_dict(self): + env = COMMON_ENV_VARIABLES.copy() + env.update(self.additional_env) + + job = { + "docker": self.docker_image, + "environment": env, + } + if self.resource_class is not None: + job["resource_class"] = self.resource_class + + all_options = {**COMMON_PYTEST_OPTIONS, **self.pytest_options} + pytest_flags = [f"--{key}={value}" if (value is not None or key in ["doctest-modules"]) else f"-{key}" for key, value in all_options.items()] + pytest_flags.append( + f"--make-reports={self.name}" if "examples" in self.name else f"--make-reports=tests_{self.name}" + ) + # Examples special case: we need to download NLTK files in advance to avoid cuncurrency issues + timeout_cmd = f"timeout {self.command_timeout} " if self.command_timeout else "" + marker_cmd = f"-m '{self.marker}'" if self.marker is not None else "" + additional_flags = f" -p no:warning -o junit_family=xunit1 --junitxml=test-results/junit.xml" + parallel = f' << pipeline.parameters.{self.job_name}_parallelism >> ' + steps = [ + "checkout", + {"attach_workspace": {"at": "test_preparation"}}, + {"run": "apt-get update && apt-get install -y curl"}, + {"run": " && ".join(self.install_steps)}, + {"run": {"name": "Download NLTK files", "command": """python -c "import nltk; nltk.download('punkt', quiet=True)" """} if "example" in self.name else "echo Skipping"}, + {"run": { + "name": "Show installed libraries and their size", + "command": """du -h -d 1 "$(pip -V | cut -d ' ' -f 4 | sed 's/pip//g')" | grep -vE "dist-info|_distutils_hack|__pycache__" | sort -h | tee installed.txt || true"""} + }, + {"run": { + "name": "Show installed libraries and their versions", + "command": """pip list --format=freeze | tee installed.txt || true"""} + }, + {"run": { + "name": "Show biggest libraries", + "command": """dpkg-query --show --showformat='${Installed-Size}\t${Package}\n' | sort -rh | head -25 | sort -h | awk '{ package=$2; sub(".*/", "", package); printf("%.5f GB %s\n", $1/1024/1024, package)}' || true"""} + }, + {"run": {"name": "Create `test-results` directory", "command": "mkdir test-results"}}, + {"run": {"name": "Get files to test", "command":f'curl -L -o {self.job_name}_test_list.txt <> --header "Circle-Token: $CIRCLE_TOKEN"' if self.name != "pr_documentation_tests" else 'echo "Skipped"'}}, + {"run": {"name": "Split tests across parallel nodes: show current parallel tests", + "command": f"TESTS=$(circleci tests split --split-by=timings {self.job_name}_test_list.txt) && echo $TESTS > splitted_tests.txt && echo $TESTS | tr ' ' '\n'" if self.parallelism else f"awk '{{printf \"%s \", $0}}' {self.job_name}_test_list.txt > splitted_tests.txt" + } + }, + {"run": { + "name": "Run tests", + "command": f"({timeout_cmd} python3 -m pytest {marker_cmd} -n {self.pytest_num_workers} {additional_flags} {' '.join(pytest_flags)} $(cat splitted_tests.txt) | tee tests_output.txt)"} + }, + {"run": {"name": "Expand to show skipped tests", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --skip"}}, + {"run": {"name": "Failed tests: show reasons", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --fail"}}, + {"run": {"name": "Errors", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --errors"}}, + {"store_test_results": {"path": "test-results"}}, + {"store_artifacts": {"path": "test-results/junit.xml"}}, + {"store_artifacts": {"path": "reports"}}, + {"store_artifacts": {"path": "tests.txt"}}, + {"store_artifacts": {"path": "splitted_tests.txt"}}, + {"store_artifacts": {"path": "installed.txt"}}, + ] + if self.parallelism: + job["parallelism"] = parallel + job["steps"] = steps + return job + + @property + def job_name(self): + return self.name if ("examples" in self.name or "pipeline" in self.name or "pr_documentation" in self.name) else f"tests_{self.name}" + + +# JOBS +torch_job = CircleCIJob( + "torch", + docker_image=[{"image": "huggingface/transformers-torch-light"}], + marker="not generate", + parallelism=6, +) + +generate_job = CircleCIJob( + "generate", + docker_image=[{"image": "huggingface/transformers-torch-light"}], + marker="generate", + parallelism=6, +) + +tokenization_job = CircleCIJob( + "tokenization", + docker_image=[{"image": "huggingface/transformers-torch-light"}], + parallelism=8, +) + +processor_job = CircleCIJob( + "processors", + docker_image=[{"image": "huggingface/transformers-torch-light"}], + parallelism=8, +) + +tf_job = CircleCIJob( + "tf", + docker_image=[{"image":"huggingface/transformers-tf-light"}], + parallelism=6, +) + + +flax_job = CircleCIJob( + "flax", + docker_image=[{"image":"huggingface/transformers-jax-light"}], + parallelism=6, + pytest_num_workers=16, + resource_class="2xlarge", +) + + +pipelines_torch_job = CircleCIJob( + "pipelines_torch", + additional_env={"RUN_PIPELINE_TESTS": True}, + docker_image=[{"image":"huggingface/transformers-torch-light"}], + marker="is_pipeline_test", + parallelism=4, +) + + +pipelines_tf_job = CircleCIJob( + "pipelines_tf", + additional_env={"RUN_PIPELINE_TESTS": True}, + docker_image=[{"image":"huggingface/transformers-tf-light"}], + marker="is_pipeline_test", + parallelism=4, +) + + +custom_tokenizers_job = CircleCIJob( + "custom_tokenizers", + additional_env={"RUN_CUSTOM_TOKENIZERS": True}, + docker_image=[{"image": "huggingface/transformers-custom-tokenizers"}], +) + + +examples_torch_job = CircleCIJob( + "examples_torch", + additional_env={"OMP_NUM_THREADS": 8}, + docker_image=[{"image":"huggingface/transformers-examples-torch"}], + # TODO @ArthurZucker remove this once docker is easier to build + install_steps=["uv venv && uv pip install . && uv pip install -r examples/pytorch/_tests_requirements.txt"], +) + + +examples_tensorflow_job = CircleCIJob( + "examples_tensorflow", + additional_env={"OMP_NUM_THREADS": 8}, + docker_image=[{"image":"huggingface/transformers-examples-tf"}], +) + + +hub_job = CircleCIJob( + "hub", + additional_env={"HUGGINGFACE_CO_STAGING": True}, + docker_image=[{"image":"huggingface/transformers-torch-light"}], + install_steps=[ + 'uv venv && uv pip install .', + 'git config --global user.email "ci@dummy.com"', + 'git config --global user.name "ci"', + ], + marker="is_staging_test", + pytest_num_workers=2, + resource_class="medium", +) + + +onnx_job = CircleCIJob( + "onnx", + docker_image=[{"image":"huggingface/transformers-torch-tf-light"}], + install_steps=[ + "uv venv", + "uv pip install .[torch,tf,testing,sentencepiece,onnxruntime,vision,rjieba]", + ], + pytest_options={"k onnx": None}, + pytest_num_workers=1, + resource_class="small", +) + + +exotic_models_job = CircleCIJob( + "exotic_models", + docker_image=[{"image":"huggingface/transformers-exotic-models"}], + parallelism=4, + pytest_options={"durations": 100}, +) + + +repo_utils_job = CircleCIJob( + "repo_utils", + docker_image=[{"image":"huggingface/transformers-consistency"}], + pytest_num_workers=4, + resource_class="large", +) + + +non_model_job = CircleCIJob( + "non_model", + docker_image=[{"image": "huggingface/transformers-torch-light"}], + marker="not generate", + parallelism=6, +) + + +# We also include a `dummy.py` file in the files to be doc-tested to prevent edge case failure. Otherwise, the pytest +# hangs forever during test collection while showing `collecting 0 items / 21 errors`. (To see this, we have to remove +# the bash output redirection.) +py_command = 'from utils.tests_fetcher import get_doctest_files; to_test = get_doctest_files() + ["dummy.py"]; to_test = " ".join(to_test); print(to_test)' +py_command = f"$(python3 -c '{py_command}')" +command = f'echo """{py_command}""" > pr_documentation_tests_temp.txt' +doc_test_job = CircleCIJob( + "pr_documentation_tests", + docker_image=[{"image":"huggingface/transformers-consistency"}], + additional_env={"TRANSFORMERS_VERBOSITY": "error", "DATASETS_VERBOSITY": "error", "SKIP_CUDA_DOCTEST": "1"}, + install_steps=[ + # Add an empty file to keep the test step running correctly even no file is selected to be tested. + "uv venv && pip install .", + "touch dummy.py", + command, + "cat pr_documentation_tests_temp.txt", + "tail -n1 pr_documentation_tests_temp.txt | tee pr_documentation_tests_test_list.txt" + ], + tests_to_run="$(cat pr_documentation_tests.txt)", # noqa + pytest_options={"-doctest-modules": None, "doctest-glob": "*.md", "dist": "loadfile", "rvsA": None}, + command_timeout=1200, # test cannot run longer than 1200 seconds + pytest_num_workers=1, +) + +REGULAR_TESTS = [torch_job, tf_job, flax_job, hub_job, onnx_job, tokenization_job, processor_job, generate_job, non_model_job] # fmt: skip +EXAMPLES_TESTS = [examples_torch_job, examples_tensorflow_job] +PIPELINE_TESTS = [pipelines_torch_job, pipelines_tf_job] +REPO_UTIL_TESTS = [repo_utils_job] +DOC_TESTS = [doc_test_job] +ALL_TESTS = REGULAR_TESTS + EXAMPLES_TESTS + PIPELINE_TESTS + REPO_UTIL_TESTS + DOC_TESTS + [custom_tokenizers_job] + [exotic_models_job] # fmt: skip + + +def create_circleci_config(folder=None): + if folder is None: + folder = os.getcwd() + os.environ["test_preparation_dir"] = folder + jobs = [k for k in ALL_TESTS if os.path.isfile(os.path.join("test_preparation" , f"{k.job_name}_test_list.txt") )] + print("The following jobs will be run ", jobs) + + if len(jobs) == 0: + jobs = [EmptyJob()] + else: + print("Full list of job name inputs", {j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs}) + # Add a job waiting all the test jobs and aggregate their test summary files at the end + collection_job = EmptyJob() + collection_job.job_name = "collection_job" + jobs = [collection_job] + jobs + + config = { + "version": "2.1", + "parameters": { + # Only used to accept the parameters from the trigger + "nightly": {"type": "boolean", "default": False}, + "tests_to_run": {"type": "string", "default": ''}, + **{j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs}, + **{j.job_name + "_parallelism":{"type":"integer", "default":1} for j in jobs}, + }, + "jobs": {j.job_name: j.to_dict() for j in jobs} + } + if "CIRCLE_TOKEN" in os.environ: + # For private forked repo. (e.g. new model addition) + config["workflows"] = {"version": 2, "run_tests": {"jobs": [{j.job_name: {"context": ["TRANSFORMERS_CONTEXT"]}} for j in jobs]}} + else: + # For public repo. (e.g. `transformers`) + config["workflows"] = {"version": 2, "run_tests": {"jobs": [j.job_name for j in jobs]}} + with open(os.path.join(folder, "generated_config.yml"), "w") as f: + f.write(yaml.dump(config, sort_keys=False, default_flow_style=False).replace("' << pipeline", " << pipeline").replace(">> '", " >>")) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--fetcher_folder", type=str, default=None, help="Only test that all tests and modules are accounted for." + ) + args = parser.parse_args() + + create_circleci_config(args.fetcher_folder) diff --git a/tasks/tasksmith-441eeab80047/tests/source/.circleci/parse_test_outputs.py b/tasks/tasksmith-441eeab80047/tests/source/.circleci/parse_test_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..a69da1a3eafb27f37ee7115472aad11b8736690b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.circleci/parse_test_outputs.py @@ -0,0 +1,70 @@ +import re +import argparse + +def parse_pytest_output(file_path): + skipped_tests = {} + skipped_count = 0 + with open(file_path, 'r') as file: + for line in file: + match = re.match(r'^SKIPPED \[(\d+)\] (tests/.*): (.*)$', line) + if match: + skipped_count += 1 + test_file, test_line, reason = match.groups() + skipped_tests[reason] = skipped_tests.get(reason, []) + [(test_file, test_line)] + for k,v in sorted(skipped_tests.items(), key=lambda x:len(x[1])): + print(f"{len(v):4} skipped because: {k}") + print("Number of skipped tests:", skipped_count) + +def parse_pytest_failure_output(file_path): + failed_tests = {} + failed_count = 0 + with open(file_path, 'r') as file: + for line in file: + match = re.match(r'^FAILED (tests/.*) - (.*): (.*)$', line) + if match: + failed_count += 1 + _, error, reason = match.groups() + failed_tests[reason] = failed_tests.get(reason, []) + [error] + for k,v in sorted(failed_tests.items(), key=lambda x:len(x[1])): + print(f"{len(v):4} failed because `{v[0]}` -> {k}") + print("Number of failed tests:", failed_count) + if failed_count>0: + exit(1) + +def parse_pytest_errors_output(file_path): + print(file_path) + error_tests = {} + error_count = 0 + with open(file_path, 'r') as file: + for line in file: + match = re.match(r'^ERROR (tests/.*) - (.*): (.*)$', line) + if match: + error_count += 1 + _, test_error, reason = match.groups() + error_tests[reason] = error_tests.get(reason, []) + [test_error] + for k,v in sorted(error_tests.items(), key=lambda x:len(x[1])): + print(f"{len(v):4} errored out because of `{v[0]}` -> {k}") + print("Number of errors:", error_count) + if error_count>0: + exit(1) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--file", help="file to parse") + parser.add_argument("--skip", action="store_true", help="show skipped reasons") + parser.add_argument("--fail", action="store_true", help="show failed tests") + parser.add_argument("--errors", action="store_true", help="show failed tests") + args = parser.parse_args() + + if args.skip: + parse_pytest_output(args.file) + + if args.fail: + parse_pytest_failure_output(args.file) + + if args.errors: + parse_pytest_errors_output(args.file) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-441eeab80047/tests/source/.gitattributes b/tasks/tasksmith-441eeab80047/tests/source/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..6505bc7edf9af5694cee1a93b90c565872fbbeb9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.gitattributes @@ -0,0 +1,4 @@ +*.py eol=lf +*.rst eol=lf +*.md eol=lf +*.mdx eol=lf \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..77c4d92b9f6cd375243169ff7c54c4795d7d5709 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,128 @@ +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve transformers +labels: [ "bug" ] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! 🤗 + + Before you submit your bug report: + + - If it is your first time submitting, be sure to check our [bug report guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#did-you-find-a-bug) + - Try our [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat) -- it might be able to help you with your issue + + - type: textarea + id: system-info + attributes: + label: System Info + description: Please share your system info with us. You can run the command `transformers-cli env` and copy-paste its output below. + placeholder: transformers version, platform, python version, ... + validations: + required: true + + - type: textarea + id: who-can-help + attributes: + label: Who can help? + description: | + Your issue will be replied to more quickly if you can figure out the right person to tag with @ + If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**. + + All issues are read by one of the core maintainers, so if you don't know who to tag, just leave this blank and + a core maintainer will ping the right person. + + Please tag fewer than 3 people. + + Models: + + - text models: @ArthurZucker + - vision models: @amyeroberts, @qubvel + - speech models: @eustlb + - graph models: @clefourrier + + Library: + + - flax: @gante and @Rocketknight1 + - generate: @zucchini-nlp (visual-language models) or @gante (all others) + - pipelines: @Rocketknight1 + - tensorflow: @gante and @Rocketknight1 + - tokenizers: @ArthurZucker and @itazap + - trainer: @muellerzr @SunMarc + + Integrations: + + - deepspeed: HF Trainer/Accelerate: @muellerzr + - ray/raytune: @richardliaw, @amogkam + - Big Model Inference: @SunMarc + - quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber + + Documentation: @stevhliu + + Model hub: + + - for issues with a model, report at https://discuss.huggingface.co/ and tag the model's creator. + + HF projects: + + - accelerate: [different repo](https://github.com/huggingface/accelerate) + - datasets: [different repo](https://github.com/huggingface/datasets) + - diffusers: [different repo](https://github.com/huggingface/diffusers) + - rust tokenizers: [different repo](https://github.com/huggingface/tokenizers) + + Maintained examples (not research project or legacy): + + - Flax: @Rocketknight1 + - PyTorch: See Models above and tag the person corresponding to the modality of the example. + - TensorFlow: @Rocketknight1 + + Research projects are not maintained and should be taken as is. + + placeholder: "@Username ..." + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + Please include relevant config information with your code, for example your Trainers, TRL, Peft, and DeepSpeed configs. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + placeholder: | + Steps to reproduce the behavior: + + 1. + 2. + 3. + + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/config.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..1b9386d11221fc6be29a88ee0b77e768a4d5eb9d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,12 @@ +blank_issues_enabled: true +version: 2.1 +contact_links: + - name: Model checkpoints on the Hugging Face Hub + url: https://huggingface.co/models + about: Open a Pull request / Discussion related to a specific model checkpoint directly on the Hugging Face Hub + - name: Website Related + url: https://github.com/huggingface/hub-docs/issues + about: Feature requests and bug reports related to the website + - name: Forum + url: https://discuss.huggingface.co/ + about: General usage questions and community discussions diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff0d452a807f6e12958b8e91dd8f18bcbf7962a4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,31 @@ +name: "\U0001F680 Feature request" +description: Submit a proposal/request for a new transformers feature +labels: [ "Feature request" ] +body: + - type: textarea + id: feature-request + validations: + required: true + attributes: + label: Feature request + description: | + A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist. + + - type: textarea + id: motivation + validations: + required: true + attributes: + label: Motivation + description: | + Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too. + + + - type: textarea + id: contribution + validations: + required: true + attributes: + label: Your contribution + description: | + Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/i18n.md b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/i18n.md new file mode 100644 index 0000000000000000000000000000000000000000..5b91427d55b73c616d9320cefbecf61787c51c1e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/i18n.md @@ -0,0 +1,46 @@ +--- +name: 🌐 Translating a new language? +about: Start a new translation effort in your language +title: '[i18n-] Translating docs to ' +labels: WIP +assignees: '' + +--- + + + +Hi! + +Let's bring the documentation to all the -speaking community 🌐 (currently 0 out of 267 complete) + +Who would want to translate? Please follow the 🤗 [TRANSLATING guide](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). Here is a list of the files ready for translation. Let us know in this issue if you'd like to translate any, and we'll add your name to the list. + +Some notes: + +* Please translate using an informal tone (imagine you are talking with a friend about transformers 🤗). +* Please translate in a gender-neutral way. +* Add your translations to the folder called `` inside the [source folder](https://github.com/huggingface/transformers/tree/main/docs/source). +* Register your translation in `/_toctree.yml`; please follow the order of the [English version](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml). +* Once you're finished, open a pull request and tag this issue by including #issue-number in the description, where issue-number is the number of this issue. Please ping @stevhliu and @MKhalusova for review. +* 🙋 If you'd like others to help you with the translation, you can also post in the 🤗 [forums](https://discuss.huggingface.co/). + +## Get Started section + +- [ ] [index.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/index.md) https://github.com/huggingface/transformers/pull/20180 +- [ ] [quicktour.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/quicktour.md) (waiting for initial PR to go through) +- [ ] [installation.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/installation.md). + +## Tutorial section +- [ ] [pipeline_tutorial.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/pipeline_tutorial.md) +- [ ] [autoclass_tutorial.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/autoclass_tutorial.md) +- [ ] [preprocessing.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/preprocessing.md) +- [ ] [training.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/training.md) +- [ ] [accelerate.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/accelerate.md) +- [ ] [model_sharing.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_sharing.md) +- [ ] [multilingual.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/multilingual.md) + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/migration.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/migration.yml new file mode 100644 index 0000000000000000000000000000000000000000..778413141b1f3b42f71c123a4d83f61bc01663e1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/migration.yml @@ -0,0 +1,72 @@ +name: "\U0001F4DA Migration from pytorch-pretrained-bert or pytorch-transformers" +description: Report a problem when migrating from pytorch-pretrained-bert or pytorch-transformers to transformers +labels: [ "migration" ] +body: + - type: textarea + id: system-info + attributes: + label: System Info + description: Please share your system info with us. You can run the command `transformers-cli env` and copy-paste its output below. + render: shell + placeholder: transformers version, platform, python version, ... + validations: + required: true + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + placeholder: | + Steps to reproduce the behavior: + + 1. + 2. + 3. + + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." + render: shell + + - type: checkboxes + id: checklist + attributes: + label: Checklist + options: + - label: "I have read the migration guide in the readme. + ([pytorch-transformers](https://github.com/huggingface/transformers#migrating-from-pytorch-transformers-to-transformers); + [pytorch-pretrained-bert](https://github.com/huggingface/transformers#migrating-from-pytorch-pretrained-bert-to-transformers))" + required: true + - label: "I checked if a related official extension example runs on my machine." + required: true diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml new file mode 100644 index 0000000000000000000000000000000000000000..2f3476d3ab095ffb109b2b498247a0984cd0b500 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml @@ -0,0 +1,31 @@ +name: "\U0001F31F New model addition" +description: Submit a proposal/request to implement a new model +labels: [ "New model" ] + +body: + - type: textarea + id: description-request + validations: + required: true + attributes: + label: Model description + description: | + Put any and all important information relative to the model + + - type: checkboxes + id: information-tasks + attributes: + label: Open source status + description: | + Please note that if the model implementation isn't available or if the weights aren't open-source, we are less likely to implement it in `transformers`. + options: + - label: "The model implementation is available" + - label: "The model weights are available" + + - type: textarea + id: additional-info + attributes: + label: Provide useful links for the implementation + description: | + Please provide information regarding the implementation, the weights, and the authors. + Please mention the authors by @gh-username if you're aware of their usernames. diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/PULL_REQUEST_TEMPLATE.md b/tasks/tasksmith-441eeab80047/tests/source/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..ca0035a629b6bc853a964e4484f1be7ee7dab386 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,79 @@ +# What does this PR do? + + + + + +Fixes # (issue) + + +## Before submitting +- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). +- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request), + Pull Request section? +- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link + to it if that's the case. +- [ ] Did you make sure to update the documentation with your changes? Here are the + [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and + [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation). +- [ ] Did you write any new necessary tests? + + +## Who can review? + +Anyone in the community is free to review the PR once the tests have passed. Feel free to tag +members/contributors who may be interested in your PR. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/conda/build.sh b/tasks/tasksmith-441eeab80047/tests/source/.github/conda/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..a40f1097a8631648d5c2cecb1be4dd144cc632c2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/conda/build.sh @@ -0,0 +1 @@ +$PYTHON setup.py install # Python command to install the script. diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/conda/meta.yaml b/tasks/tasksmith-441eeab80047/tests/source/.github/conda/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..89dc353b127774528faa0c979e28215be12de6f0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/conda/meta.yaml @@ -0,0 +1,56 @@ +{% set name = "transformers" %} + +package: + name: "{{ name|lower }}" + version: "{{ TRANSFORMERS_VERSION }}" + +source: + path: ../../ + +build: + noarch: python + +requirements: + host: + - python + - pip + - numpy >=1.17 + - dataclasses + - huggingface_hub + - packaging + - filelock + - requests + - tqdm >=4.27 + - sacremoses + - regex !=2019.12.17 + - protobuf + - tokenizers >=0.11.1,!=0.11.3,<0.13 + - pyyaml >=5.1 + - safetensors + - fsspec + run: + - python + - numpy >=1.17 + - dataclasses + - huggingface_hub + - packaging + - filelock + - requests + - tqdm >=4.27 + - sacremoses + - regex !=2019.12.17 + - protobuf + - tokenizers >=0.11.1,!=0.11.3,<0.13 + - pyyaml >=5.1 + - safetensors + - fsspec + +test: + imports: + - transformers + +about: + home: https://huggingface.co + license: Apache License 2.0 + license_file: LICENSE + summary: "🤗Transformers: State-of-the-art Natural Language Processing for Pytorch and TensorFlow 2.0." diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/assign_reviewers.py b/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/assign_reviewers.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8fd9b4be0919d406d9fddc99ee80435b0e4b10 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/assign_reviewers.py @@ -0,0 +1,98 @@ +# coding=utf-8 +# Copyright 2025 the HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import github +import json +from github import Github +import re +from collections import Counter +from pathlib import Path + +def pattern_to_regex(pattern): + start_anchor = pattern.startswith("/") + pattern = re.escape(pattern) + # Replace `*` with "any number of non-slash characters" + pattern = pattern.replace(r"\*", "[^/]*") + if start_anchor: + pattern = "^" + pattern + return pattern + +def get_file_owners(file_path, codeowners_lines): + # Process lines in reverse (last matching pattern takes precedence) + for line in reversed(codeowners_lines): + # Skip comments and empty lines, strip inline comments + line = line.split('#')[0].strip() + if not line: + continue + + # Split into pattern and owners + parts = line.split() + pattern = parts[0] + # Can be empty, e.g. for dummy files with explicitly no owner! + owners = [owner.removeprefix("@") for owner in parts[1:]] + + # Check if file matches pattern + file_regex = pattern_to_regex(pattern) + if re.search(file_regex, file_path) is not None: + return owners # Remember, can still be empty! + return [] # Should never happen, but just in case + +def main(): + script_dir = Path(__file__).parent.absolute() + with open(script_dir / "codeowners_for_review_action") as f: + codeowners_lines = f.readlines() + + g = Github(os.environ['GITHUB_TOKEN']) + repo = g.get_repo("huggingface/transformers") + with open(os.environ['GITHUB_EVENT_PATH']) as f: + event = json.load(f) + + # The PR number is available in the event payload + pr_number = event['pull_request']['number'] + pr = repo.get_pull(pr_number) + pr_author = pr.user.login + + existing_reviews = list(pr.get_reviews()) + if existing_reviews: + print(f"Already has reviews: {[r.user.login for r in existing_reviews]}") + return + + users_requested, teams_requested = pr.get_review_requests() + users_requested = list(users_requested) + if users_requested: + print(f"Reviewers already requested: {users_requested}") + return + + locs_per_owner = Counter() + for file in pr.get_files(): + owners = get_file_owners(file.filename, codeowners_lines) + for owner in owners: + locs_per_owner[owner] += file.changes + + # Assign the top 2 based on locs changed as reviewers, but skip the owner if present + locs_per_owner.pop(pr_author, None) + top_owners = locs_per_owner.most_common(2) + print("Top owners", top_owners) + top_owners = [owner[0] for owner in top_owners] + try: + pr.create_review_request(top_owners) + except github.GithubException as e: + print(f"Failed to request review for {top_owners}: {e}") + + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/codeowners_for_review_action b/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/codeowners_for_review_action new file mode 100644 index 0000000000000000000000000000000000000000..f3da6d516ca8fbb020f68447e22e12ad19837ede --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/scripts/codeowners_for_review_action @@ -0,0 +1,370 @@ +# Top-level rules are matched only if nothing else matches +* @Rocketknight1 @ArthurZucker # if no one is pinged based on the other rules, he will do the dispatch +*.md @stevhliu +*tokenization* @ArthurZucker +docs/ @stevhliu +/benchmark/ @McPatate +/docker/ @ydshieh @ArthurZucker + +# More high-level globs catch cases when specific rules later don't apply +/src/transformers/models/*/processing* @molbap @yonigozlan @qubvel +/src/transformers/models/*/image_processing* @qubvel +/src/transformers/models/*/image_processing_*_fast* @yonigozlan + +# Owners of subsections of the library +/src/transformers/generation/ @gante +/src/transformers/pipeline/ @Rocketknight1 @yonigozlan +/src/transformers/integrations/ @SunMarc @MekkCyber @muellerzr +/src/transformers/quantizers/ @SunMarc @MekkCyber +tests/ @ydshieh +tests/generation/ @gante + +/src/transformers/models/auto/ @ArthurZucker +/src/transformers/utils/ @ArthurZucker @Rocketknight1 +/src/transformers/loss/ @ArthurZucker +/src/transformers/onnx/ @michaelbenayoun + +# Specific files come after the sections/globs, so they take priority +/.circleci/config.yml @ArthurZucker @ydshieh +/utils/tests_fetcher.py @ydshieh +trainer.py @muellerzr @SunMarc +trainer_utils.py @muellerzr @SunMarc +/utils/modular_model_converter.py @Cyrilvallez @ArthurZucker + +# Owners of individual models are specific / high priority, and so they come last +# mod* captures modeling and modular files + +# Text models +/src/transformers/models/albert/mod*_albert* @ArthurZucker +/src/transformers/models/bamba/mod*_bamba* @ArthurZucker +/src/transformers/models/bart/mod*_bart* @ArthurZucker +/src/transformers/models/barthez/mod*_barthez* @ArthurZucker +/src/transformers/models/bartpho/mod*_bartpho* @ArthurZucker +/src/transformers/models/bert/mod*_bert* @ArthurZucker +/src/transformers/models/bert_generation/mod*_bert_generation* @ArthurZucker +/src/transformers/models/bert_japanese/mod*_bert_japanese* @ArthurZucker +/src/transformers/models/bertweet/mod*_bertweet* @ArthurZucker +/src/transformers/models/big_bird/mod*_big_bird* @ArthurZucker +/src/transformers/models/bigbird_pegasus/mod*_bigbird_pegasus* @ArthurZucker +/src/transformers/models/biogpt/mod*_biogpt* @ArthurZucker +/src/transformers/models/blenderbot/mod*_blenderbot* @ArthurZucker +/src/transformers/models/blenderbot_small/mod*_blenderbot_small* @ArthurZucker +/src/transformers/models/bloom/mod*_bloom* @ArthurZucker +/src/transformers/models/bort/mod*_bort* @ArthurZucker +/src/transformers/models/byt5/mod*_byt5* @ArthurZucker +/src/transformers/models/camembert/mod*_camembert* @ArthurZucker +/src/transformers/models/canine/mod*_canine* @ArthurZucker +/src/transformers/models/codegen/mod*_codegen* @ArthurZucker +/src/transformers/models/code_llama/mod*_code_llama* @ArthurZucker +/src/transformers/models/cohere/mod*_cohere* @ArthurZucker +/src/transformers/models/cohere2/mod*_cohere2* @ArthurZucker +/src/transformers/models/convbert/mod*_convbert* @ArthurZucker +/src/transformers/models/cpm/mod*_cpm* @ArthurZucker +/src/transformers/models/cpmant/mod*_cpmant* @ArthurZucker +/src/transformers/models/ctrl/mod*_ctrl* @ArthurZucker +/src/transformers/models/dbrx/mod*_dbrx* @ArthurZucker +/src/transformers/models/deberta/mod*_deberta* @ArthurZucker +/src/transformers/models/deberta_v2/mod*_deberta_v2* @ArthurZucker +/src/transformers/models/dialogpt/mod*_dialogpt* @ArthurZucker +/src/transformers/models/diffllama/mod*_diffllama* @ArthurZucker +/src/transformers/models/distilbert/mod*_distilbert* @ArthurZucker +/src/transformers/models/dpr/mod*_dpr* @ArthurZucker +/src/transformers/models/electra/mod*_electra* @ArthurZucker +/src/transformers/models/encoder_decoder/mod*_encoder_decoder* @ArthurZucker +/src/transformers/models/ernie/mod*_ernie* @ArthurZucker +/src/transformers/models/ernie_m/mod*_ernie_m* @ArthurZucker +/src/transformers/models/esm/mod*_esm* @ArthurZucker +/src/transformers/models/falcon/mod*_falcon* @ArthurZucker +/src/transformers/models/falcon3/mod*_falcon3* @ArthurZucker +/src/transformers/models/falcon_mamba/mod*_falcon_mamba* @ArthurZucker +/src/transformers/models/fastspeech2_conformer/mod*_fastspeech2_conformer* @ArthurZucker +/src/transformers/models/flan_t5/mod*_flan_t5* @ArthurZucker +/src/transformers/models/flan_ul2/mod*_flan_ul2* @ArthurZucker +/src/transformers/models/flaubert/mod*_flaubert* @ArthurZucker +/src/transformers/models/fnet/mod*_fnet* @ArthurZucker +/src/transformers/models/fsmt/mod*_fsmt* @ArthurZucker +/src/transformers/models/funnel/mod*_funnel* @ArthurZucker +/src/transformers/models/fuyu/mod*_fuyu* @ArthurZucker +/src/transformers/models/gemma/mod*_gemma* @ArthurZucker +/src/transformers/models/gemma2/mod*_gemma2* @ArthurZucker +/src/transformers/models/glm/mod*_glm* @ArthurZucker +/src/transformers/models/openai_gpt/mod*_openai_gpt* @ArthurZucker +/src/transformers/models/gpt_neo/mod*_gpt_neo* @ArthurZucker +/src/transformers/models/gpt_neox/mod*_gpt_neox* @ArthurZucker +/src/transformers/models/gpt_neox_japanese/mod*_gpt_neox_japanese* @ArthurZucker +/src/transformers/models/gptj/mod*_gptj* @ArthurZucker +/src/transformers/models/gpt2/mod*_gpt2* @ArthurZucker +/src/transformers/models/gpt_bigcode/mod*_gpt_bigcode* @ArthurZucker +/src/transformers/models/gptsan_japanese/mod*_gptsan_japanese* @ArthurZucker +/src/transformers/models/gpt_sw3/mod*_gpt_sw3* @ArthurZucker +/src/transformers/models/granite/mod*_granite* @ArthurZucker +/src/transformers/models/granitemoe/mod*_granitemoe* @ArthurZucker +/src/transformers/models/herbert/mod*_herbert* @ArthurZucker +/src/transformers/models/ibert/mod*_ibert* @ArthurZucker +/src/transformers/models/jamba/mod*_jamba* @ArthurZucker +/src/transformers/models/jetmoe/mod*_jetmoe* @ArthurZucker +/src/transformers/models/jukebox/mod*_jukebox* @ArthurZucker +/src/transformers/models/led/mod*_led* @ArthurZucker +/src/transformers/models/llama/mod*_llama* @ArthurZucker @Cyrilvallez +/src/transformers/models/longformer/mod*_longformer* @ArthurZucker +/src/transformers/models/longt5/mod*_longt5* @ArthurZucker +/src/transformers/models/luke/mod*_luke* @ArthurZucker +/src/transformers/models/m2m_100/mod*_m2m_100* @ArthurZucker +/src/transformers/models/madlad_400/mod*_madlad_400* @ArthurZucker +/src/transformers/models/mamba/mod*_mamba* @ArthurZucker +/src/transformers/models/mamba2/mod*_mamba2* @ArthurZucker +/src/transformers/models/marian/mod*_marian* @ArthurZucker +/src/transformers/models/markuplm/mod*_markuplm* @ArthurZucker +/src/transformers/models/mbart/mod*_mbart* @ArthurZucker +/src/transformers/models/mega/mod*_mega* @ArthurZucker +/src/transformers/models/megatron_bert/mod*_megatron_bert* @ArthurZucker +/src/transformers/models/megatron_gpt2/mod*_megatron_gpt2* @ArthurZucker +/src/transformers/models/mistral/mod*_mistral* @ArthurZucker +/src/transformers/models/mixtral/mod*_mixtral* @ArthurZucker +/src/transformers/models/mluke/mod*_mluke* @ArthurZucker +/src/transformers/models/mobilebert/mod*_mobilebert* @ArthurZucker +/src/transformers/models/modernbert/mod*_modernbert* @ArthurZucker +/src/transformers/models/mpnet/mod*_mpnet* @ArthurZucker +/src/transformers/models/mpt/mod*_mpt* @ArthurZucker +/src/transformers/models/mra/mod*_mra* @ArthurZucker +/src/transformers/models/mt5/mod*_mt5* @ArthurZucker +/src/transformers/models/mvp/mod*_mvp* @ArthurZucker +/src/transformers/models/myt5/mod*_myt5* @ArthurZucker +/src/transformers/models/nemotron/mod*_nemotron* @ArthurZucker +/src/transformers/models/nezha/mod*_nezha* @ArthurZucker +/src/transformers/models/nllb/mod*_nllb* @ArthurZucker +/src/transformers/models/nllb_moe/mod*_nllb_moe* @ArthurZucker +/src/transformers/models/nystromformer/mod*_nystromformer* @ArthurZucker +/src/transformers/models/olmo/mod*_olmo* @ArthurZucker +/src/transformers/models/olmo2/mod*_olmo2* @ArthurZucker +/src/transformers/models/olmoe/mod*_olmoe* @ArthurZucker +/src/transformers/models/open_llama/mod*_open_llama* @ArthurZucker +/src/transformers/models/opt/mod*_opt* @ArthurZucker +/src/transformers/models/pegasus/mod*_pegasus* @ArthurZucker +/src/transformers/models/pegasus_x/mod*_pegasus_x* @ArthurZucker +/src/transformers/models/persimmon/mod*_persimmon* @ArthurZucker +/src/transformers/models/phi/mod*_phi* @ArthurZucker +/src/transformers/models/phi3/mod*_phi3* @ArthurZucker +/src/transformers/models/phimoe/mod*_phimoe* @ArthurZucker +/src/transformers/models/phobert/mod*_phobert* @ArthurZucker +/src/transformers/models/plbart/mod*_plbart* @ArthurZucker +/src/transformers/models/prophetnet/mod*_prophetnet* @ArthurZucker +/src/transformers/models/qdqbert/mod*_qdqbert* @ArthurZucker +/src/transformers/models/qwen2/mod*_qwen2* @ArthurZucker +/src/transformers/models/qwen2_moe/mod*_qwen2_moe* @ArthurZucker +/src/transformers/models/rag/mod*_rag* @ArthurZucker +/src/transformers/models/realm/mod*_realm* @ArthurZucker +/src/transformers/models/recurrent_gemma/mod*_recurrent_gemma* @ArthurZucker +/src/transformers/models/reformer/mod*_reformer* @ArthurZucker +/src/transformers/models/rembert/mod*_rembert* @ArthurZucker +/src/transformers/models/retribert/mod*_retribert* @ArthurZucker +/src/transformers/models/roberta/mod*_roberta* @ArthurZucker +/src/transformers/models/roberta_prelayernorm/mod*_roberta_prelayernorm* @ArthurZucker +/src/transformers/models/roc_bert/mod*_roc_bert* @ArthurZucker +/src/transformers/models/roformer/mod*_roformer* @ArthurZucker +/src/transformers/models/rwkv/mod*_rwkv* @ArthurZucker +/src/transformers/models/splinter/mod*_splinter* @ArthurZucker +/src/transformers/models/squeezebert/mod*_squeezebert* @ArthurZucker +/src/transformers/models/stablelm/mod*_stablelm* @ArthurZucker +/src/transformers/models/starcoder2/mod*_starcoder2* @ArthurZucker +/src/transformers/models/switch_transformers/mod*_switch_transformers* @ArthurZucker +/src/transformers/models/t5/mod*_t5* @ArthurZucker +/src/transformers/models/t5v1.1/mod*_t5v1.1* @ArthurZucker +/src/transformers/models/tapex/mod*_tapex* @ArthurZucker +/src/transformers/models/transfo_xl/mod*_transfo_xl* @ArthurZucker +/src/transformers/models/ul2/mod*_ul2* @ArthurZucker +/src/transformers/models/umt5/mod*_umt5* @ArthurZucker +/src/transformers/models/xmod/mod*_xmod* @ArthurZucker +/src/transformers/models/xglm/mod*_xglm* @ArthurZucker +/src/transformers/models/xlm/mod*_xlm* @ArthurZucker +/src/transformers/models/xlm_prophetnet/mod*_xlm_prophetnet* @ArthurZucker +/src/transformers/models/xlm_roberta/mod*_xlm_roberta* @ArthurZucker +/src/transformers/models/xlm_roberta_xl/mod*_xlm_roberta_xl* @ArthurZucker +/src/transformers/models/xlm_v/mod*_xlm_v* @ArthurZucker +/src/transformers/models/xlnet/mod*_xlnet* @ArthurZucker +/src/transformers/models/yoso/mod*_yoso* @ArthurZucker +/src/transformers/models/zamba/mod*_zamba* @ArthurZucker + +# Vision models +/src/transformers/models/beit/mod*_beit* @amyeroberts @qubvel +/src/transformers/models/bit/mod*_bit* @amyeroberts @qubvel +/src/transformers/models/conditional_detr/mod*_conditional_detr* @amyeroberts @qubvel +/src/transformers/models/convnext/mod*_convnext* @amyeroberts @qubvel +/src/transformers/models/convnextv2/mod*_convnextv2* @amyeroberts @qubvel +/src/transformers/models/cvt/mod*_cvt* @amyeroberts @qubvel +/src/transformers/models/deformable_detr/mod*_deformable_detr* @amyeroberts @qubvel +/src/transformers/models/deit/mod*_deit* @amyeroberts @qubvel +/src/transformers/models/depth_anything/mod*_depth_anything* @amyeroberts @qubvel +/src/transformers/models/depth_anything_v2/mod*_depth_anything_v2* @amyeroberts @qubvel +/src/transformers/models/deta/mod*_deta* @amyeroberts @qubvel +/src/transformers/models/detr/mod*_detr* @amyeroberts @qubvel +/src/transformers/models/dinat/mod*_dinat* @amyeroberts @qubvel +/src/transformers/models/dinov2/mod*_dinov2* @amyeroberts @qubvel +/src/transformers/models/dinov2_with_registers/mod*_dinov2_with_registers* @amyeroberts @qubvel +/src/transformers/models/dit/mod*_dit* @amyeroberts @qubvel +/src/transformers/models/dpt/mod*_dpt* @amyeroberts @qubvel +/src/transformers/models/efficientformer/mod*_efficientformer* @amyeroberts @qubvel +/src/transformers/models/efficientnet/mod*_efficientnet* @amyeroberts @qubvel +/src/transformers/models/focalnet/mod*_focalnet* @amyeroberts @qubvel +/src/transformers/models/glpn/mod*_glpn* @amyeroberts @qubvel +/src/transformers/models/hiera/mod*_hiera* @amyeroberts @qubvel +/src/transformers/models/ijepa/mod*_ijepa* @amyeroberts @qubvel +/src/transformers/models/imagegpt/mod*_imagegpt* @amyeroberts @qubvel +/src/transformers/models/levit/mod*_levit* @amyeroberts @qubvel +/src/transformers/models/mask2former/mod*_mask2former* @amyeroberts @qubvel +/src/transformers/models/maskformer/mod*_maskformer* @amyeroberts @qubvel +/src/transformers/models/mobilenet_v1/mod*_mobilenet_v1* @amyeroberts @qubvel +/src/transformers/models/mobilenet_v2/mod*_mobilenet_v2* @amyeroberts @qubvel +/src/transformers/models/mobilevit/mod*_mobilevit* @amyeroberts @qubvel +/src/transformers/models/mobilevitv2/mod*_mobilevitv2* @amyeroberts @qubvel +/src/transformers/models/nat/mod*_nat* @amyeroberts @qubvel +/src/transformers/models/poolformer/mod*_poolformer* @amyeroberts @qubvel +/src/transformers/models/pvt/mod*_pvt* @amyeroberts @qubvel +/src/transformers/models/pvt_v2/mod*_pvt_v2* @amyeroberts @qubvel +/src/transformers/models/regnet/mod*_regnet* @amyeroberts @qubvel +/src/transformers/models/resnet/mod*_resnet* @amyeroberts @qubvel +/src/transformers/models/rt_detr/mod*_rt_detr* @amyeroberts @qubvel +/src/transformers/models/segformer/mod*_segformer* @amyeroberts @qubvel +/src/transformers/models/seggpt/mod*_seggpt* @amyeroberts @qubvel +/src/transformers/models/superpoint/mod*_superpoint* @amyeroberts @qubvel +/src/transformers/models/swiftformer/mod*_swiftformer* @amyeroberts @qubvel +/src/transformers/models/swin/mod*_swin* @amyeroberts @qubvel +/src/transformers/models/swinv2/mod*_swinv2* @amyeroberts @qubvel +/src/transformers/models/swin2sr/mod*_swin2sr* @amyeroberts @qubvel +/src/transformers/models/table_transformer/mod*_table_transformer* @amyeroberts @qubvel +/src/transformers/models/textnet/mod*_textnet* @amyeroberts @qubvel +/src/transformers/models/timm_wrapper/mod*_timm_wrapper* @amyeroberts @qubvel +/src/transformers/models/upernet/mod*_upernet* @amyeroberts @qubvel +/src/transformers/models/van/mod*_van* @amyeroberts @qubvel +/src/transformers/models/vit/mod*_vit* @amyeroberts @qubvel +/src/transformers/models/vit_hybrid/mod*_vit_hybrid* @amyeroberts @qubvel +/src/transformers/models/vitdet/mod*_vitdet* @amyeroberts @qubvel +/src/transformers/models/vit_mae/mod*_vit_mae* @amyeroberts @qubvel +/src/transformers/models/vitmatte/mod*_vitmatte* @amyeroberts @qubvel +/src/transformers/models/vit_msn/mod*_vit_msn* @amyeroberts @qubvel +/src/transformers/models/vitpose/mod*_vitpose* @amyeroberts @qubvel +/src/transformers/models/yolos/mod*_yolos* @amyeroberts @qubvel +/src/transformers/models/zoedepth/mod*_zoedepth* @amyeroberts @qubvel + +# Audio models +/src/transformers/models/audio_spectrogram_transformer/mod*_audio_spectrogram_transformer* @eustlb +/src/transformers/models/bark/mod*_bark* @eustlb +/src/transformers/models/clap/mod*_clap* @eustlb +/src/transformers/models/dac/mod*_dac* @eustlb +/src/transformers/models/encodec/mod*_encodec* @eustlb +/src/transformers/models/hubert/mod*_hubert* @eustlb +/src/transformers/models/mctct/mod*_mctct* @eustlb +/src/transformers/models/mimi/mod*_mimi* @eustlb +/src/transformers/models/mms/mod*_mms* @eustlb +/src/transformers/models/moshi/mod*_moshi* @eustlb +/src/transformers/models/musicgen/mod*_musicgen* @eustlb +/src/transformers/models/musicgen_melody/mod*_musicgen_melody* @eustlb +/src/transformers/models/pop2piano/mod*_pop2piano* @eustlb +/src/transformers/models/seamless_m4t/mod*_seamless_m4t* @eustlb +/src/transformers/models/seamless_m4t_v2/mod*_seamless_m4t_v2* @eustlb +/src/transformers/models/sew/mod*_sew* @eustlb +/src/transformers/models/sew_d/mod*_sew_d* @eustlb +/src/transformers/models/speech_to_text/mod*_speech_to_text* @eustlb +/src/transformers/models/speech_to_text_2/mod*_speech_to_text_2* @eustlb +/src/transformers/models/speecht5/mod*_speecht5* @eustlb +/src/transformers/models/unispeech/mod*_unispeech* @eustlb +/src/transformers/models/unispeech_sat/mod*_unispeech_sat* @eustlb +/src/transformers/models/univnet/mod*_univnet* @eustlb +/src/transformers/models/vits/mod*_vits* @eustlb +/src/transformers/models/wav2vec2/mod*_wav2vec2* @eustlb +/src/transformers/models/wav2vec2_bert/mod*_wav2vec2_bert* @eustlb +/src/transformers/models/wav2vec2_conformer/mod*_wav2vec2_conformer* @eustlb +/src/transformers/models/wav2vec2_phoneme/mod*_wav2vec2_phoneme* @eustlb +/src/transformers/models/wavlm/mod*_wavlm* @eustlb +/src/transformers/models/whisper/mod*_whisper* @eustlb +/src/transformers/models/xls_r/mod*_xls_r* @eustlb +/src/transformers/models/xlsr_wav2vec2/mod*_xlsr_wav2vec2* @eustlb + +# Video models +/src/transformers/models/timesformer/mod*_timesformer* @Rocketknight1 +/src/transformers/models/videomae/mod*_videomae* @Rocketknight1 +/src/transformers/models/vivit/mod*_vivit* @Rocketknight1 + +# Multimodal models +/src/transformers/models/align/mod*_align* @zucchini-nlp +/src/transformers/models/altclip/mod*_altclip* @zucchini-nlp +/src/transformers/models/aria/mod*_aria* @zucchini-nlp +/src/transformers/models/blip/mod*_blip* @zucchini-nlp +/src/transformers/models/blip_2/mod*_blip_2* @zucchini-nlp +/src/transformers/models/bridgetower/mod*_bridgetower* @zucchini-nlp +/src/transformers/models/bros/mod*_bros* @zucchini-nlp +/src/transformers/models/chameleon/mod*_chameleon* @zucchini-nlp +/src/transformers/models/chinese_clip/mod*_chinese_clip* @zucchini-nlp +/src/transformers/models/clip/mod*_clip* @zucchini-nlp +/src/transformers/models/clipseg/mod*_clipseg* @zucchini-nlp +/src/transformers/models/clvp/mod*_clvp* @zucchini-nlp +/src/transformers/models/colpali/mod*_colpali* @zucchini-nlp @yonigozlan +/src/transformers/models/data2vec/mod*_data2vec* @zucchini-nlp +/src/transformers/models/deplot/mod*_deplot* @zucchini-nlp +/src/transformers/models/donut/mod*_donut* @zucchini-nlp +/src/transformers/models/flava/mod*_flava* @zucchini-nlp +/src/transformers/models/git/mod*_git* @zucchini-nlp +/src/transformers/models/grounding_dino/mod*_grounding_dino* @qubvel +/src/transformers/models/groupvit/mod*_groupvit* @zucchini-nlp +/src/transformers/models/idefics/mod*_idefics* @zucchini-nlp +/src/transformers/models/idefics2/mod*_idefics2* @zucchini-nlp +/src/transformers/models/idefics3/mod*_idefics3* @zucchini-nlp +/src/transformers/models/instructblip/mod*_instructblip* @zucchini-nlp +/src/transformers/models/instructblipvideo/mod*_instructblipvideo* @zucchini-nlp +/src/transformers/models/kosmos_2/mod*_kosmos_2* @zucchini-nlp +/src/transformers/models/layoutlm/mod*_layoutlm* @NielsRogge +/src/transformers/models/layoutlmv2/mod*_layoutlmv2* @NielsRogge +/src/transformers/models/layoutlmv3/mod*_layoutlmv3* @NielsRogge +/src/transformers/models/layoutxlm/mod*_layoutxlm* @NielsRogge +/src/transformers/models/lilt/mod*_lilt* @zucchini-nlp +/src/transformers/models/llava/mod*_llava* @zucchini-nlp @arthurzucker +/src/transformers/models/llava_next/mod*_llava_next* @zucchini-nlp +/src/transformers/models/llava_next_video/mod*_llava_next_video* @zucchini-nlp +/src/transformers/models/llava_onevision/mod*_llava_onevision* @zucchini-nlp +/src/transformers/models/lxmert/mod*_lxmert* @zucchini-nlp +/src/transformers/models/matcha/mod*_matcha* @zucchini-nlp +/src/transformers/models/mgp_str/mod*_mgp_str* @zucchini-nlp +/src/transformers/models/mllama/mod*_mllama* @zucchini-nlp +/src/transformers/models/nougat/mod*_nougat* @NielsRogge +/src/transformers/models/omdet_turbo/mod*_omdet_turbo* @qubvel @yonigozlan +/src/transformers/models/oneformer/mod*_oneformer* @zucchini-nlp +/src/transformers/models/owlvit/mod*_owlvit* @qubvel +/src/transformers/models/owlv2/mod*_owlv2* @qubvel +/src/transformers/models/paligemma/mod*_paligemma* @zucchini-nlp @molbap +/src/transformers/models/perceiver/mod*_perceiver* @zucchini-nlp +/src/transformers/models/pix2struct/mod*_pix2struct* @zucchini-nlp +/src/transformers/models/pixtral/mod*_pixtral* @zucchini-nlp @ArthurZucker +/src/transformers/models/qwen2_audio/mod*_qwen2_audio* @zucchini-nlp @ArthurZucker +/src/transformers/models/qwen2_vl/mod*_qwen2_vl* @zucchini-nlp @ArthurZucker +/src/transformers/models/sam/mod*_sam* @zucchini-nlp @ArthurZucker +/src/transformers/models/siglip/mod*_siglip* @zucchini-nlp +/src/transformers/models/speech_encoder_decoder/mod*_speech_encoder_decoder* @zucchini-nlp +/src/transformers/models/tapas/mod*_tapas* @NielsRogge +/src/transformers/models/trocr/mod*_trocr* @zucchini-nlp +/src/transformers/models/tvlt/mod*_tvlt* @zucchini-nlp +/src/transformers/models/tvp/mod*_tvp* @zucchini-nlp +/src/transformers/models/udop/mod*_udop* @zucchini-nlp +/src/transformers/models/video_llava/mod*_video_llava* @zucchini-nlp +/src/transformers/models/vilt/mod*_vilt* @zucchini-nlp +/src/transformers/models/vipllava/mod*_vipllava* @zucchini-nlp +/src/transformers/models/vision_encoder_decoder/mod*_vision_encoder_decoder* @Rocketknight1 +/src/transformers/models/vision_text_dual_encoder/mod*_vision_text_dual_encoder* @Rocketknight1 +/src/transformers/models/visual_bert/mod*_visual_bert* @zucchini-nlp +/src/transformers/models/xclip/mod*_xclip* @zucchini-nlp + +# Reinforcement learning models +/src/transformers/models/decision_transformer/mod*_decision_transformer* @Rocketknight1 +/src/transformers/models/trajectory_transformer/mod*_trajectory_transformer* @Rocketknight1 + +# Time series models +/src/transformers/models/autoformer/mod*_autoformer* @Rocketknight1 +/src/transformers/models/informer/mod*_informer* @Rocketknight1 +/src/transformers/models/patchtsmixer/mod*_patchtsmixer* @Rocketknight1 +/src/transformers/models/patchtst/mod*_patchtst* @Rocketknight1 +/src/transformers/models/time_series_transformer/mod*_time_series_transformer* @Rocketknight1 + +# Graph models +/src/transformers/models/graphormer/mod*_graphormer* @clefourrier + +# Finally, files with no owners that shouldn't generate pings, usually automatically generated and checked in the CI +utils/dummy* \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/TROUBLESHOOT.md b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/TROUBLESHOOT.md new file mode 100644 index 0000000000000000000000000000000000000000..f6101e6d70b59af8ef1878c1461c914090f9fa22 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/TROUBLESHOOT.md @@ -0,0 +1,9 @@ +# Troubleshooting + +This is a document explaining how to deal with various issues on github-actions self-hosted CI. The entries may include actual solutions or pointers to Issues that cover those. + +## GitHub Actions (self-hosted CI) + +* Deepspeed + + - if jit build hangs, clear out `rm -rf ~/.cache/torch_extensions/` reference: https://github.com/huggingface/transformers/pull/12723 diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/add-model-like.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/add-model-like.yml new file mode 100644 index 0000000000000000000000000000000000000000..cd6768317844065146ed425701f59cb87aec61bf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/add-model-like.yml @@ -0,0 +1,80 @@ +name: Add model like runner + +on: + push: + branches: + - none # put main here when this is fixed + #pull_request: + # paths: + # - "src/**" + # - "tests/**" + # - ".github/**" + # types: [opened, synchronize, reopened] + +jobs: + run_tests_templates_like: + name: "Add new model like template tests" + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt -y update && sudo apt install -y libsndfile1-dev + + - name: Load cached virtual environment + uses: actions/cache@v4 + id: cache + with: + path: ~/venv/ + key: v4-tests_model_like-${{ hashFiles('setup.py') }} + + - name: Create virtual environment on cache miss + if: steps.cache.outputs.cache-hit != 'true' + run: | + python -m venv ~/venv && . ~/venv/bin/activate + pip install --upgrade pip!=21.3 + pip install -e .[dev] + + - name: Check transformers location + # make `transformers` available as package (required since we use `-e` flag) and check it's indeed from the repo. + run: | + . ~/venv/bin/activate + python setup.py develop + transformers_install=$(pip list -e | grep transformers) + transformers_install_array=($transformers_install) + transformers_loc=${transformers_install_array[-1]} + transformers_repo_loc=$(pwd .) + if [ "$transformers_loc" != "$transformers_repo_loc" ]; then + echo "transformers is from $transformers_loc but it shoud be from $transformers_repo_loc/src." + echo "A fix is required. Stop testing." + exit 1 + fi + + - name: Create model files + run: | + . ~/venv/bin/activate + transformers-cli add-new-model-like --config_file tests/fixtures/add_distilbert_like_config.json --path_to_repo . + make style + make fix-copies + + - name: Run all PyTorch modeling test + run: | + . ~/venv/bin/activate + python -m pytest -n 2 --dist=loadfile -s --make-reports=tests_new_models tests/bert_new/test_modeling_bert_new.py + + - name: Run style changes + run: | + . ~/venv/bin/activate + make style && make quality && make repo-consistency + + - name: Failure short reports + if: ${{ always() }} + run: cat reports/tests_new_models/failures_short.txt + + - name: Test suite reports artifacts + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: run_all_tests_new_models_test_reports + path: reports/tests_new_models diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/assign-reviewers.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/assign-reviewers.yml new file mode 100644 index 0000000000000000000000000000000000000000..46bcb52a169f5fb7368395ee626b3c6dbdd6ec25 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/assign-reviewers.yml @@ -0,0 +1,26 @@ +name: Assign PR Reviewers +on: + pull_request_target: + branches: + - main + types: [ready_for_review] + +jobs: + assign_reviewers: + permissions: + pull-requests: write + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.13' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install PyGithub + - name: Run assignment script + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: python .github/scripts/assign_reviewers.py \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/benchmark.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/benchmark.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b5555097c097bdc8940e31b438263e8e8af4377 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/benchmark.yml @@ -0,0 +1,76 @@ +name: Self-hosted runner (benchmark) + +on: + push: + branches: [main] + pull_request: + types: [ opened, labeled, reopened, synchronize ] + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +env: + HF_HOME: /mnt/cache + +jobs: + benchmark: + name: Benchmark + strategy: + matrix: + # group: [aws-g5-4xlarge-cache, aws-p4d-24xlarge-plus] (A100 runner is not enabled) + group: [aws-g5-4xlarge-cache] + runs-on: + group: ${{ matrix.group }} + if: | + (github.event_name == 'pull_request' && contains( github.event.pull_request.labels.*.name, 'run-benchmark') )|| + (github.event_name == 'push' && github.ref == 'refs/heads/main') + container: + image: huggingface/transformers-pytorch-gpu + options: --gpus all --privileged --ipc host + steps: + - name: Get repo + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + - name: Install libpq-dev & psql + run: | + apt update + apt install -y libpq-dev postgresql-client + + - name: Install benchmark script dependencies + run: python3 -m pip install -r benchmark/requirements.txt + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e ".[torch]" + + - name: Run database init script + run: | + psql -f benchmark/init_db.sql + env: + PGDATABASE: metrics + PGHOST: ${{ secrets.TRANSFORMERS_BENCHMARKS_PGHOST }} + PGUSER: transformers_benchmarks + PGPASSWORD: ${{ secrets.TRANSFORMERS_BENCHMARKS_PGPASSWORD }} + + - name: Run benchmark + run: | + git config --global --add safe.directory /__w/transformers/transformers + if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then + commit_id=$(echo "${{ github.event.pull_request.head.sha }}") + elif [ "$GITHUB_EVENT_NAME" = "push" ]; then + commit_id=$GITHUB_SHA + fi + commit_msg=$(git show -s --format=%s | cut -c1-70) + python3 benchmark/benchmarks_entrypoint.py "$BRANCH_NAME" "$commit_id" "$commit_msg" + env: + HF_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + # Enable this to see debug logs + # HF_HUB_VERBOSITY: debug + # TRANSFORMERS_VERBOSITY: debug + PGHOST: ${{ secrets.TRANSFORMERS_BENCHMARKS_PGHOST }} + PGUSER: transformers_benchmarks + PGPASSWORD: ${{ secrets.TRANSFORMERS_BENCHMARKS_PGPASSWORD }} + BRANCH_NAME: ${{ github.head_ref || github.ref_name }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-ci-docker-images.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-ci-docker-images.yml new file mode 100644 index 0000000000000000000000000000000000000000..5606668531da95a9839921e7a79be0f81d2191a3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-ci-docker-images.yml @@ -0,0 +1,77 @@ +name: Build pr ci-docker + +on: + push: + branches: + - push-ci-image # for now let's only build on this branch + repository_dispatch: + workflow_call: + inputs: + image_postfix: + required: true + type: string + schedule: + - cron: "6 0 * * *" + + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-22.04 + + if: ${{ contains(github.event.head_commit.message, '[build-ci-image]') || contains(github.event.head_commit.message, '[push-ci-image]') && '!cancelled()' || github.event_name == 'schedule' }} + + strategy: + matrix: + file: ["quality", "consistency", "custom-tokenizers", "torch-light", "tf-light", "exotic-models", "torch-tf-light", "jax-light", "examples-torch", "examples-tf"] + continue-on-error: true + + steps: + - + name: Set tag + run: | + if ${{contains(github.event.head_commit.message, '[build-ci-image]')}}; then + echo "TAG=huggingface/transformers-${{ matrix.file }}:dev" >> "$GITHUB_ENV" + echo "setting it to DEV!" + else + echo "TAG=huggingface/transformers-${{ matrix.file }}" >> "$GITHUB_ENV" + + fi + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build ${{ matrix.file }}.dockerfile + uses: docker/build-push-action@v5 + with: + context: ./docker + build-args: | + REF=${{ github.sha }} + file: "./docker/${{ matrix.file }}.dockerfile" + push: ${{ contains(github.event.head_commit.message, 'ci-image]') || github.event_name == 'schedule' }} + tags: ${{ env.TAG }} + + notify: + runs-on: ubuntu-22.04 + if: ${{ contains(github.event.head_commit.message, '[build-ci-image]') || contains(github.event.head_commit.message, '[push-ci-image]') && '!cancelled()' || github.event_name == 'schedule' }} + steps: + - name: Post to Slack + if: ${{ contains(github.event.head_commit.message, '[push-ci-image]') && github.event_name != 'schedule' }} + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: "#transformers-ci-circleci-images" + title: 🤗 New docker images for CircleCI are pushed. + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-docker-images.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-docker-images.yml new file mode 100644 index 0000000000000000000000000000000000000000..c21faf2d7479426bd7c995e018cef935446ba3be --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-docker-images.yml @@ -0,0 +1,393 @@ +name: Build docker images (scheduled) + +on: + push: + branches: + - build_ci_docker_image* + repository_dispatch: + workflow_call: + inputs: + image_postfix: + required: true + type: string + schedule: + - cron: "17 0 * * *" + +concurrency: + group: docker-images-builds + cancel-in-progress: false + +jobs: + latest-docker: + name: "Latest PyTorch + TensorFlow [dev]" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-all-latest-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-all-latest-gpu${{ inputs.image_postfix }} + # Push CI images still need to be re-built daily + - + name: Build and push (for Push CI) in a daily basis + # This condition allows `schedule` events, or `push` events that trigger this workflow NOT via `workflow_call`. + # The later case is useful for manual image building for debugging purpose. Use another tag in this case! + if: inputs.image_postfix != '-push-ci' + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-all-latest-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-all-latest-gpu-push-ci + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the transformers-all-latest-gpu-push-ci docker build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-torch-deepspeed-docker: + name: "Latest PyTorch + DeepSpeed" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-deepspeed-latest-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-deepspeed-latest-gpu${{ inputs.image_postfix }} + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER}} + title: 🤗 Results of the transformers-pytorch-deepspeed-latest-gpu docker build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + # Can't build 2 images in a single job `latest-torch-deepspeed-docker` (for `nvcr.io/nvidia`) + latest-torch-deepspeed-docker-for-push-ci-daily-build: + name: "Latest PyTorch + DeepSpeed (Push CI - Daily Build)" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + # Push CI images still need to be re-built daily + - + name: Build and push (for Push CI) in a daily basis + # This condition allows `schedule` events, or `push` events that trigger this workflow NOT via `workflow_call`. + # The later case is useful for manual image building for debugging purpose. Use another tag in this case! + if: inputs.image_postfix != '-push-ci' + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-deepspeed-latest-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-deepspeed-latest-gpu-push-ci + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the transformers-pytorch-deepspeed-latest-gpu-push-ci docker build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + doc-builder: + name: "Doc builder" + # Push CI doesn't need this image + if: inputs.image_postfix != '-push-ci' + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-doc-builder + push: true + tags: huggingface/transformers-doc-builder + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the huggingface/transformers-doc-builder docker build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-pytorch: + name: "Latest PyTorch [dev]" + # Push CI doesn't need this image + if: inputs.image_postfix != '-push-ci' + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-gpu + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the huggingface/transformers-pytorch-gpudocker build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-pytorch-amd: + name: "Latest PyTorch (AMD) [dev]" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-amd-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-amd-gpu${{ inputs.image_postfix }} + # Push CI images still need to be re-built daily + - + name: Build and push (for Push CI) in a daily basis + # This condition allows `schedule` events, or `push` events that trigger this workflow NOT via `workflow_call`. + # The later case is useful for manual image building for debugging purpose. Use another tag in this case! + if: inputs.image_postfix != '-push-ci' + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-amd-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-amd-gpu-push-ci + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the huggingface/transformers-pytorch-amd-gpu-push-ci build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-tensorflow: + name: "Latest TensorFlow [dev]" + # Push CI doesn't need this image + if: inputs.image_postfix != '-push-ci' + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-tensorflow-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-tensorflow-gpu + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the huggingface/transformers-tensorflow-gpu build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-pytorch-deepspeed-amd: + name: "PyTorch + DeepSpeed (AMD) [dev]" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-deepspeed-amd-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-deepspeed-amd-gpu${{ inputs.image_postfix }} + # Push CI images still need to be re-built daily + - + name: Build and push (for Push CI) in a daily basis + # This condition allows `schedule` events, or `push` events that trigger this workflow NOT via `workflow_call`. + # The later case is useful for manual image building for debugging purpose. Use another tag in this case! + if: inputs.image_postfix != '-push-ci' + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-pytorch-deepspeed-amd-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-deepspeed-amd-gpu-push-ci + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the transformers-pytorch-deepspeed-amd-gpu build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + latest-quantization-torch-docker: + name: "Latest Pytorch + Quantization [dev]" + # Push CI doesn't need this image + if: inputs.image_postfix != '-push-ci' + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: ./docker/transformers-quantization-latest-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-quantization-latest-gpu${{ inputs.image_postfix }} + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ secrets.CI_SLACK_CHANNEL_DOCKER }} + title: 🤗 Results of the transformers-quantization-latest-gpu build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-nightly-ci-docker-images.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-nightly-ci-docker-images.yml new file mode 100644 index 0000000000000000000000000000000000000000..4b00a6d3fae36639fd2bf3a14b5517fdac0d1665 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-nightly-ci-docker-images.yml @@ -0,0 +1,67 @@ +name: Build docker images (Nightly CI) + +on: + workflow_call: + push: + branches: + - build_nightly_ci_docker_image* + +concurrency: + group: docker-images-builds + cancel-in-progress: false + +jobs: + latest-with-torch-nightly-docker: + name: "Nightly PyTorch + Stable TensorFlow" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v3 + with: + context: ./docker/transformers-all-latest-gpu + build-args: | + REF=main + PYTORCH=pre + push: true + tags: huggingface/transformers-all-latest-torch-nightly-gpu + + nightly-torch-deepspeed-docker: + name: "Nightly PyTorch + DeepSpeed" + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - + name: Check out code + uses: actions/checkout@v4 + - + name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v3 + with: + context: ./docker/transformers-pytorch-deepspeed-nightly-gpu + build-args: | + REF=main + push: true + tags: huggingface/transformers-pytorch-deepspeed-nightly-gpu diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-past-ci-docker-images.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-past-ci-docker-images.yml new file mode 100644 index 0000000000000000000000000000000000000000..c4f0b78986caea24724dfa38465b1e27b88be335 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build-past-ci-docker-images.yml @@ -0,0 +1,101 @@ +name: Build docker images (Past CI) + +on: + push: + branches: + - build_past_ci_docker_image* + +concurrency: + group: docker-images-builds + cancel-in-progress: false + +jobs: + past-pytorch-docker: + name: "Past PyTorch Docker" + strategy: + fail-fast: false + matrix: + version: ["1.13", "1.12", "1.11"] + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - + name: Check out code + uses: actions/checkout@v4 + - + id: get-base-image + name: Get Base Image + env: + framework_version: ${{ matrix.version }} + run: | + echo "base_image=$(python3 -c 'import os; from utils.past_ci_versions import past_versions_testing; base_image = past_versions_testing["pytorch"][os.environ["framework_version"]]["base_image"]; print(base_image)')" >> $GITHUB_OUTPUT + - + name: Print Base Image + run: | + echo ${{ steps.get-base-image.outputs.base_image }} + - + name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v3 + with: + context: ./docker/transformers-past-gpu + build-args: | + REF=main + BASE_DOCKER_IMAGE=${{ steps.get-base-image.outputs.base_image }} + FRAMEWORK=pytorch + VERSION=${{ matrix.version }} + push: true + tags: huggingface/transformers-pytorch-past-${{ matrix.version }}-gpu + + past-tensorflow-docker: + name: "Past TensorFlow Docker" + strategy: + fail-fast: false + matrix: + version: ["2.11", "2.10", "2.9", "2.8", "2.7", "2.6", "2.5"] + runs-on: + group: aws-general-8-plus + steps: + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - + name: Check out code + uses: actions/checkout@v4 + - + id: get-base-image + name: Get Base Image + env: + framework_version: ${{ matrix.version }} + run: | + echo "base_image=$(python3 -c 'import os; from utils.past_ci_versions import past_versions_testing; base_image = past_versions_testing["tensorflow"][os.environ["framework_version"]]["base_image"]; print(base_image)')" >> $GITHUB_OUTPUT + - + name: Print Base Image + run: | + echo ${{ steps.get-base-image.outputs.base_image }} + - + name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - + name: Build and push + uses: docker/build-push-action@v3 + with: + context: ./docker/transformers-past-gpu + build-args: | + REF=main + BASE_DOCKER_IMAGE=${{ steps.get-base-image.outputs.base_image }} + FRAMEWORK=tensorflow + VERSION=${{ matrix.version }} + push: true + tags: huggingface/transformers-tensorflow-past-${{ matrix.version }}-gpu diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_documentation.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..c55638ded1497c574639d8f352dbe1ed303a06fb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_documentation.yml @@ -0,0 +1,23 @@ +name: Build documentation + +on: + workflow_dispatch: + push: + branches: + - main + - doc-builder* + - v*-release + - use_templates + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main + with: + commit_sha: ${{ github.sha }} + package: transformers + notebook_folder: transformers_doc + languages: ar de en es fr hi it ko pt tr zh ja te + custom_container: huggingface/transformers-doc-builder + secrets: + token: ${{ secrets.HUGGINGFACE_PUSH }} + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_pr_documentation.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..f698f860b2f93c64a8b4d5c9dfeace0133c99eed --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,18 @@ +name: Build PR Documentation + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: transformers + languages: ar de en es fr hi it ko pt tr zh ja te + custom_container: huggingface/transformers-doc-builder diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/change_pr_to_draft.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/change_pr_to_draft.yml new file mode 100644 index 0000000000000000000000000000000000000000..f44a0cf1420feb94f29043504392a29254f077d3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/change_pr_to_draft.yml @@ -0,0 +1,25 @@ +name: Change PR to draft + +on: + pull_request_target: + types: [opened, reopened] + +jobs: + convert_pr_to_draft: + runs-on: ubuntu-22.04 + name: Convert PR to draft + permissions: + pull-requests: write + contents: write + if: github.event.pull_request.draft == false + steps: + - name: Convert PR to draft + shell: bash + env: + PR_NUMBER: ${{ github.event.number }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + run: | + echo $PR_NUMBER + gh pr ready $PR_NUMBER --repo $REPO --undo + gh pr comment $PR_NUMBER --repo $REPO --body "Hi 👋, thank you for opening this pull request! The pull request is converted to draft by default. When it is ready for review, please click the \`Ready for review\` button (at the bottom of the PR page)." diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_failed_model_tests.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_failed_model_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..5963523fd76c9d5476d034ffe698c87491dc71e1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_failed_model_tests.yml @@ -0,0 +1,128 @@ +name: Process failed tests + +on: + workflow_call: + inputs: + docker: + required: true + type: string + start_sha: + required: true + type: string + + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes + # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. + # This token is created under the bot `hf-transformers-bot`. + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + + +jobs: + run_models_gpu: + name: " " + runs-on: + group: aws-g4dn-2xlarge-cache + container: + image: ${{ inputs.docker }} + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - uses: actions/download-artifact@v4 + with: + name: ci_results_run_models_gpu + path: /transformers/ci_results_run_models_gpu + + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Get target commit + working-directory: /transformers/utils + run: | + echo "END_SHA=$(TOKEN=${{ secrets.ACCESS_REPO_INFO_TOKEN }} python3 -c 'import os; from get_previous_daily_ci import get_last_daily_ci_run_commit; commit=get_last_daily_ci_run_commit(token=os.environ["TOKEN"]); print(commit)')" >> $GITHUB_ENV + + - name: Checkout to `start_sha` + working-directory: /transformers + run: git fetch && git checkout ${{ inputs.start_sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Check failed tests + working-directory: /transformers + run: python3 utils/check_bad_commit.py --start_commit ${{ inputs.start_sha }} --end_commit ${{ env.END_SHA }} --file ci_results_run_models_gpu/new_model_failures.json --output_file new_model_failures_with_bad_commit.json + + - name: Show results + working-directory: /transformers + run: | + ls -l new_model_failures_with_bad_commit.json + cat new_model_failures_with_bad_commit.json + + - name: Checkout back + working-directory: /transformers + run: | + git checkout ${{ inputs.start_sha }} + + - name: Process report + shell: bash + working-directory: /transformers + env: + TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN: ${{ secrets.TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN }} + run: | + python3 utils/process_bad_commit_report.py + + - name: Process report + shell: bash + working-directory: /transformers + env: + TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN: ${{ secrets.TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN }} + run: | + { + echo 'REPORT_TEXT<> "$GITHUB_ENV" + + - name: Send processed report + if: ${{ !endsWith(env.REPORT_TEXT, '{}') }} + uses: slackapi/slack-github-action@6c661ce58804a1a20f6dc5fbee7f0381b469e001 + with: + # Slack channel id, channel name, or user id to post message. + # See also: https://api.slack.com/methods/chat.postMessage#channels + channel-id: '#transformers-ci-feedback-tests' + # For posting a rich message using Block Kit + payload: | + { + "blocks": [ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "${{ env.REPORT_TEXT }}" + } + } + ] + } + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_tiny_models.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_tiny_models.yml new file mode 100644 index 0000000000000000000000000000000000000000..a2b4846051a05460d62a86cdc45d59b1fa323487 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/check_tiny_models.yml @@ -0,0 +1,82 @@ +name: Check Tiny Models + +on: + push: + branches: + - check_tiny_models* + repository_dispatch: + schedule: + - cron: "0 2 * * *" + +env: + TOKEN: ${{ secrets.TRANSFORMERS_HUB_BOT_HF_TOKEN }} + +jobs: + check_tiny_models: + name: Check tiny models + runs-on: ubuntu-22.04 + steps: + - name: Checkout transformers + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - uses: actions/checkout@v4 + - name: Set up Python 3.8 + uses: actions/setup-python@v5 + with: + # Semantic version range syntax or exact version of a Python version + python-version: '3.8' + # Optional - x64 or x86 architecture, defaults to x64 + architecture: 'x64' + + - name: Install + run: | + sudo apt-get -y update && sudo apt-get install -y libsndfile1-dev espeak-ng cmake + pip install --upgrade pip + python -m pip install -U .[sklearn,torch,testing,sentencepiece,torch-speech,vision,timm,video,tf-cpu] + pip install tensorflow_probability + python -m pip install -U 'natten<0.15.0' + + - name: Create all tiny models (locally) + run: | + python utils/create_dummy_models.py tiny_local_models --all --num_workers 2 + + - name: Local tiny model reports artifacts + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: tiny_local_model_creation_reports + path: tiny_local_models/reports + + # GitHub-hosted runners have 2-core CPUs + - name: Run pipeline tests against all new (local) tiny models + run: | + OMP_NUM_THREADS=1 TRANSFORMERS_TINY_MODEL_PATH=tiny_local_models python -m pytest --max-worker-restart=0 -n 2 --dist=loadfile -s -rA --make-reports=tests_pipelines tests/models -m is_pipeline_test -k "test_pipeline_" | tee tests_output.txt + + - name: Test suite reports artifacts + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: tiny_local_model_creation_reports + path: reports/tests_pipelines + + - name: Create + Upload tiny models for new model architecture(s) + run: | + python utils/update_tiny_models.py --num_workers 2 + + - name: Full report + run: cat tiny_models/reports/tiny_model_creation_report.json + + - name: Failure report + run: cat tiny_models/reports/simple_failed_report.txt + + - name: Summary report + run: cat tiny_models/reports/tiny_model_summary.json + + - name: New tiny model creation reports artifacts + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: tiny_model_creation_reports + path: tiny_models/reports diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctest_job.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctest_job.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb62b797b8eb5575a33a6c0452563d809ce7fce7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctest_job.yml @@ -0,0 +1,83 @@ +name: Doctest job + +on: + workflow_call: + inputs: + job_splits: + required: true + type: string + split_keys: + required: true + type: string + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + RUN_SLOW: yes + OMP_NUM_THREADS: 16 + MKL_NUM_THREADS: 16 + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + +jobs: + run_doctests: + name: " " + strategy: + max-parallel: 8 # 8 jobs at a time + fail-fast: false + matrix: + split_keys: ${{ fromJson(inputs.split_keys) }} + runs-on: + group: aws-g4dn-2xlarge-cache + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e .[flax] + + - name: GPU visibility + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + run: pip freeze + + - name: Get doctest files + working-directory: /transformers + run: | + echo "${{ toJson(fromJson(inputs.job_splits)[matrix.split_keys]) }}" > doc_tests.txt + cat doc_tests.txt + + - name: Set `split_keys` + shell: bash + run: | + echo "${{ matrix.split_keys }}" + split_keys=${{ matrix.split_keys }} + split_keys=${split_keys//'/'/'_'} + echo "split_keys" + echo "split_keys=$split_keys" >> $GITHUB_ENV + + - name: Run doctests + working-directory: /transformers + run: | + cat doc_tests.txt + python3 -m pytest -v --make-reports doc_tests_gpu_${{ env.split_keys }} --doctest-modules $(cat doc_tests.txt) -sv --doctest-continue-on-failure --doctest-glob="*.md" + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/doc_tests_gpu_${{ env.split_keys }}/failures_short.txt + + - name: "Test suite reports artifacts: doc_tests_gpu_test_reports_${{ env.split_keys }}" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: doc_tests_gpu_test_reports_${{ env.split_keys }} + path: /transformers/reports/doc_tests_gpu_${{ env.split_keys }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctests.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctests.yml new file mode 100644 index 0000000000000000000000000000000000000000..472b07684ed12ada716cc5f561665e5947c2f835 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/doctests.yml @@ -0,0 +1,89 @@ +name: Doctests + +on: + push: + branches: + - run_doctest* + repository_dispatch: + schedule: + - cron: "17 2 * * *" + +env: + NUM_SLICES: 3 + +jobs: + setup: + name: Setup + runs-on: + group: aws-g4dn-2xlarge-cache + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + outputs: + job_splits: ${{ steps.set-matrix.outputs.job_splits }} + split_keys: ${{ steps.set-matrix.outputs.split_keys }} + steps: + - name: Update clone + working-directory: /transformers + run: | + git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Check values for matrix + working-directory: /transformers + run: | + python3 utils/split_doctest_jobs.py + python3 utils/split_doctest_jobs.py --only_return_keys --num_splits ${{ env.NUM_SLICES }} + + - id: set-matrix + working-directory: /transformers + name: Set values for matrix + run: | + echo "job_splits=$(python3 utils/split_doctest_jobs.py)" >> $GITHUB_OUTPUT + echo "split_keys=$(python3 utils/split_doctest_jobs.py --only_return_keys --num_splits ${{ env.NUM_SLICES }})" >> $GITHUB_OUTPUT + + call_doctest_job: + name: "Call doctest jobs" + needs: setup + strategy: + max-parallel: 1 # 1 split at a time (in `doctest_job.yml`, we set `8` to run 8 jobs at the same time) + fail-fast: false + matrix: + split_keys: ${{ fromJson(needs.setup.outputs.split_keys) }} + uses: ./.github/workflows/doctest_job.yml + with: + job_splits: ${{ needs.setup.outputs.job_splits }} + split_keys: ${{ toJson(matrix.split_keys) }} + secrets: inherit + + send_results: + name: Send results to webhook + runs-on: ubuntu-22.04 + if: always() + needs: [call_doctest_job] + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + - name: Send message to Slack + env: + CI_SLACK_BOT_TOKEN: ${{ secrets.CI_SLACK_BOT_TOKEN }} + ACCESS_REPO_INFO_TOKEN: ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + # Use `CI_SLACK_CHANNEL_DUMMY_TESTS` when doing experimentation + SLACK_REPORT_CHANNEL: ${{ secrets.CI_SLACK_CHANNEL_ID_DAILY_DOCS }} + run: | + pip install slack_sdk + python utils/notification_service_doc_tests.py + + - name: "Upload results" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: doc_test_results + path: doc_test_results diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs.yml new file mode 100644 index 0000000000000000000000000000000000000000..0997a1112ad7da0b66e1b37314deee4465686a5a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs.yml @@ -0,0 +1,138 @@ +name: model jobs + +on: + workflow_call: + inputs: + folder_slices: + required: true + type: string + machine_type: + required: true + type: string + slice_id: + required: true + type: number + runner: + required: true + type: string + docker: + required: true + type: string + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes + # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. + # This token is created under the bot `hf-transformers-bot`. + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + +jobs: + run_models_gpu: + name: " " + strategy: + max-parallel: 8 + fail-fast: false + matrix: + folders: ${{ fromJson(inputs.folder_slices)[inputs.slice_id] }} + runs-on: + group: '${{ inputs.machine_type }}' + container: + image: ${{ inputs.docker }} + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Echo input and matrix info + shell: bash + run: | + echo "${{ inputs.folder_slices }}" + echo "${{ matrix.folders }}" + echo "${{ toJson(fromJson(inputs.folder_slices)[inputs.slice_id]) }}" + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Update / Install some packages (for Past CI) + if: ${{ contains(inputs.docker, '-past-') }} + working-directory: /transformers + run: | + python3 -m pip install -U datasets + + - name: Update / Install some packages (for Past CI) + if: ${{ contains(inputs.docker, '-past-') && contains(inputs.docker, '-pytorch-') }} + working-directory: /transformers + run: | + python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ inputs.machine_type }}" + + if [ "${{ inputs.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ inputs.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ inputs.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run all tests on GPU + working-directory: /transformers + run: python3 -m pytest -rsfE -v --make-reports=${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports tests/${{ matrix.folders }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: Run test + shell: bash + run: | + mkdir -p /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports + echo "hello" > /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/hello.txt + echo "${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports" + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs_amd.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs_amd.yml new file mode 100644 index 0000000000000000000000000000000000000000..c90181ec6f1b6df86a90f9215ff13e64e7a2f781 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/model_jobs_amd.yml @@ -0,0 +1,128 @@ +name: model jobs + +on: + workflow_call: + inputs: + folder_slices: + required: true + type: string + machine_type: + required: true + type: string + slice_id: + required: true + type: number + runner: + required: true + type: string + docker: + required: true + type: string + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes + # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. + # This token is created under the bot `hf-transformers-bot`. + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + +jobs: + run_models_gpu: + name: " " + strategy: + max-parallel: 1 # For now, not to parallelize. Can change later if it works well. + fail-fast: false + matrix: + folders: ${{ fromJson(inputs.folder_slices)[inputs.slice_id] }} + runs-on: ['${{ inputs.machine_type }}', self-hosted, amd-gpu, '${{ inputs.runner }}'] + container: + image: ${{ inputs.docker }} + options: --device /dev/kfd --device /dev/dri --env ROCR_VISIBLE_DEVICES --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Echo input and matrix info + shell: bash + run: | + echo "${{ inputs.folder_slices }}" + echo "${{ matrix.folders }}" + echo "${{ toJson(fromJson(inputs.folder_slices)[inputs.slice_id]) }}" + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Update / Install some packages (for Past CI) + if: ${{ contains(inputs.docker, '-past-') }} + working-directory: /transformers + run: | + python3 -m pip install -U datasets + + - name: Update / Install some packages (for Past CI) + if: ${{ contains(inputs.docker, '-past-') && contains(inputs.docker, '-pytorch-') }} + working-directory: /transformers + run: | + python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + + - name: ROCM-SMI + run: | + rocm-smi + + - name: ROCM-INFO + run: | + rocminfo | grep "Agent" -A 14 + + - name: Show ROCR environment + run: | + echo "ROCR: $ROCR_VISIBLE_DEVICES" + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run all tests on GPU + working-directory: /transformers + run: python3 -m pytest -rsfE -v --make-reports=${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports tests/${{ matrix.folders }} -m "not not_device_test" + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: Run test + shell: bash + run: | + mkdir -p /transformers/reports/${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports + echo "hello" > /transformers/reports/${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/hello.txt + echo "${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports" + + - name: "Test suite reports artifacts: ${{ inputs.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ inputs.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/new_model_pr_merged_notification.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/new_model_pr_merged_notification.yml new file mode 100644 index 0000000000000000000000000000000000000000..6282528c0b74cb07c021e7d3420c1221f2b40b38 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/new_model_pr_merged_notification.yml @@ -0,0 +1,68 @@ +# Used to notify core maintainers about new model PR being merged +name: New model PR merged notification + +on: + push: + branches: + - main + paths: + - 'src/transformers/models/*/modeling_*' + +jobs: + notify_new_model: + name: Notify new model + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Check new model + shell: bash + run: | + python -m pip install gitpython + python -c 'from utils.pr_slow_ci_models import get_new_model; new_model = get_new_model(diff_with_last_commit=True); print(new_model)' | tee output.txt + echo "NEW_MODEL=$(tail -n 1 output.txt)" >> $GITHUB_ENV + echo "COMMIT_SHA=$(git log -1 --format=%H)" >> $GITHUB_ENV + + - name: print commit sha + if: ${{ env.NEW_MODEL != ''}} + shell: bash + run: | + echo "$COMMIT_SHA" + + - name: print new model + if: ${{ env.NEW_MODEL != ''}} + shell: bash + run: | + echo "$NEW_MODEL" + + - name: Notify + if: ${{ env.NEW_MODEL != ''}} + uses: slackapi/slack-github-action@6c661ce58804a1a20f6dc5fbee7f0381b469e001 + with: + # Slack channel id, channel name, or user id to post message. + # See also: https://api.slack.com/methods/chat.postMessage#channels + channel-id: transformers-new-model-notification + # For posting a rich message using Block Kit + payload: | + { + "blocks": [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "New model!", + "emoji": true + } + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": " GH_ArthurZucker, GH_lysandrejik, GH_ydshieh" + } + } + ] + } + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/push-important-models.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/push-important-models.yml new file mode 100644 index 0000000000000000000000000000000000000000..6a5f5acbce0d2aeb42ed8a304dddf8914e65d55e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/push-important-models.yml @@ -0,0 +1,135 @@ +name: Slow tests on important models (on Push - A10) + +on: + push: + branches: [ main ] + +env: + OUTPUT_SLACK_CHANNEL_ID: "C06L2SGMEEA" + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. # This token is created under the bot `hf-transformers-bot`. + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + +jobs: + get_modified_models: + name: "Get all modified files" + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.set-matrix.outputs.matrix }} + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@3f54ebb830831fc121d3263c1857cfbdc310cdb9 #v42 + with: + files: src/transformers/models/** + + - name: Run step if only the files listed above change + if: steps.changed-files.outputs.any_changed == 'true' + id: set-matrix + env: + ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }} + run: | + model_arrays=() + for file in $ALL_CHANGED_FILES; do + model_path="${file#*models/}" + model_path="models/${model_path%%/*}" + if grep -qFx "$model_path" utils/important_models.txt; then + # Append the file to the matrix string + model_arrays+=("$model_path") + fi + done + matrix_string=$(printf '"%s", ' "${model_arrays[@]}" | sed 's/, $//') + echo "matrix=[$matrix_string]" >> $GITHUB_OUTPUT + test_modified_files: + needs: get_modified_models + name: Slow & FA2 tests + runs-on: + group: aws-g5-4xlarge-cache + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus all --privileged --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + if: ${{ needs.get_modified_models.outputs.matrix != '[]' && needs.get_modified_models.outputs.matrix != '' && fromJson(needs.get_modified_models.outputs.matrix)[0] != null }} + strategy: + fail-fast: false + matrix: + model-name: ${{ fromJson(needs.get_modified_models.outputs.matrix) }} + + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Install locally transformers & other libs + run: | + apt install sudo + sudo -H pip install --upgrade pip + sudo -H pip uninstall -y transformers + sudo -H pip install -U -e ".[testing]" + MAX_JOBS=4 pip install flash-attn --no-build-isolation + pip install bitsandbytes + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Show installed libraries and their versions + run: pip freeze + + - name: Run FA2 tests + id: run_fa2_tests + run: + pytest -rsfE -m "flash_attn_test" --make-reports=${{ matrix.model-name }}_fa2_tests/ tests/${{ matrix.model-name }}/test_modeling_* + + - name: "Test suite reports artifacts: ${{ matrix.model-name }}_fa2_tests" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.model-name }}_fa2_tests + path: /transformers/reports/${{ matrix.model-name }}_fa2_tests + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.OUTPUT_SLACK_CHANNEL_ID }} + title: 🤗 Results of the FA2 tests - ${{ matrix.model-name }} + status: ${{ steps.run_fa2_tests.conclusion}} + slack_token: ${{ secrets.CI_SLACK_BOT_TOKEN }} + + - name: Run integration tests + id: run_integration_tests + if: always() + run: + pytest -rsfE -k "IntegrationTest" --make-reports=tests_integration_${{ matrix.model-name }} tests/${{ matrix.model-name }}/test_modeling_* + + - name: "Test suite reports artifacts: tests_integration_${{ matrix.model-name }}" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: tests_integration_${{ matrix.model-name }} + path: /transformers/reports/tests_integration_${{ matrix.model-name }} + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.OUTPUT_SLACK_CHANNEL_ID }} + title: 🤗 Results of the Integration tests - ${{ matrix.model-name }} + status: ${{ steps.run_integration_tests.conclusion}} + slack_token: ${{ secrets.CI_SLACK_BOT_TOKEN }} + + - name: Tailscale # In order to be able to SSH when a test fails + if: ${{ runner.debug == '1'}} + uses: huggingface/tailscale-action@v1 + with: + authkey: ${{ secrets.TAILSCALE_SSH_AUTHKEY }} + slackChannel: ${{ secrets.SLACK_CIFEEDBACK_CHANNEL }} + slackToken: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + waitForSSH: true diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/release-conda.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/release-conda.yml new file mode 100644 index 0000000000000000000000000000000000000000..c0e28d7a510d7fae787b7b007ac4235360a5d666 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/release-conda.yml @@ -0,0 +1,47 @@ +name: Release - Conda + +on: + push: + tags: + - v* + branches: + - conda_* + +env: + ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }} + +jobs: + build_and_package: + runs-on: ubuntu-22.04 + defaults: + run: + shell: bash -l {0} + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install miniconda + uses: conda-incubator/setup-miniconda@v2 + with: + auto-update-conda: true + auto-activate-base: false + python-version: 3.8 + activate-environment: "build-transformers" + channels: huggingface + + - name: Setup conda env + run: | + conda install -c defaults anaconda-client conda-build + + - name: Extract version + run: echo "TRANSFORMERS_VERSION=`python setup.py --version`" >> $GITHUB_ENV + + - name: Build conda packages + run: | + conda info + conda list + conda-build .github/conda + + - name: Upload to Anaconda + run: anaconda upload `conda-build .github/conda --output` --force diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-comment-ci.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-comment-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..a3df2ea97c24a9b5c58073e1d8d6ee854dd7fa97 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-comment-ci.yml @@ -0,0 +1,416 @@ +name: PR comment GitHub CI + +on: + issue_comment: + types: + - created + branches-ignore: + - main +concurrency: + group: ${{ github.workflow }}-${{ github.event.issue.number }}-${{ startsWith(github.event.comment.body, 'run-slow') || startsWith(github.event.comment.body, 'run slow') || startsWith(github.event.comment.body, 'run_slow') }} + cancel-in-progress: true +permissions: read-all + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes + # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. + # This token is created under the bot `hf-transformers-bot`. + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + +jobs: + get-pr-number: + runs-on: ubuntu-22.04 + name: Get PR number + # For security: only allow team members to run + if: ${{ github.event.issue.state == 'open' && contains(fromJSON('["ydshieh", "ArthurZucker", "zucchini-nlp", "qubvel", "molbap", "gante", "LysandreJik", "Cyrilvallez", "Rocketknight1", "SunMarc", "muellerzr"]'), github.actor) && (startsWith(github.event.comment.body, 'run-slow') || startsWith(github.event.comment.body, 'run slow') || startsWith(github.event.comment.body, 'run_slow')) }} + outputs: + PR_NUMBER: ${{ steps.set_pr_number.outputs.PR_NUMBER }} + steps: + - name: Get PR number + shell: bash + run: | + if [[ "${{ github.event.issue.number }}" != "" && "${{ github.event.issue.pull_request }}" != "" ]]; then + echo "PR_NUMBER=${{ github.event.issue.number }}" >> $GITHUB_ENV + else + echo "PR_NUMBER=" >> $GITHUB_ENV + fi + + - name: Check PR number + shell: bash + run: | + echo "${{ env.PR_NUMBER }}" + + - name: Set PR number + id: set_pr_number + run: echo "PR_NUMBER=${{ env.PR_NUMBER }}" >> "$GITHUB_OUTPUT" + + get-sha: + runs-on: ubuntu-22.04 + needs: get-pr-number + if: ${{ needs.get-pr-number.outputs.PR_NUMBER != ''}} + outputs: + PR_HEAD_SHA: ${{ steps.get_sha.outputs.PR_HEAD_SHA }} + PR_MERGE_SHA: ${{ steps.get_sha.outputs.PR_MERGE_SHA }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: "0" + ref: "refs/pull/${{needs.get-pr-number.outputs.PR_NUMBER}}/merge" + + - name: Get SHA (and verify timestamps against the issue comment date) + id: get_sha + env: + PR_NUMBER: ${{ needs.get-pr-number.outputs.PR_NUMBER }} + COMMENT_DATE: ${{ github.event.comment.created_at }} + run: | + git fetch origin refs/pull/$PR_NUMBER/head:refs/remotes/pull/$PR_NUMBER/head + git checkout refs/remotes/pull/$PR_NUMBER/head + echo "PR_HEAD_SHA: $(git log -1 --format=%H)" + echo "PR_HEAD_SHA=$(git log -1 --format=%H)" >> "$GITHUB_OUTPUT" + git fetch origin refs/pull/$PR_NUMBER/merge:refs/remotes/pull/$PR_NUMBER/merge + git checkout refs/remotes/pull/$PR_NUMBER/merge + echo "PR_MERGE_SHA: $(git log -1 --format=%H)" + echo "PR_MERGE_SHA=$(git log -1 --format=%H)" >> "$GITHUB_OUTPUT" + PR_MERGE_COMMIT_TIMESTAMP=$(git log -1 --date=unix --format=%cd) + echo "PR_MERGE_COMMIT_TIMESTAMP: $PR_MERGE_COMMIT_TIMESTAMP" + COMMENT_TIMESTAMP=$(date -d "${COMMENT_DATE}" +"%s") + echo "COMMENT_DATE: $COMMENT_DATE" + echo "COMMENT_TIMESTAMP: $COMMENT_TIMESTAMP" + if [ $COMMENT_TIMESTAMP -le $PR_MERGE_COMMIT_TIMESTAMP ]; then + echo "Last commit on the pull request is newer than the issue comment triggering this run! Abort!"; + exit -1; + fi + + # use a python script to handle this complex logic + # case 1: `run-slow` (auto. infer with limited number of models, but in particular, new model) + # case 2: `run-slow model_1, model_2` + get-tests: + runs-on: ubuntu-22.04 + needs: [get-pr-number, get-sha] + if: ${{ needs.get-pr-number.outputs.PR_NUMBER != ''}} + outputs: + models: ${{ steps.models_to_run.outputs.models }} + quantizations: ${{ steps.models_to_run.outputs.quantizations }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: "0" + ref: "refs/pull/${{needs.get-pr-number.outputs.PR_NUMBER}}/merge" + + - name: Verify merge commit SHA + env: + VERIFIED_PR_MERGE_SHA: ${{ needs.get-sha.outputs.PR_MERGE_SHA }} + run: | + PR_MERGE_SHA=$(git log -1 --format=%H) + if [ $PR_MERGE_SHA != $VERIFIED_PR_MERGE_SHA ]; then + echo "The merged commit SHA is not the same as the verified one! Security issue detected, abort the workflow!"; + exit -1; + fi + + - name: Get models to test + env: + PR_COMMENT: ${{ github.event.comment.body }} + run: | + python -m pip install GitPython + python utils/pr_slow_ci_models.py --message "$PR_COMMENT" | tee output.txt + echo "models=$(tail -n 1 output.txt)" >> $GITHUB_ENV + python utils/pr_slow_ci_models.py --message "$PR_COMMENT" --quantization | tee output2.txt + echo "quantizations=$(tail -n 1 output2.txt)" >> $GITHUB_ENV + + - name: Show models to test + id: models_to_run + run: | + echo "${{ env.models }}" + echo "models=${{ env.models }}" >> $GITHUB_ENV + echo "models=${{ env.models }}" >> $GITHUB_OUTPUT + echo "${{ env.quantizations }}" + echo "quantizations=${{ env.quantizations }}" >> $GITHUB_OUTPUT + + reply_to_comment: + name: Reply to the comment + if: ${{ needs.get-tests.outputs.models != '[]' || needs.get-tests.outputs.quantizations != '[]' }} + needs: [get-pr-number, get-tests] + permissions: + pull-requests: write + runs-on: ubuntu-22.04 + steps: + - name: Reply to the comment + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MODELS: ${{ needs.get-tests.outputs.models }} + BODY: "This comment contains run-slow, running the specified jobs:\n\nmodels: ${{ needs.get-tests.outputs.models }}\nquantizations: ${{ needs.get-tests.outputs.quantizations }}" + run: | + gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + repos/${{ github.repository }}/issues/${{ needs.get-pr-number.outputs.PR_NUMBER }}/comments \ + -f "body=This comment contains run-slow, running the specified jobs: ${{ env.BODY }} ..." + + create_run: + name: Create run + if: ${{ needs.get-tests.outputs.models != '[]' || needs.get-tests.outputs.quantizations != '[]' }} + needs: [get-sha, get-tests, reply_to_comment] + permissions: + statuses: write + runs-on: ubuntu-22.04 + steps: + - name: Create Run + id: create_run + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Create a commit status (pending) for a run of this workflow. The status has to be updated later in `update_run_status`. + # See https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28#create-a-commit-status + GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + repos/${{ github.repository }}/statuses/${{ needs.get-sha.outputs.PR_HEAD_SHA }} \ + -f "target_url=$GITHUB_RUN_URL" -f "state=pending" -f "description=Slow CI job" -f "context=pytest/custom-tests" + + run_models_gpu: + name: Run all tests for the model + if: ${{ needs.get-tests.outputs.models != '[]' }} + needs: [get-pr-number, get-sha, get-tests, create_run] + strategy: + fail-fast: false + matrix: + folders: ${{ fromJson(needs.get-tests.outputs.models) }} + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Echo input and matrix info + shell: bash + run: | + echo "${{ matrix.folders }}" + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: Checkout to PR merge commit + working-directory: /transformers + run: | + git fetch origin refs/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge:refs/remotes/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge + git checkout refs/remotes/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge + git log -1 --format=%H + + - name: Verify merge commit SHA + env: + VERIFIED_PR_MERGE_SHA: ${{ needs.get-sha.outputs.PR_MERGE_SHA }} + working-directory: /transformers + run: | + PR_MERGE_SHA=$(git log -1 --format=%H) + if [ $PR_MERGE_SHA != $VERIFIED_PR_MERGE_SHA ]; then + echo "The merged commit SHA is not the same as the verified one! Security issue detected, abort the workflow!"; + exit -1; + fi + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run all tests on GPU + working-directory: /transformers + run: | + export CUDA_VISIBLE_DEVICES="$(python3 utils/set_cuda_devices_for_ci.py --test_folder ${{ matrix.folders }})" + echo $CUDA_VISIBLE_DEVICES + python3 -m pytest -v -rsfE --make-reports=${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports tests/${{ matrix.folders }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: Make sure report directory exists + shell: bash + run: | + mkdir -p /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports + echo "hello" > /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/hello.txt + echo "${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports" + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports + + run_quantization_torch_gpu: + name: Run all tests for a quantization + if: ${{ needs.get-tests.outputs.quantizations != '[]' }} + needs: [get-pr-number, get-sha, get-tests, create_run] + strategy: + fail-fast: false + matrix: + folders: ${{ fromJson(needs.get-tests.outputs.quantizations) }} + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-quantization-latest-gpu + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Echo folder ${{ matrix.folders }} + shell: bash + run: | + echo "${{ matrix.folders }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'quantization/'/'quantization_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: Checkout to PR merge commit + working-directory: /transformers + run: | + git fetch origin refs/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge:refs/remotes/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge + git checkout refs/remotes/pull/${{ needs.get-pr-number.outputs.PR_NUMBER }}/merge + git log -1 --format=%H + + - name: Verify merge commit SHA + env: + VERIFIED_PR_MERGE_SHA: ${{ needs.get-sha.outputs.PR_MERGE_SHA }} + working-directory: /transformers + run: | + PR_MERGE_SHA=$(git log -1 --format=%H) + if [ $PR_MERGE_SHA != $VERIFIED_PR_MERGE_SHA ]; then + echo "The merged commit SHA is not the same as the verified one! Security issue detected, abort the workflow!"; + exit -1; + fi + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run quantization tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -v --make-reports=${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports tests/${{ matrix.folders }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: Make sure report directory exists + shell: bash + run: | + mkdir -p /transformers/reports/${{ env.machine_type }}_run_quantization_gpu_${{ matrix.folders }}_test_reports + echo "hello" > /transformers/reports/${{ env.machine_type }}_run_quantization_gpu_${{ matrix.folders }}_test_reports/hello.txt + echo "${{ env.machine_type }}_run_quantization_gpu_${{ matrix.folders }}_test_reports" + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_quantization_torch_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_quantization_torch_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports + + update_run_status: + name: Update Check Run Status + needs: [get-sha, create_run, run_models_gpu, run_quantization_torch_gpu] + permissions: + statuses: write + if: ${{ always() && needs.create_run.result == 'success' }} + runs-on: ubuntu-22.04 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + STATUS_OK: ${{ contains(fromJSON('["skipped", "success"]'), needs.run_models_gpu.result) && contains(fromJSON('["skipped", "success"]'), needs.run_quantization_torch_gpu.result) }} + steps: + - name: Get `run_models_gpu` job status + run: | + echo "${{ needs.run_models_gpu.result }}" + echo "${{ needs.run_quantization_torch_gpu.result }}" + echo $STATUS_OK + if [ "$STATUS_OK" = "true" ]; then + echo "STATUS=success" >> $GITHUB_ENV + else + echo "STATUS=failure" >> $GITHUB_ENV + fi + + - name: Update PR commit statuses + run: | + echo "${{ needs.run_models_gpu.result }}" + echo "${{ env.STATUS }}" + gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + repos/${{ github.repository }}/statuses/${{ needs.get-sha.outputs.PR_HEAD_SHA }} \ + -f "target_url=$GITHUB_RUN_URL" -f "state=${{ env.STATUS }}" -f "description=Slow CI job" -f "context=pytest/custom-tests" diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..5538e2d56e749091d0b7fdccdf24ed95b39e5a3d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-caller.yml @@ -0,0 +1,43 @@ +name: Self-hosted runner (nightly-ci) + + +on: + repository_dispatch: + schedule: + - cron: "17 2 * * *" + push: + branches: + - run_nightly_ci* + +jobs: + build_nightly_ci_images: + name: Build Nightly CI Docker Images + if: (github.event_name == 'schedule') || ((github.event_name == 'push') && startsWith(github.ref_name, 'run_nightly_ci')) + uses: ./.github/workflows/build-nightly-ci-docker-images.yml + secrets: inherit + + model-ci: + name: Model CI + needs: [build_nightly_ci_images] + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_models_gpu + slack_report_channel: "#transformers-ci-past-future" + runner: ci + docker: huggingface/transformers-all-latest-torch-nightly-gpu + ci_event: Nightly CI + secrets: inherit + + deepspeed-ci: + name: DeepSpeed CI + needs: [build_nightly_ci_images] + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_torch_cuda_extensions_gpu + slack_report_channel: "#transformers-ci-past-future" + runner: ci + # test deepspeed nightly build with the latest release torch + docker: huggingface/transformers-pytorch-deepspeed-latest-gpu + ci_event: Nightly CI + working-directory-prefix: /workspace + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-past-ci-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-past-ci-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..46d811d4a43394a86f256669b69d19cf5d109fab --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-nightly-past-ci-caller.yml @@ -0,0 +1,99 @@ +name: Self-hosted runner (nightly-past-ci-caller) + +on: + schedule: + - cron: "17 2,14 * * *" + push: + branches: + - run_past_ci* + +jobs: + get_number: + name: Get number + runs-on: ubuntu-22.04 + outputs: + run_number: ${{ steps.get_number.outputs.run_number }} + steps: + - name: Get number + id: get_number + run: | + echo "${{ github.run_number }}" + echo "$(python3 -c 'print(int(${{ github.run_number }}) % 10)')" + echo "run_number=$(python3 -c 'print(int(${{ github.run_number }}) % 10)')" >> $GITHUB_OUTPUT + + run_past_ci_tensorflow_2-11: + name: TensorFlow 2.11 + needs: get_number + if: needs.get_number.outputs.run_number == 3 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.11" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-10: + name: TensorFlow 2.10 + needs: get_number + if: needs.get_number.outputs.run_number == 4 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.10" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-9: + name: TensorFlow 2.9 + needs: get_number + if: needs.get_number.outputs.run_number == 5 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.9" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-8: + name: TensorFlow 2.8 + needs: get_number + if: needs.get_number.outputs.run_number == 6 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.8" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-7: + name: TensorFlow 2.7 + needs: get_number + if: needs.get_number.outputs.run_number == 7 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.7" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-6: + name: TensorFlow 2.6 + needs: get_number + if: needs.get_number.outputs.run_number == 8 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.6" + sha: ${{ github.sha }} + secrets: inherit + + run_past_ci_tensorflow_2-5: + name: TensorFlow 2.5 + needs: get_number + if: needs.get_number.outputs.run_number == 9 && (cancelled() != true) && ((github.event_name == 'push') && startsWith(github.ref_name, 'run_past_ci')) + uses: ./.github/workflows/self-past-caller.yml + with: + framework: tensorflow + version: "2.5" + sha: ${{ github.sha }} + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-past-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-past-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..1929a01c34d94726d1e820924933cec1412a02d6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-past-caller.yml @@ -0,0 +1,40 @@ +name: Self-hosted runner (past-ci) + + +on: + workflow_call: + inputs: + framework: + required: true + type: string + version: + required: true + type: string + # Use this to control the commit to test against + sha: + default: 'main' + required: false + type: string + +jobs: + model-ci: + name: Model CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_models_gpu + slack_report_channel: "#transformers-ci-past-future" + runner: past-ci + docker: huggingface/transformers-${{ inputs.framework }}-past-${{ inputs.version }}-gpu + ci_event: Past CI - ${{ inputs.framework }}-${{ inputs.version }} + secrets: inherit + + deepspeed-ci: + name: DeepSpeed CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_torch_cuda_extensions_gpu + slack_report_channel: "#transformers-ci-past-future" + runner: past-ci + docker: huggingface/transformers-${{ inputs.framework }}-past-${{ inputs.version }}-gpu + ci_event: Past CI - ${{ inputs.framework }}-${{ inputs.version }} + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi210-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi210-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..45b325f7b357bf838f2f876bb7f4748ed6204ee2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi210-caller.yml @@ -0,0 +1,25 @@ +name: Self-hosted runner (AMD mi210 CI caller) + +on: + #workflow_run: + # workflows: ["Self-hosted runner (push-caller)"] + # branches: ["main"] + # types: [completed] + push: + branches: + - run_amd_push_ci_caller* + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "templates/**" + - "utils/**" + +jobs: + run_amd_ci: + name: AMD mi210 + if: (cancelled() != true) && ((github.event_name == 'workflow_run') || ((github.event_name == 'push') && startsWith(github.ref_name, 'run_amd_push_ci_caller'))) + uses: ./.github/workflows/self-push-amd.yml + with: + gpu_flavor: mi210 + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi250-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi250-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..91b978b593d0b5b37d2415677a35c8f73c434dac --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi250-caller.yml @@ -0,0 +1,25 @@ +name: Self-hosted runner (AMD mi250 CI caller) + +on: + #workflow_run: + # workflows: ["Self-hosted runner (push-caller)"] + # branches: ["main"] + # types: [completed] + push: + branches: + - run_amd_push_ci_caller* + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "templates/**" + - "utils/**" + +jobs: + run_amd_ci: + name: AMD mi250 + if: (cancelled() != true) && ((github.event_name == 'workflow_run') || ((github.event_name == 'push') && startsWith(github.ref_name, 'run_amd_push_ci_caller'))) + uses: ./.github/workflows/self-push-amd.yml + with: + gpu_flavor: mi250 + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi300-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi300-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..797916125a24fbaf75ae74e87eddbd46a7507154 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd-mi300-caller.yml @@ -0,0 +1,25 @@ +name: Self-hosted runner (AMD mi300 CI caller) + +on: + #workflow_run: + # workflows: ["Self-hosted runner (push-caller)"] + # branches: ["main"] + # types: [completed] + push: + branches: + - run_amd_push_ci_caller* + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "templates/**" + - "utils/**" + +jobs: + run_amd_ci: + name: AMD mi300 + if: (cancelled() != true) && ((github.event_name == 'workflow_run') || ((github.event_name == 'push') && (startsWith(github.ref_name, 'run_amd_push_ci_caller') || startsWith(github.ref_name, 'mi300-ci')))) + uses: ./.github/workflows/self-push-amd.yml + with: + gpu_flavor: mi300 + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd.yml new file mode 100644 index 0000000000000000000000000000000000000000..621061988949d3f57aa47b2a3740603c86800733 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-amd.yml @@ -0,0 +1,334 @@ +name: Self-hosted runner AMD GPU (push) + +on: + workflow_call: + inputs: + gpu_flavor: + required: true + type: string + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + PYTEST_TIMEOUT: 60 + TF_FORCE_GPU_ALLOW_GROWTH: true + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + +jobs: + check_runner_status: + name: Check Runner Status + runs-on: ubuntu-22.04 + steps: + - name: Checkout transformers + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Check Runner Status + run: python utils/check_self_hosted_runner.py --target_runners amd-mi210-single-gpu-ci-runner-docker --token ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + + check_runners: + name: Check Runners + needs: check_runner_status + strategy: + matrix: + machine_type: [single-gpu, multi-gpu] + runs-on: [self-hosted, amd-gpu, '${{ matrix.machine_type }}', '${{ inputs.gpu_flavor }}'] + container: + image: huggingface/transformers-pytorch-amd-gpu-push-ci # <--- We test only for PyTorch for now + options: --device /dev/kfd --device /dev/dri --env ROCR_VISIBLE_DEVICES --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: ROCM-SMI + run: | + rocm-smi + - name: ROCM-INFO + run: | + rocminfo | grep "Agent" -A 14 + - name: Show ROCR environment + run: | + echo "ROCR: $ROCR_VISIBLE_DEVICES" + + setup_gpu: + name: Setup + needs: check_runners + strategy: + matrix: + machine_type: [single-gpu, multi-gpu] + runs-on: [self-hosted, amd-gpu, '${{ matrix.machine_type }}', '${{ inputs.gpu_flavor }}'] + container: + image: huggingface/transformers-pytorch-amd-gpu-push-ci # <--- We test only for PyTorch for now + options: --device /dev/kfd --device /dev/dri --env ROCR_VISIBLE_DEVICES --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + outputs: + matrix: ${{ steps.set-matrix.outputs.matrix }} + test_map: ${{ steps.set-matrix.outputs.test_map }} + env: + # `CI_BRANCH_PUSH`: The branch name from the push event + # `CI_BRANCH_WORKFLOW_RUN`: The name of the branch on which this workflow is triggered by `workflow_run` event + # `CI_SHA_PUSH`: The commit SHA from the push event + # `CI_SHA_WORKFLOW_RUN`: The commit SHA that triggers this workflow by `workflow_run` event + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # `CI_BRANCH`: The non-empty branch name from the above two (one and only one of them is empty) + # `CI_SHA`: The non-empty commit SHA from the above two (one and only one of them is empty) + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Update clone using environment variables + working-directory: /transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Cleanup + working-directory: /transformers + run: | + rm -rf tests/__pycache__ + rm -rf tests/models/__pycache__ + rm -rf reports + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Fetch the tests to run + working-directory: /transformers + # TODO: add `git-python` in the docker images + run: | + pip install --upgrade git-python + python3 utils/tests_fetcher.py --diff_with_last_commit | tee test_preparation.txt + + - name: Report fetched tests + uses: actions/upload-artifact@v4 + with: + name: test_fetched + path: /transformers/test_preparation.txt + + - id: set-matrix + name: Organize tests into models + working-directory: /transformers + # The `keys` is used as GitHub actions matrix for jobs, i.e. `models/bert`, `tokenization`, `pipeline`, etc. + # The `test_map` is used to get the actual identified test files under each key. + # If no test to run (so no `test_map.json` file), create a dummy map (empty matrix will fail) + run: | + if [ -f test_map.json ]; then + keys=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); d = list(test_map.keys()); print(d)') + test_map=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); print(test_map)') + else + keys=$(python3 -c 'keys = ["dummy"]; print(keys)') + test_map=$(python3 -c 'test_map = {"dummy": []}; print(test_map)') + fi + echo $keys + echo $test_map + echo "matrix=$keys" >> $GITHUB_OUTPUT + echo "test_map=$test_map" >> $GITHUB_OUTPUT + + run_models_gpu: + name: Model tests + needs: setup_gpu + # `dummy` means there is no test to run + if: contains(fromJson(needs.setup_gpu.outputs.matrix), 'dummy') != true + strategy: + fail-fast: false + matrix: + folders: ${{ fromJson(needs.setup_gpu.outputs.matrix) }} + machine_type: [single-gpu, multi-gpu] + runs-on: [self-hosted, amd-gpu, '${{ matrix.machine_type }}', '${{ inputs.gpu_flavor }}'] + container: + image: huggingface/transformers-pytorch-amd-gpu-push-ci # <--- We test only for PyTorch for now + options: --device /dev/kfd --device /dev/dri --env ROCR_VISIBLE_DEVICES --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Update clone using environment variables + working-directory: /transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + echo "${{ fromJson(needs.setup_gpu.outputs.test_map)[matrix.folders] }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: ROCM-SMI + run: | + rocm-smi + - name: ROCM-INFO + run: | + rocminfo | grep "Agent" -A 14 + - name: Show ROCR environment + run: | + echo "ROCR: $ROCR_VISIBLE_DEVICES" + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run all non-slow selected tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -n 2 --dist=loadfile -v --make-reports=${{ matrix.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports ${{ fromJson(needs.setup_gpu.outputs.test_map)[matrix.folders] }} -m "not not_device_test" + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ matrix.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ matrix.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.machine_type }}_run_models_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ matrix.machine_type }}_run_models_gpu_${{ matrix.folders }}_test_reports + + send_results: + name: Send results to webhook + runs-on: ubuntu-22.04 + if: always() + needs: [ + check_runner_status, + check_runners, + setup_gpu, + run_models_gpu, +# run_tests_torch_cuda_extensions_single_gpu, +# run_tests_torch_cuda_extensions_multi_gpu + ] + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + - name: Preliminary job status + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + echo "Runner availability: ${{ needs.check_runner_status.result }}" + echo "Setup status: ${{ needs.setup_gpu.result }}" + echo "Runner status: ${{ needs.check_runners.result }}" + + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - uses: actions/checkout@v4 + # To avoid failure when multiple commits are merged into `main` in a short period of time. + # Checking out to an old commit beyond the fetch depth will get an error `fatal: reference is not a tree: ... + # (Only required for `workflow_run` event, where we get the latest HEAD on `main` instead of the event commit) + with: + fetch-depth: 20 + + - name: Update clone using environment variables + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - uses: actions/download-artifact@v4 + - name: Send message to Slack + env: + CI_SLACK_BOT_TOKEN: ${{ secrets.CI_SLACK_BOT_TOKEN }} + CI_SLACK_CHANNEL_ID: ${{ secrets.CI_SLACK_CHANNEL_ID }} + CI_SLACK_CHANNEL_ID_DAILY: ${{ secrets.CI_SLACK_CHANNEL_ID_DAILY }} + CI_SLACK_CHANNEL_ID_AMD: ${{ secrets.CI_SLACK_CHANNEL_ID_AMD }} + CI_SLACK_CHANNEL_DUMMY_TESTS: ${{ secrets.CI_SLACK_CHANNEL_DUMMY_TESTS }} + CI_SLACK_REPORT_CHANNEL_ID: ${{ secrets.CI_SLACK_CHANNEL_ID_AMD }} + ACCESS_REPO_INFO_TOKEN: ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + CI_EVENT: Push CI (AMD) - ${{ inputs.gpu_flavor }} + CI_TITLE_PUSH: ${{ github.event.head_commit.message }} + CI_TITLE_WORKFLOW_RUN: ${{ github.event.workflow_run.head_commit.message }} + CI_SHA: ${{ env.CI_SHA }} + RUNNER_STATUS: ${{ needs.check_runner_status.result }} + RUNNER_ENV_STATUS: ${{ needs.check_runners.result }} + SETUP_STATUS: ${{ needs.setup_gpu.result }} + + # We pass `needs.setup_gpu.outputs.matrix` as the argument. A processing in `notification_service.py` to change + # `models/bert` to `models_bert` is required, as the artifact names use `_` instead of `/`. + run: | + pip install huggingface_hub + pip install slack_sdk + pip show slack_sdk + python utils/notification_service.py "${{ needs.setup_gpu.outputs.matrix }}" diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..59adde4c54e077b4e944f8f6ae578cb6de05f8b4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push-caller.yml @@ -0,0 +1,54 @@ +# Used to trigger self-push CI +name: Self-hosted runner (push-caller) + +on: + push: + branches: + - main + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "templates/**" + - "utils/**" + +jobs: + check-for-setup: + runs-on: ubuntu-22.04 + name: Check if setup was changed + outputs: + changed: ${{ steps.was_changed.outputs.changed }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: "2" + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@v41 + + - name: Was setup changed + id: was_changed + run: | + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + if [ `basename "${file}"` = "setup.py" ]; then + echo "changed=1" >> $GITHUB_OUTPUT + fi + done + + build-docker-containers: + needs: check-for-setup + if: (github.event_name == 'push') && (needs.check-for-setup.outputs.changed == '1') + uses: ./.github/workflows/build-docker-images.yml + with: + image_postfix: "-push-ci" + secrets: inherit + + run_push_ci: + name: Trigger Push CI + runs-on: ubuntu-22.04 + if: ${{ always() }} + needs: build-docker-containers + steps: + - name: Trigger push CI via workflow_run + run: echo "Trigger push CI via workflow_run" \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b3be41e3e9b561b0b038ae4ac74c74d9ca5d4ce --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-push.yml @@ -0,0 +1,652 @@ +name: Self-hosted runner (push) + +on: + workflow_run: + workflows: ["Self-hosted runner (push-caller)"] + branches: ["main"] + types: [completed] + push: + branches: + - ci_* + - ci-* + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "templates/**" + - "utils/**" + repository_dispatch: + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + PYTEST_TIMEOUT: 60 + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + +jobs: + setup: + name: Setup + strategy: + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu-push-ci + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + outputs: + matrix: ${{ steps.set-matrix.outputs.matrix }} + test_map: ${{ steps.set-matrix.outputs.test_map }} + env: + # `CI_BRANCH_PUSH`: The branch name from the push event + # `CI_BRANCH_WORKFLOW_RUN`: The name of the branch on which this workflow is triggered by `workflow_run` event + # `CI_SHA_PUSH`: The commit SHA from the push event + # `CI_SHA_WORKFLOW_RUN`: The commit SHA that triggers this workflow by `workflow_run` event + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # `CI_BRANCH`: The non-empty branch name from the above two (one and only one of them is empty) + # `CI_SHA`: The non-empty commit SHA from the above two (one and only one of them is empty) + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Update clone using environment variables + working-directory: /transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Cleanup + working-directory: /transformers + run: | + rm -rf tests/__pycache__ + rm -rf tests/models/__pycache__ + rm -rf reports + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Fetch the tests to run + working-directory: /transformers + # TODO: add `git-python` in the docker images + run: | + pip install --upgrade git-python + python3 utils/tests_fetcher.py --diff_with_last_commit | tee test_preparation.txt + + - name: Report fetched tests + uses: actions/upload-artifact@v4 + with: + name: test_fetched + path: /transformers/test_preparation.txt + + - id: set-matrix + name: Organize tests into models + working-directory: /transformers + # The `keys` is used as GitHub actions matrix for jobs, i.e. `models/bert`, `tokenization`, `pipeline`, etc. + # The `test_map` is used to get the actual identified test files under each key. + # If no test to run (so no `test_map.json` file), create a dummy map (empty matrix will fail) + run: | + if [ -f test_map.json ]; then + keys=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); d = list(test_map.keys()); print(d)') + test_map=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); print(test_map)') + else + keys=$(python3 -c 'keys = ["dummy"]; print(keys)') + test_map=$(python3 -c 'test_map = {"dummy": []}; print(test_map)') + fi + echo $keys + echo $test_map + echo "matrix=$keys" >> $GITHUB_OUTPUT + echo "test_map=$test_map" >> $GITHUB_OUTPUT + + run_tests_single_gpu: + name: Model tests + needs: setup + # `dummy` means there is no test to run + if: contains(fromJson(needs.setup.outputs.matrix), 'dummy') != true + strategy: + fail-fast: false + matrix: + folders: ${{ fromJson(needs.setup.outputs.matrix) }} + machine_type: [aws-g4dn-2xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu-push-ci + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Update clone using environment variables + working-directory: /transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + echo "${{ fromJson(needs.setup.outputs.test_map)[matrix.folders] }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run all non-slow selected tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -n 2 --dist=loadfile -v --make-reports=${{ env.machine_type }}_tests_gpu_${{ matrix.folders }} ${{ fromJson(needs.setup.outputs.test_map)[matrix.folders] }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_tests_gpu_${{ matrix.folders }}/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_all_tests_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_all_tests_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_tests_gpu_${{ matrix.folders }} + + run_tests_multi_gpu: + name: Model tests + needs: setup + # `dummy` means there is no test to run + if: contains(fromJson(needs.setup.outputs.matrix), 'dummy') != true + strategy: + fail-fast: false + matrix: + folders: ${{ fromJson(needs.setup.outputs.matrix) }} + machine_type: [aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu-push-ci + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Update clone using environment variables + working-directory: /transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Echo folder ${{ matrix.folders }} + shell: bash + # For folders like `models/bert`, set an env. var. (`matrix_folders`) to `models_bert`, which will be used to + # set the artifact folder names (because the character `/` is not allowed). + run: | + echo "${{ matrix.folders }}" + echo "${{ fromJson(needs.setup.outputs.test_map)[matrix.folders] }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'models/'/'models_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Run all non-slow selected tests on GPU + env: + MKL_SERVICE_FORCE_INTEL: 1 + working-directory: /transformers + run: | + python3 -m pytest -n 2 --dist=loadfile -v --make-reports=${{ env.machine_type }}_tests_gpu_${{ matrix.folders }} ${{ fromJson(needs.setup.outputs.test_map)[matrix.folders] }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_tests_gpu_${{ matrix.folders }}/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_all_tests_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_all_tests_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_tests_gpu_${{ matrix.folders }} + + run_tests_torch_cuda_extensions_single_gpu: + name: Torch CUDA extension tests + needs: setup + if: contains(fromJson(needs.setup.outputs.matrix), 'deepspeed') || contains(fromJson(needs.setup.outputs.matrix), 'extended') + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-pytorch-deepspeed-latest-gpu-push-ci + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Set `machine_type` for report and artifact names + working-directory: /workspace/transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Update clone using environment variables + working-directory: /workspace/transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /workspace/transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Remove cached torch extensions + run: rm -rf /github/home/.cache/torch_extensions/ + + # To avoid unknown test failures + - name: Pre build DeepSpeed *again* + working-directory: /workspace + run: | + python3 -m pip uninstall -y deepspeed + DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /workspace/transformers + run: | + python utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /workspace/transformers + run: pip freeze + + - name: Run all non-slow selected tests on GPU + working-directory: /workspace/transformers + # TODO: Here we pass all tests in the 2 folders for simplicity. It's better to pass only the identified tests. + run: | + python -m pytest -n 1 --dist=loadfile -v --make-reports=${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports tests/deepspeed tests/extended + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /workspace/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + path: /workspace/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + + run_tests_torch_cuda_extensions_multi_gpu: + name: Torch CUDA extension tests + needs: setup + if: contains(fromJson(needs.setup.outputs.matrix), 'deepspeed') || contains(fromJson(needs.setup.outputs.matrix), 'extended') + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-pytorch-deepspeed-latest-gpu-push-ci + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - name: Set `machine_type` for report and artifact names + working-directory: /workspace/transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Update clone using environment variables + working-directory: /workspace/transformers + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /workspace/transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Remove cached torch extensions + run: rm -rf /github/home/.cache/torch_extensions/ + + # To avoid unknown test failures + - name: Pre build DeepSpeed *again* + working-directory: /workspace + run: | + python3 -m pip uninstall -y deepspeed + DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /workspace/transformers + run: | + python utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /workspace/transformers + run: pip freeze + + - name: Run all non-slow selected tests on GPU + working-directory: /workspace/transformers + # TODO: Here we pass all tests in the 2 folders for simplicity. It's better to pass only the identified tests. + run: | + python -m pytest -n 1 --dist=loadfile -v --make-reports=${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports tests/deepspeed tests/extended + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /workspace/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + path: /workspace/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + + send_results: + name: Send results to webhook + runs-on: ubuntu-22.04 + if: always() + needs: [ + setup, + run_tests_single_gpu, + run_tests_multi_gpu, + run_tests_torch_cuda_extensions_single_gpu, + run_tests_torch_cuda_extensions_multi_gpu + ] + env: + # For the meaning of these environment variables, see the job `Setup` + CI_BRANCH_PUSH: ${{ github.event.ref }} + CI_BRANCH_WORKFLOW_RUN: ${{ github.event.workflow_run.head_branch }} + CI_SHA_PUSH: ${{ github.event.head_commit.id }} + CI_SHA_WORKFLOW_RUN: ${{ github.event.workflow_run.head_sha }} + steps: + - name: Preliminary job status + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + echo "Setup status: ${{ needs.setup.result }}" + + # Necessary to get the correct branch name and commit SHA for `workflow_run` event + # We also take into account the `push` event (we might want to test some changes in a branch) + - name: Prepare custom environment variables + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + CI_BRANCH_PUSH=${CI_BRANCH_PUSH/'refs/heads/'/''} + echo $CI_BRANCH_PUSH + echo $CI_BRANCH_WORKFLOW_RUN + echo $CI_SHA_PUSH + echo $CI_SHA_WORKFLOW_RUN + [[ ! -z "$CI_BRANCH_PUSH" ]] && echo "CI_BRANCH=$CI_BRANCH_PUSH" >> $GITHUB_ENV || echo "CI_BRANCH=$CI_BRANCH_WORKFLOW_RUN" >> $GITHUB_ENV + [[ ! -z "$CI_SHA_PUSH" ]] && echo "CI_SHA=$CI_SHA_PUSH" >> $GITHUB_ENV || echo "CI_SHA=$CI_SHA_WORKFLOW_RUN" >> $GITHUB_ENV + + - name: print environment variables + run: | + echo "env.CI_BRANCH = ${{ env.CI_BRANCH }}" + echo "env.CI_SHA = ${{ env.CI_SHA }}" + + - uses: actions/checkout@v4 + # To avoid failure when multiple commits are merged into `main` in a short period of time. + # Checking out to an old commit beyond the fetch depth will get an error `fatal: reference is not a tree: ... + # (Only required for `workflow_run` event, where we get the latest HEAD on `main` instead of the event commit) + with: + fetch-depth: 20 + + - name: Update clone using environment variables + run: | + echo "original branch = $(git branch --show-current)" + git fetch && git checkout ${{ env.CI_BRANCH }} + echo "updated branch = $(git branch --show-current)" + git checkout ${{ env.CI_SHA }} + echo "log = $(git log -n 1)" + + - uses: actions/download-artifact@v4 + - name: Send message to Slack + env: + CI_SLACK_BOT_TOKEN: ${{ secrets.CI_SLACK_BOT_TOKEN }} + CI_SLACK_CHANNEL_ID: ${{ secrets.CI_SLACK_CHANNEL_ID }} + CI_SLACK_CHANNEL_ID_DAILY: ${{ secrets.CI_SLACK_CHANNEL_ID_DAILY }} + CI_SLACK_CHANNEL_DUMMY_TESTS: ${{ secrets.CI_SLACK_CHANNEL_DUMMY_TESTS }} + CI_SLACK_REPORT_CHANNEL_ID: ${{ secrets.CI_SLACK_CHANNEL_ID }} + ACCESS_REPO_INFO_TOKEN: ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + CI_EVENT: push + CI_TITLE_PUSH: ${{ github.event.head_commit.message }} + CI_TITLE_WORKFLOW_RUN: ${{ github.event.workflow_run.head_commit.message }} + CI_SHA: ${{ env.CI_SHA }} + SETUP_STATUS: ${{ needs.setup.result }} + + # We pass `needs.setup.outputs.matrix` as the argument. A processing in `notification_service.py` to change + # `models/bert` to `models_bert` is required, as the artifact names use `_` instead of `/`. + run: | + pip install huggingface_hub + pip install slack_sdk + pip show slack_sdk + python utils/notification_service.py "${{ needs.setup.outputs.matrix }}" diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..dc5c7b7e905bd88424452ab95da23af096bffa26 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-caller.yml @@ -0,0 +1,14 @@ +name: Self-hosted runner (AMD scheduled CI caller) + +on: + schedule: + - cron: "17 2 * * *" + +jobs: + run_scheduled_amd_ci: + name: Trigger Scheduled AMD CI + runs-on: ubuntu-22.04 + if: ${{ always() }} + steps: + - name: Trigger scheduled AMD CI via workflow_run + run: echo "Trigger scheduled AMD CI via workflow_run" diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi210-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi210-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..6109faca00932e9a2fdb11c1098aba1d7f7a8a5b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi210-caller.yml @@ -0,0 +1,55 @@ +name: Self-hosted runner (AMD mi210 scheduled CI caller) + +on: + workflow_run: + workflows: ["Self-hosted runner (AMD scheduled CI caller)"] + branches: ["main"] + types: [completed] + push: + branches: + - run_amd_scheduled_ci_caller* + +jobs: + model-ci: + name: Model CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_models_gpu + slack_report_channel: "#transformers-ci-daily-amd" + runner: mi210 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi210 + secrets: inherit + + torch-pipeline: + name: Torch pipeline CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_pipelines_torch_gpu + slack_report_channel: "#transformers-ci-daily-amd" + runner: mi210 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi210 + secrets: inherit + + example-ci: + name: Example CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_examples_gpu + slack_report_channel: "#transformers-ci-daily-amd" + runner: mi210 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi210 + secrets: inherit + + deepspeed-ci: + name: DeepSpeed CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_torch_cuda_extensions_gpu + slack_report_channel: "#transformers-ci-daily-amd" + runner: mi210 + docker: huggingface/transformers-pytorch-deepspeed-amd-gpu + ci_event: Scheduled CI (AMD) - mi210 + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi250-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi250-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..4c6284a78cda8eceda05db5c99f8136e47685883 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-amd-mi250-caller.yml @@ -0,0 +1,55 @@ +name: Self-hosted runner (AMD mi250 scheduled CI caller) + +on: + workflow_run: + workflows: ["Self-hosted runner (AMD scheduled CI caller)"] + branches: ["main"] + types: [completed] + push: + branches: + - run_amd_scheduled_ci_caller* + +jobs: + model-ci: + name: Model CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_models_gpu + slack_report_channel: "#amd-hf-ci" + runner: mi250 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi250 + secrets: inherit + + torch-pipeline: + name: Torch pipeline CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_pipelines_torch_gpu + slack_report_channel: "#amd-hf-ci" + runner: mi250 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi250 + secrets: inherit + + example-ci: + name: Example CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_examples_gpu + slack_report_channel: "#amd-hf-ci" + runner: mi250 + docker: huggingface/transformers-pytorch-amd-gpu + ci_event: Scheduled CI (AMD) - mi250 + secrets: inherit + + deepspeed-ci: + name: DeepSpeed CI + uses: huggingface/hf-workflows/.github/workflows/transformers_amd_ci_scheduled.yaml@main + with: + job: run_torch_cuda_extensions_gpu + slack_report_channel: "#amd-hf-ci" + runner: mi250 + docker: huggingface/transformers-pytorch-deepspeed-amd-gpu + ci_event: Scheduled CI (AMD) - mi250 + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-caller.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-caller.yml new file mode 100644 index 0000000000000000000000000000000000000000..75ea3bb24bc7fa2acda33e001780bafc26bc5f0b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled-caller.yml @@ -0,0 +1,78 @@ +name: Self-hosted runner (scheduled) + + +on: + repository_dispatch: + schedule: + - cron: "17 2 * * *" + push: + branches: + - run_scheduled_ci* + +jobs: + model-ci: + name: Model CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_models_gpu + slack_report_channel: "#transformers-ci-daily-models" + runner: daily-ci + docker: huggingface/transformers-all-latest-gpu + ci_event: Daily CI + secrets: inherit + + torch-pipeline: + name: Torch pipeline CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_pipelines_torch_gpu + slack_report_channel: "#transformers-ci-daily-pipeline-torch" + runner: daily-ci + docker: huggingface/transformers-pytorch-gpu + ci_event: Daily CI + secrets: inherit + + tf-pipeline: + name: TF pipeline CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_pipelines_tf_gpu + slack_report_channel: "#transformers-ci-daily-pipeline-tf" + runner: daily-ci + docker: huggingface/transformers-tensorflow-gpu + ci_event: Daily CI + secrets: inherit + + example-ci: + name: Example CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_examples_gpu + slack_report_channel: "#transformers-ci-daily-examples" + runner: daily-ci + docker: huggingface/transformers-all-latest-gpu + ci_event: Daily CI + secrets: inherit + + deepspeed-ci: + name: DeepSpeed CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_torch_cuda_extensions_gpu + slack_report_channel: "#transformers-ci-daily-deepspeed" + runner: daily-ci + docker: huggingface/transformers-pytorch-deepspeed-latest-gpu + ci_event: Daily CI + working-directory-prefix: /workspace + secrets: inherit + + quantization-ci: + name: Quantization CI + uses: ./.github/workflows/self-scheduled.yml + with: + job: run_quantization_torch_gpu + slack_report_channel: "#transformers-ci-daily-quantization" + runner: daily-ci + docker: huggingface/transformers-quantization-latest-gpu + ci_event: Daily CI + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled.yml new file mode 100644 index 0000000000000000000000000000000000000000..78971820d146de19a345362e8b05c377206a724d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/self-scheduled.yml @@ -0,0 +1,573 @@ +name: Self-hosted runner (scheduled) + +# Note that each job's dependencies go into a corresponding docker file. +# +# For example for `run_torch_cuda_extensions_gpu` the docker image is +# `huggingface/transformers-pytorch-deepspeed-latest-gpu`, which can be found at +# `docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile` + +on: + workflow_call: + inputs: + job: + required: true + type: string + slack_report_channel: + required: true + type: string + runner: + required: true + type: string + docker: + required: true + type: string + ci_event: + required: true + type: string + working-directory-prefix: + default: '' + required: false + type: string + +env: + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes + # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. + # This token is created under the bot `hf-transformers-bot`. + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + NUM_SLICES: 2 + +jobs: + setup: + if: contains(fromJSON('["run_models_gpu", "run_quantization_torch_gpu"]'), inputs.job) + name: Setup + strategy: + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + outputs: + folder_slices: ${{ steps.set-matrix.outputs.folder_slices }} + slice_ids: ${{ steps.set-matrix.outputs.slice_ids }} + quantization_matrix: ${{ steps.set-matrix-quantization.outputs.quantization_matrix }} + steps: + - name: Update clone + working-directory: /transformers + run: | + git fetch && git checkout ${{ github.sha }} + + - name: Cleanup + working-directory: /transformers + run: | + rm -rf tests/__pycache__ + rm -rf tests/models/__pycache__ + rm -rf reports + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - id: set-matrix + if: ${{ inputs.job == 'run_models_gpu' }} + name: Identify models to test + working-directory: /transformers/tests + run: | + echo "folder_slices=$(python3 ../utils/split_model_tests.py --num_splits ${{ env.NUM_SLICES }})" >> $GITHUB_OUTPUT + echo "slice_ids=$(python3 -c 'd = list(range(${{ env.NUM_SLICES }})); print(d)')" >> $GITHUB_OUTPUT + + - id: set-matrix-quantization + if: ${{ inputs.job == 'run_quantization_torch_gpu' }} + name: Identify quantization method to test + working-directory: /transformers/tests + run: | + echo "quantization_matrix=$(python3 -c 'import os; tests = os.getcwd(); quantization_tests = os.listdir(os.path.join(tests, "quantization")); d = sorted(list(filter(os.path.isdir, [f"quantization/{x}" for x in quantization_tests]))) ; print(d)')" >> $GITHUB_OUTPUT + + - name: NVIDIA-SMI + run: | + nvidia-smi + + run_models_gpu: + if: ${{ inputs.job == 'run_models_gpu' }} + name: " " + needs: setup + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + slice_id: ${{ fromJSON(needs.setup.outputs.slice_ids) }} + uses: ./.github/workflows/model_jobs.yml + with: + folder_slices: ${{ needs.setup.outputs.folder_slices }} + machine_type: ${{ matrix.machine_type }} + slice_id: ${{ matrix.slice_id }} + runner: ${{ inputs.runner }} + docker: ${{ inputs.docker }} + secrets: inherit + + run_pipelines_torch_gpu: + if: ${{ inputs.job == 'run_pipelines_torch_gpu' }} + name: PyTorch pipelines + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-pytorch-gpu + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run all pipeline tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -n 1 -v --dist=loadfile --make-reports=${{ env.machine_type }}_run_pipelines_torch_gpu_test_reports tests/pipelines + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_pipelines_torch_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_pipelines_torch_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_pipelines_torch_gpu_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_pipelines_torch_gpu_test_reports + + run_pipelines_tf_gpu: + if: ${{ inputs.job == 'run_pipelines_tf_gpu' }} + name: TensorFlow pipelines + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-tensorflow-gpu + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Update clone + working-directory: /transformers + run: | + git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run all pipeline tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -n 1 -v --dist=loadfile --make-reports=${{ env.machine_type }}_run_pipelines_tf_gpu_test_reports tests/pipelines + + - name: Failure short reports + if: ${{ always() }} + run: | + cat /transformers/reports/${{ env.machine_type }}_run_pipelines_tf_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_pipelines_tf_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_pipelines_tf_gpu_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_pipelines_tf_gpu_test_reports + + run_examples_gpu: + if: ${{ inputs.job == 'run_examples_gpu' }} + name: Examples directory + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-all-latest-gpu + options: --gpus 0 --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run examples tests on GPU + working-directory: /transformers + run: | + pip install -r examples/pytorch/_tests_requirements.txt + python3 -m pytest -v --make-reports=${{ env.machine_type }}_run_examples_gpu_test_reports examples/pytorch + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_examples_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_examples_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_examples_gpu_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_examples_gpu_test_reports + + run_torch_cuda_extensions_gpu: + if: ${{ inputs.job == 'run_torch_cuda_extensions_gpu' }} + name: Torch CUDA extension tests + strategy: + fail-fast: false + matrix: + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: ${{ inputs.docker }} + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Update clone + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: Update / Install some packages (for Past CI) + if: ${{ contains(inputs.docker, '-past-') && contains(inputs.docker, '-pytorch-') }} + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: | + python3 -m pip install -U datasets + python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + + - name: Remove cached torch extensions + run: rm -rf /github/home/.cache/torch_extensions/ + + # To avoid unknown test failures + - name: Pre build DeepSpeed *again* (for daily CI) + if: ${{ contains(inputs.ci_event, 'Daily CI') }} + working-directory: ${{ inputs.working-directory-prefix }}/ + run: | + python3 -m pip uninstall -y deepspeed + DS_DISABLE_NINJA=1 DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check + + # To avoid unknown test failures + - name: Pre build DeepSpeed *again* (for nightly & Past CI) + if: ${{ contains(inputs.ci_event, 'Nightly CI') || contains(inputs.ci_event, 'Past CI') }} + working-directory: ${{ inputs.working-directory-prefix }}/ + run: | + python3 -m pip uninstall -y deepspeed + rm -rf DeepSpeed + git clone https://github.com/deepspeedai/DeepSpeed && cd DeepSpeed && rm -rf build + DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install . --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run all tests on GPU + working-directory: ${{ inputs.working-directory-prefix }}/transformers + run: | + python3 -m pytest -v --make-reports=${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports tests/deepspeed tests/extended + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat ${{ inputs.working-directory-prefix }}/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + path: ${{ inputs.working-directory-prefix }}/transformers/reports/${{ env.machine_type }}_run_torch_cuda_extensions_gpu_test_reports + + run_quantization_torch_gpu: + if: ${{ inputs.job == 'run_quantization_torch_gpu' }} + name: " " + needs: setup + strategy: + max-parallel: 4 + fail-fast: false + matrix: + folders: ${{ fromJson(needs.setup.outputs.quantization_matrix) }} + machine_type: [aws-g4dn-2xlarge-cache, aws-g4dn-12xlarge-cache] + runs-on: + group: '${{ matrix.machine_type }}' + container: + image: huggingface/transformers-quantization-latest-gpu + options: --gpus all --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + steps: + - name: Echo folder ${{ matrix.folders }} + shell: bash + run: | + echo "${{ matrix.folders }}" + matrix_folders=${{ matrix.folders }} + matrix_folders=${matrix_folders/'quantization/'/'quantization_'} + echo "$matrix_folders" + echo "matrix_folders=$matrix_folders" >> $GITHUB_ENV + + - name: Update clone + working-directory: /transformers + run: git fetch && git checkout ${{ github.sha }} + + - name: Reinstall transformers in edit mode (remove the one installed during docker image build) + working-directory: /transformers + run: python3 -m pip uninstall -y transformers && python3 -m pip install -e . + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Environment + working-directory: /transformers + run: | + python3 utils/print_env.py + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: Set `machine_type` for report and artifact names + working-directory: /transformers + shell: bash + run: | + echo "${{ matrix.machine_type }}" + + if [ "${{ matrix.machine_type }}" = "aws-g4dn-2xlarge-cache" ]; then + machine_type=single-gpu + elif [ "${{ matrix.machine_type }}" = "aws-g4dn-12xlarge-cache" ]; then + machine_type=multi-gpu + else + machine_type=${{ matrix.machine_type }} + fi + + echo "$machine_type" + echo "machine_type=$machine_type" >> $GITHUB_ENV + + - name: Run quantization tests on GPU + working-directory: /transformers + run: | + python3 -m pytest -v --make-reports=${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports tests/${{ matrix.folders }} + + - name: Failure short reports + if: ${{ failure() }} + continue-on-error: true + run: cat /transformers/reports/${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports/failures_short.txt + + - name: "Test suite reports artifacts: ${{ env.machine_type }}_run_quantization_torch_gpu_${{ env.matrix_folders }}_test_reports" + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ${{ env.machine_type }}_run_quantization_torch_gpu_${{ env.matrix_folders }}_test_reports + path: /transformers/reports/${{ env.machine_type }}_run_quantization_torch_gpu_${{ matrix.folders }}_test_reports + + run_extract_warnings: + # Let's only do this for the job `run_models_gpu` to simplify the (already complex) logic. + if: ${{ always() && inputs.job == 'run_models_gpu' }} + name: Extract warnings in CI artifacts + runs-on: ubuntu-22.04 + needs: [setup, run_models_gpu] + steps: + - name: Checkout transformers + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Install transformers + run: pip install transformers + + - name: Show installed libraries and their versions + run: pip freeze + + - name: Create output directory + run: mkdir warnings_in_ci + + - uses: actions/download-artifact@v4 + with: + path: warnings_in_ci + + - name: Show artifacts + run: echo "$(python3 -c 'import os; d = os.listdir(); print(d)')" + working-directory: warnings_in_ci + + - name: Extract warnings in CI artifacts + run: | + python3 utils/extract_warnings.py --workflow_run_id ${{ github.run_id }} --output_dir warnings_in_ci --token ${{ secrets.ACCESS_REPO_INFO_TOKEN }} --from_gh + echo "$(python3 -c 'import os; import json; fp = open("warnings_in_ci/selected_warnings.json"); d = json.load(fp); d = "\n".join(d) ;print(d)')" + + - name: Upload artifact + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: warnings_in_ci + path: warnings_in_ci/selected_warnings.json + + send_results: + name: Slack Report + needs: [ + setup, + run_models_gpu, + run_pipelines_torch_gpu, + run_pipelines_tf_gpu, + run_examples_gpu, + run_torch_cuda_extensions_gpu, + run_quantization_torch_gpu, + run_extract_warnings + ] + if: ${{ always() }} + uses: ./.github/workflows/slack-report.yml + with: + job: ${{ inputs.job }} + # This would be `skipped` if `setup` is skipped. + setup_status: ${{ needs.setup.result }} + slack_report_channel: ${{ inputs.slack_report_channel }} + # This would be an empty string if `setup` is skipped. + folder_slices: ${{ needs.setup.outputs.folder_slices }} + quantization_matrix: ${{ needs.setup.outputs.quantization_matrix }} + ci_event: ${{ inputs.ci_event }} + + secrets: inherit + + check_new_model_failures: + if: ${{ always() && inputs.ci_event == 'Daily CI' && inputs.job == 'run_models_gpu' && needs.send_results.result == 'success' }} + name: Check new model failures + needs: send_results + uses: ./.github/workflows/check_failed_model_tests.yml + with: + docker: ${{ inputs.docker }} + start_sha: ${{ github.sha }} + secrets: inherit diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/slack-report.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/slack-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..cbea37ff567a96272cfc5f8d8c4cfd6a8947b87c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/slack-report.yml @@ -0,0 +1,101 @@ +name: CI slack report + +on: + workflow_call: + inputs: + job: + required: true + type: string + slack_report_channel: + required: true + type: string + setup_status: + required: true + type: string + folder_slices: + required: true + type: string + quantization_matrix: + required: true + type: string + ci_event: + required: true + type: string + +env: + TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN: ${{ secrets.TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN }} + +jobs: + send_results: + name: Send results to webhook + runs-on: ubuntu-22.04 + if: always() + steps: + - name: Preliminary job status + shell: bash + # For the meaning of these environment variables, see the job `Setup` + run: | + echo "Setup status: ${{ inputs.setup_status }}" + + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + - name: Send message to Slack + if: ${{ inputs.job != 'run_quantization_torch_gpu' }} + env: + CI_SLACK_BOT_TOKEN: ${{ secrets.CI_SLACK_BOT_TOKEN }} + CI_SLACK_CHANNEL_ID: ${{ secrets.CI_SLACK_CHANNEL_ID }} + CI_SLACK_CHANNEL_ID_DAILY: ${{ secrets.CI_SLACK_CHANNEL_ID_DAILY }} + CI_SLACK_CHANNEL_DUMMY_TESTS: ${{ secrets.CI_SLACK_CHANNEL_DUMMY_TESTS }} + SLACK_REPORT_CHANNEL: ${{ inputs.slack_report_channel }} + ACCESS_REPO_INFO_TOKEN: ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + CI_EVENT: ${{ inputs.ci_event }} + CI_SHA: ${{ github.sha }} + CI_WORKFLOW_REF: ${{ github.workflow_ref }} + CI_TEST_JOB: ${{ inputs.job }} + SETUP_STATUS: ${{ inputs.setup_status }} + # We pass `needs.setup.outputs.matrix` as the argument. A processing in `notification_service.py` to change + # `models/bert` to `models_bert` is required, as the artifact names use `_` instead of `/`. + # For a job that doesn't depend on (i.e. `needs`) `setup`, the value for `inputs.folder_slices` would be an + # empty string, and the called script still get one argument (which is the emtpy string). + run: | + sudo apt-get install -y curl + pip install huggingface_hub + pip install slack_sdk + pip show slack_sdk + python utils/notification_service.py "${{ inputs.folder_slices }}" + + # Upload complete failure tables, as they might be big and only truncated versions could be sent to Slack. + - name: Failure table artifacts + uses: actions/upload-artifact@v4 + with: + name: ci_results_${{ inputs.job }} + path: ci_results_${{ inputs.job }} + + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + - name: Send message to Slack for quantization workflow + if: ${{ inputs.job == 'run_quantization_torch_gpu' }} + env: + CI_SLACK_BOT_TOKEN: ${{ secrets.CI_SLACK_BOT_TOKEN }} + ACCESS_REPO_INFO_TOKEN: ${{ secrets.ACCESS_REPO_INFO_TOKEN }} + SLACK_REPORT_CHANNEL: ${{ inputs.slack_report_channel }} + CI_EVENT: ${{ inputs.ci_event }} + CI_SHA: ${{ github.sha }} + CI_TEST_JOB: ${{ inputs.job }} + SETUP_STATUS: ${{ inputs.setup_status }} + # We pass `needs.setup.outputs.quantization_matrix` as the argument. A processing in `notification_service_quantization.py` to change + # `quantization/bnb` to `quantization_bnb` is required, as the artifact names use `_` instead of `/`. + run: | + sudo apt-get install -y curl + pip install huggingface_hub + pip install slack_sdk + pip show slack_sdk + python utils/notification_service_quantization.py "${{ inputs.quantization_matrix }}" + + # Upload complete failure tables, as they might be big and only truncated versions could be sent to Slack. + - name: Failure table artifacts + if: ${{ inputs.job == 'run_quantization_torch_gpu' }} + uses: actions/upload-artifact@v4 + with: + name: ci_results_${{ inputs.job }} + path: ci_results_${{ inputs.job }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/ssh-runner.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/ssh-runner.yml new file mode 100644 index 0000000000000000000000000000000000000000..e648883f191e0da240c5e72fc09496564b0a2891 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/ssh-runner.yml @@ -0,0 +1,113 @@ +name: SSH into our runners + +on: + workflow_dispatch: + inputs: + runner_type: + description: 'Type of runner to test (a10 or t4)' + required: true + docker_image: + description: 'Name of the Docker image' + required: true + num_gpus: + description: 'Type of the number of gpus to use (`single` or `multi`)' + required: true + +env: + HF_HUB_READ_TOKEN: ${{ secrets.HF_HUB_READ_TOKEN }} + HF_HOME: /mnt/cache + TRANSFORMERS_IS_CI: yes + OMP_NUM_THREADS: 8 + MKL_NUM_THREADS: 8 + RUN_SLOW: yes # For gated repositories, we still need to agree to share information on the Hub repo. page in order to get access. # This token is created under the bot `hf-transformers-bot`. + SIGOPT_API_TOKEN: ${{ secrets.SIGOPT_API_TOKEN }} + TF_FORCE_GPU_ALLOW_GROWTH: true + CUDA_VISIBLE_DEVICES: 0,1 + +jobs: + get_runner: + name: "Get runner to use" + runs-on: ubuntu-22.04 + outputs: + RUNNER: ${{ steps.set_runner.outputs.RUNNER }} + steps: + - name: Get runner to use + shell: bash + run: | + if [[ "${{ github.event.inputs.num_gpus }}" == "single" && "${{ github.event.inputs.runner_type }}" == "t4" ]]; then + echo "RUNNER=aws-g4dn-2xlarge-cache" >> $GITHUB_ENV + elif [[ "${{ github.event.inputs.num_gpus }}" == "multi" && "${{ github.event.inputs.runner_type }}" == "t4" ]]; then + echo "RUNNER=aws-g4dn-12xlarge-cache" >> $GITHUB_ENV + elif [[ "${{ github.event.inputs.num_gpus }}" == "single" && "${{ github.event.inputs.runner_type }}" == "a10" ]]; then + echo "RUNNER=aws-g5-4xlarge-cache" >> $GITHUB_ENV + elif [[ "${{ github.event.inputs.num_gpus }}" == "multi" && "${{ github.event.inputs.runner_type }}" == "a10" ]]; then + echo "RUNNER=aws-g5-12xlarge-cache" >> $GITHUB_ENV + else + echo "RUNNER=" >> $GITHUB_ENV + fi + + - name: Set runner to use + id: set_runner + run: | + echo ${{ env.RUNNER }} + echo "RUNNER=${{ env.RUNNER }}" >> $GITHUB_OUTPUT + + ssh_runner: + name: "SSH" + needs: get_runner + runs-on: + group: ${{ needs.get_runner.outputs.RUNNER }} + container: + image: ${{ github.event.inputs.docker_image }} + options: --gpus all --privileged --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ + + steps: + - name: Update clone + working-directory: /transformers + run: | + git fetch && git checkout ${{ github.sha }} + + - name: Cleanup + working-directory: /transformers + run: | + rm -rf tests/__pycache__ + rm -rf tests/models/__pycache__ + rm -rf reports + + - name: Show installed libraries and their versions + working-directory: /transformers + run: pip freeze + + - name: NVIDIA-SMI + run: | + nvidia-smi + + - name: Store Slack infos + #because the SSH can be enabled dynamically if the workflow failed, so we need to store slack infos to be able to retrieve them during the waitforssh step + shell: bash + run: | + echo "${{ github.actor }}" + github_actor=${{ github.actor }} + github_actor=${github_actor/'-'/'_'} + echo "$github_actor" + echo "github_actor=$github_actor" >> $GITHUB_ENV + + - name: Store Slack infos + #because the SSH can be enabled dynamically if the workflow failed, so we need to store slack infos to be able to retrieve them during the waitforssh step + shell: bash + run: | + echo "${{ env.github_actor }}" + if [ "${{ secrets[format('{0}_{1}', env.github_actor, 'SLACK_ID')] }}" != "" ]; then + echo "SLACKCHANNEL=${{ secrets[format('{0}_{1}', env.github_actor, 'SLACK_ID')] }}" >> $GITHUB_ENV + else + echo "SLACKCHANNEL=${{ secrets.SLACK_CIFEEDBACK_CHANNEL }}" >> $GITHUB_ENV + fi + + - name: Tailscale # In order to be able to SSH when a test fails + uses: huggingface/tailscale-action@main + with: + authkey: ${{ secrets.TAILSCALE_SSH_AUTHKEY }} + slackChannel: ${{ env.SLACKCHANNEL }} + slackToken: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + waitForSSH: true + sshTimeout: 15m diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/stale.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..65eaf755ab3a69f9d978f8ab6f7e14584918262c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/stale.yml @@ -0,0 +1,29 @@ +name: Stale Bot + +on: + schedule: + - cron: "0 8 * * *" + +jobs: + close_stale_issues: + name: Close Stale Issues + if: github.repository == 'huggingface/transformers' + runs-on: ubuntu-22.04 + permissions: + issues: write + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: 3.8 + + - name: Install requirements + run: | + pip install PyGithub + - name: Close stale issues + run: | + python scripts/stale.py diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/trufflehog.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/trufflehog.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f6646e114d82c20dfba79f0d625a02e1ee3522d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/trufflehog.yml @@ -0,0 +1,20 @@ +on: + push: + +name: Secret Leaks + +permissions: + contents: read + +jobs: + trufflehog: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@main + with: + extra_args: --results=verified,unknown diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/update_metdata.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/update_metdata.yml new file mode 100644 index 0000000000000000000000000000000000000000..90cd73077ac0bb01ef4b14b2305ff4d39d612eba --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/update_metdata.yml @@ -0,0 +1,27 @@ +name: Update Transformers metadata + +on: + push: + branches: + - main + - update_transformers_metadata* + +jobs: + build_and_package: + runs-on: ubuntu-22.04 + defaults: + run: + shell: bash -l {0} + + steps: + - uses: actions/checkout@v4 + + - name: Setup environment + run: | + pip install --upgrade pip + pip install datasets pandas==2.0.3 + pip install .[torch,tf,flax] + + - name: Update metadata + run: | + python utils/update_metadata.py --token ${{ secrets.LYSANDRE_HF_TOKEN }} --commit_sha ${{ github.sha }} diff --git a/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/upload_pr_documentation.yml b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/upload_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..64befc595c421e1167765404e551b080211cb192 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.github/workflows/upload_pr_documentation.yml @@ -0,0 +1,16 @@ +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main + with: + package_name: transformers + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} + comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/.gitignore b/tasks/tasksmith-441eeab80047/tests/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..337f2ef2c735e89dc8f76ba3367cc29301264f66 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/.gitignore @@ -0,0 +1,169 @@ +# Initially taken from Github's Python gitignore file + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# tests and logs +tests/fixtures/cached_*_text.txt +logs/ +lightning_logs/ +lang_code_data/ + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# vscode +.vs +.vscode + +# Pycharm +.idea + +# TF code +tensorflow_code + +# Models +proc_data + +# examples +runs +/runs_old +/wandb +/examples/runs +/examples/**/*.args +/examples/rag/sweep + +# data +/data +serialization_dir + +# emacs +*.*~ +debug.env + +# vim +.*.swp + +#ctags +tags + +# pre-commit +.pre-commit* + +# .lock +*.lock + +# DS_Store (MacOS) +.DS_Store + +# ruff +.ruff_cache diff --git a/tasks/tasksmith-441eeab80047/tests/source/CITATION.cff b/tasks/tasksmith-441eeab80047/tests/source/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..b4d5156786f94df7ca0aebe5322b17dbb1521cb3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/CITATION.cff @@ -0,0 +1,82 @@ +cff-version: "1.2.0" +date-released: 2020-10 +message: "If you use this software, please cite it using these metadata." +title: "Transformers: State-of-the-Art Natural Language Processing" +url: "https://github.com/huggingface/transformers" +authors: + - family-names: Wolf + given-names: Thomas + - family-names: Debut + given-names: Lysandre + - family-names: Sanh + given-names: Victor + - family-names: Chaumond + given-names: Julien + - family-names: Delangue + given-names: Clement + - family-names: Moi + given-names: Anthony + - family-names: Cistac + given-names: Perric + - family-names: Ma + given-names: Clara + - family-names: Jernite + given-names: Yacine + - family-names: Plu + given-names: Julien + - family-names: Xu + given-names: Canwen + - family-names: "Le Scao" + given-names: Teven + - family-names: Gugger + given-names: Sylvain + - family-names: Drame + given-names: Mariama + - family-names: Lhoest + given-names: Quentin + - family-names: Rush + given-names: "Alexander M." +preferred-citation: + type: conference-paper + authors: + - family-names: Wolf + given-names: Thomas + - family-names: Debut + given-names: Lysandre + - family-names: Sanh + given-names: Victor + - family-names: Chaumond + given-names: Julien + - family-names: Delangue + given-names: Clement + - family-names: Moi + given-names: Anthony + - family-names: Cistac + given-names: Perric + - family-names: Ma + given-names: Clara + - family-names: Jernite + given-names: Yacine + - family-names: Plu + given-names: Julien + - family-names: Xu + given-names: Canwen + - family-names: "Le Scao" + given-names: Teven + - family-names: Gugger + given-names: Sylvain + - family-names: Drame + given-names: Mariama + - family-names: Lhoest + given-names: Quentin + - family-names: Rush + given-names: "Alexander M." + booktitle: "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations" + month: 10 + start: 38 + end: 45 + title: "Transformers: State-of-the-Art Natural Language Processing" + year: 2020 + publisher: "Association for Computational Linguistics" + url: "https://www.aclweb.org/anthology/2020.emnlp-demos.6" + address: "Online" diff --git a/tasks/tasksmith-441eeab80047/tests/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-441eeab80047/tests/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..b23f3150a5a6987a74acc7bb31df8c9bf1a48d57 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/tasks/tasksmith-441eeab80047/tests/source/CONTRIBUTING.md b/tasks/tasksmith-441eeab80047/tests/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c4804c69fb034fe0f83bf0e3bec11881c007db6c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/CONTRIBUTING.md @@ -0,0 +1,395 @@ + + +# Contribute to 🤗 Transformers + +Everyone is welcome to contribute, and we value everybody's contribution. Code +contributions are not the only way to help the community. Answering questions, helping +others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts +about the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our +[code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to 🤗 Transformers: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement new models. +* Contribute to the examples or to the documentation. + +If you don't know where to start, there is a special [Good First +Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of +open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions. + +> [!TIP] +> We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫 + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version** and **Python**, **PyTorch** and + **TensorFlow** versions when applicable. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +transformers-cli env +``` + +You can also run the same command from the root of the repository: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the features usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue. + +## Do you want to implement a new model? + +New models are constantly released and if you want to implement a new model, please provide the following information: + +* A short description of the model and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to the model weights if they are available. + +If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers! + +We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model). + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested! + +For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs). + +## Create a Pull Request + +Before writing any code, we strongly advise you to search through the existing PRs or +issues to make sure nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to contribute to +🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest +manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing: + +1. Fork the [repository](https://github.com/huggingface/transformers) by + clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +3. Create a new branch to hold your development changes: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 **Do not** work on the `main` branch! + +4. Set up a development environment by running the following command in a virtual environment: + + ```bash + pip install -e ".[dev]" + ``` + + If 🤗 Transformers was already installed in the virtual environment, remove + it with `pip uninstall transformers` before reinstalling it in editable + mode with the `-e` flag. + + Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a + failure with this command. If that's the case make sure to install the Deep Learning framework you are working with + (PyTorch, TensorFlow and/or Flax) then do: + + ```bash + pip install -e ".[quality]" + ``` + + which should be enough for most use cases. + +5. Develop the features in your branch. + + As you work on your code, you should make sure the test suite + passes. Run the tests impacted by your changes like this: + + ```bash + pytest tests/.py + ``` + + For more information about tests, check out the + [Testing](https://huggingface.co/docs/transformers/testing) guide. + + 🤗 Transformers relies on `black` and `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + ```bash + make fixup + ``` + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command applies the + style corrections: + + ```bash + make style + ``` + + 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality + controls are run by the CI, but you can run the same checks with: + + ```bash + make quality + ``` + + Finally, we have a lot of scripts to make sure we don't forget to update + some files when adding a new model. You can run these scripts with: + + ```bash + make repo-consistency + ``` + + To learn more about those checks and how to fix any issues with them, check out the + [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + + If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check + make sure you install the [documentation builder](https://github.com/huggingface/doc-builder). + + ```bash + pip install hf-doc-builder + ``` + + Run the following command from the root of the repository: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated + Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request. + + Once you're happy with your changes, add the changed files with `git add` and + record your changes locally with `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Please remember to write [good commit + messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made! + + To keep your copy of the code up to date with the original + repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push your changes to your branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally. + +6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review. + +7. It's ok if maintainers request changes, it happens to our core contributors + too! So everyone can see the changes in the pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + +### Pull request checklist + +☐ The pull request title should summarize your contribution.
+☐ If your pull request addresses an issue, please mention the issue number in the pull +request description to make sure they are linked (and people viewing the issue know you +are working on it).
+☐ To indicate a work in progress please prefix the title with `[WIP]`. These are +useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.
+☐ Make sure existing tests pass.
+☐ If adding a new feature, also add tests for it.
+ - If you are adding a new model, make sure you use + `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests. + - If you are adding new `@slow` tests, make sure they pass using + `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`. + - If you are adding a new tokenizer, write tests and make sure + `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes. + - CircleCI does not run the slow tests, but GitHub Actions does every night!
+ +☐ All public methods must have informative docstrings (see +[`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) +for an example).
+☐ Due to the rapidly growing repository, don't add any images, videos and other +non-text files that'll significantly weigh down the repository. Instead, use a Hub +repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) +to host these files and reference them by URL. We recommend placing documentation +related images in the following repository: +[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +You can open a PR on this dataset repository and ask a Hugging Face member to merge it. + +For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the +[examples](https://github.com/huggingface/transformers/tree/main/examples) folder. + +We like `pytest` and `pytest-xdist` because it's faster. From the root of the +repository, specify a *path to a subfolder or a test file* to run the test: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory: + +```bash +pip install -r examples/xxx/requirements.txt # only needed the first time +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)! + +You can also specify a smaller set of tests in order to test only the feature +you're working on. + +By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to +`yes` to run them. This will download many gigabytes of models so make sure you +have enough disk space, a good internet connection or a lot of patience! + + + +Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Like the slow tests, there are other environment variables available which are not enabled by default during testing: +- `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers. + +More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py). + +🤗 Transformers uses `pytest` as a test runner only. It doesn't use any +`pytest`-specific features in the test suite itself. + +This means `unittest` is fully supported. Here's how to run tests with +`unittest`: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Style guide + +For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) +for more information. + +### Develop on Windows + +On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings: + +```bash +git config core.autocrlf input +``` + +One way to run the `make` command on Windows is with MSYS2: + +1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`. +2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu). +3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`. +4. Add `C:\msys64\usr\bin` to your PATH environment variable. + +You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉 + +### Sync a forked repository with upstream main (the Hugging Face repository) + +When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs. + +1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main. +2. If a PR is absolutely necessary, use the following steps after checking out your branch: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..691225949df2e6ee5395cf2b9891de65920c2147 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.12-slim +WORKDIR /workspace +RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu torchvision==0.26.0+cpu numpy==2.5.3 packaging==26.3 parameterized==0.9.0 Pillow==10.4.0 pytest==8.4.2 pyyaml==6.0.2 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 tokenizers==0.21.4 huggingface-hub==0.36.2 tqdm==4.67.1 wheel==0.48.0 filelock==3.16.1 datasets==3.6.0 fsspec==2025.3.0 +COPY . /workspace +RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e . +RUN rm -rf /workspace/.git /root/.cache/pip +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 diff --git a/tasks/tasksmith-441eeab80047/tests/source/ISSUES.md b/tasks/tasksmith-441eeab80047/tests/source/ISSUES.md new file mode 100644 index 0000000000000000000000000000000000000000..a5969a3027f86dc1ed20ec1683642a1c723d0d19 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/ISSUES.md @@ -0,0 +1,277 @@ + + +# How To Request Support + +This is an Open Source Project so please be mindful that like in any other project of this kind there is no obligation to answer all requests for help. + +However, we want to encourage you to ask for help whenever you think it's needed! We are happy about every question we get because it allows us to better understand your needs, possible misunderstandings, and most importantly a way for you to help us make this library better. That being said, this document's main purpose is to provide guidelines at how you can formulate your requests to increase your chances to be understood and to get support. + +There are two main venues to receive support: [the forums](https://discuss.huggingface.co/) and [the GitHub issues](https://github.com/huggingface/transformers/issues). + +## The Forums + +[The user forums](https://discuss.huggingface.co/) are supported by the wide community of the library users and backed up by developers when needed. + +If you have a difficulty with deploying this library or some questions, or you'd like to discuss a new feature, please first consider discussing those things at the forums. Only when you feel your subject matter has been crystalized and you still need support from the library developers do proceed to file an [issue](https://github.com/huggingface/transformers/issues). + +In particular all "Please explain" questions or objectively very user-specific feature requests belong to the forums. Here are some example of such questions: + +* "I would like to use a BertModel within a RL-Agent for a customer support service. How can I use a BertForMaskedLM in my ChatBotModel?" + +* "Could you please explain why T5 has no positional embedding matrix under T5Model?" + +* "How should I set my generation parameters for translation?" + +* "How to train T5 on De->En translation?" + + +## The GitHub Issues + +Everything which hints at a bug should be opened as an [issue](https://github.com/huggingface/transformers/issues). + +You are not required to read the following guidelines before opening an issue. However, if you notice that your issue doesn't get any replies, chances are that the developers have one or several difficulties with its quality. In this case, reading the following points and adjusting your issue accordingly could help. + +1. Before posting an issue, first search for already posted issues, since chances are someone has already asked a similar question before you. + + If you use Google your search query should be: + + ``` + "huggingface" "transformers" your query + ``` + + The first two quoted words tell Google to limit the search to the context of the Huggingface Transformers. The remainder is your query - most commonly this would be the error message the software fails with. We will go deeper into details shortly. + + The results of such a query will typically match GitHub issues, Hugging Face forums, StackExchange, and blogs. + + If you find relevant hints, you may choose to continue the discussion there if you have follow up questions. + + If what you found is similar but doesn't quite answer your problem, please, post a new issue and do include links to similar issues or forum discussions you may have found. + + Let's look at some examples: + + The error message, often referred to as an assertion, tells us what went wrong. Here is an example of an assertion: + + ```python + Traceback (most recent call last): + File "", line 1, in + File "/transformers/src/transformers/__init__.py", line 34, in + from . import dependency_versions_check + File "/transformers/src/transformers/dependency_versions_check.py", line 34, in + from .utils import is_tokenizers_available + File "/transformers/src/transformers/utils/import_utils.py", line 40, in + from tqdm.auto import tqdm + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + and it typically includes a traceback, so that we can see the full stack of calls the program made before it fails. This gives us the context to know why the program failed. + + Going back to the above example. If you received this error search, look at the very last line of the error which is: + + ```python + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + And now we can use it to do the searching on your favorite search engine: + + 1. first for `"huggingface" "transformers" "ModuleNotFoundError: No module named 'tqdm.auto'"` + 2. if you don't find relevant results, then search for just `"ModuleNotFoundError: No module named 'tqdm.auto'"` + 3. and finally if nothing still comes up, then remove the outside quotes: `ModuleNotFoundError: No module named 'tqdm.auto'` + + If the error includes any messages that include bits unique to your filesystem, always remove those in the search query since other users will not have the same filesystem as yours. For example: + + ```bash + python -c 'open("/tmp/wrong_path.txt", "r")' + Traceback (most recent call last): + File "", line 1, in + FileNotFoundError: [Errno 2] No such file or directory: '/tmp/wrong_path.txt' + ``` + Here you'd search for just: `"FileNotFoundError: [Errno 2] No such file or directory"` + + If the local information that you removed were inside the error message and you removed them you may need to remove double quotes since your query is no longer exact. So if the error message was something like: + + ```bash + ValueError: '/tmp/wrong_path.txt' cannot be found + ``` + + then you'd search for `"ValueError" "cannot be found"` + + As you search you will notice that when you don't use quotes often the search engines will return a variety of unrelated hits, which may or may not be what you want. + + Experiment with different ways and find which approach gives the most satisfactory results. + +2. Keep the issue short, providing the information that you think will aid the developers to understand your situation. Put yourself in the shoes of the person who has never seen your code or knows anything about your custom setup. This mental exercise will help to develop an intuition to what/what not to share" + +3. If there is a software failure, always provide the full traceback, for example: + + ```python + $ python -c 'import transformers' + Traceback (most recent call last): + File "", line 1, in + File "/transformers/src/transformers/__init__.py", line 34, in + from . import dependency_versions_check + File "/transformers/src/transformers/dependency_versions_check.py", line 34, in + from .utils import is_tokenizers_available + File "/transformers/src/transformers/utils/import_utils.py", line 40, in + from tqdm.auto import tqdm + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + + As compared to providing just the last line of the error message, e.g.: + ```python + ModuleNotFoundError: No module named 'tqdm.auto' + ``` + which is not sufficient. + + If your application is running on more than one GPU (e.g. under `DistributedDataParallel`) and typically getting every log and traceback printed multiple times, please make sure that you paste only one copy of it. At times the traceback from parallel processes may get interleaved - so either disentangle these or change the loggers to log only for `local_rank==0` so that only one process logs things. + +4. When quoting a traceback, command line instructions and any type of code always enclose it in triple backticks inside the editor window, that is: + + ```` + ``` + git clone https://github.com/huggingface/transformers + cd transformers + pip install . + ``` + ```` + + If it's a command line with a long argument list, please consider breaking it down using backslashes and new lines. Here is an example of a good command line quote: + + ```bash + cd examples/seq2seq + torchrun --nproc_per_node=2 ./finetune_trainer.py \ + --model_name_or_path sshleifer/distill-mbart-en-ro-12-4 --data_dir wmt_en_ro \ + --output_dir output_dir --overwrite_output_dir \ + --do_train --n_train 500 --num_train_epochs 1 \ + --per_device_train_batch_size 1 --freeze_embeds \ + --src_lang en_XX --tgt_lang ro_RO --task translation \ + --fp16 + ``` + + If you don't break it up, one has to scroll horizontally which often makes it quite difficult to quickly see what's happening. + + The backslashes allow us to copy the command directly into the console to run it, without needing to edit it. + +5. Include only the important information that you think will help the developer to quickly identify the problem. + + For example applications often create huge amounts of logs. Ask yourself whether providing all or parts of the log is useful. + + Pasting a 100-1000 lines of log into the issue is an immediate turn off, since it will take a lot of time to figure out where the pertinent parts of the log are. + + Attaching a full log can be helpful if it's done as an attachment, if it's enclosed in the following html code in the comment editor window: + + ``` +
+ Full log +
+
+   many
+   lines
+   go
+   here
+
+   
+
+ ``` + + which would result in the following entry, which can be opened if desired, but otherwise takes little space. + +
+ Full log +
+   many
+   lines
+   go
+   here
+   
+
+ + You could also provide a link to a pastebin service, but this is less beneficial since those links tend to expire quickly and future readers of your issue might not be able to access that log file anymore and may lack some context. + +6. If this is an issue in your code, do try to reduce that code to a minimal example that still demonstrates the problem. Please ask at the forums if you have a hard time figuring how to do that. Please realize that we don't have the luxury of having time to try and understand all of your custom code. + + If you really tried to make a short reproducible code but couldn't figure it out, it might be that having a traceback will give the developer enough information to know what's going on. But if it is not enough and we can't reproduce the problem, we can't really solve it. + + Do not despair if you can't figure it out from the beginning, just share what you can and perhaps someone else will be able to help you at the forums. + + If your setup involves any custom datasets, the best way to help us reproduce the problem is to create a [Google Colab notebook](https://colab.research.google.com/) that demonstrates the issue and once you verify that the issue still exists, include a link to that notebook in the Issue. Just make sure that you don't copy and paste the location bar url of the open notebook - as this is private and we won't be able to open it. Instead, you need to click on `Share` in the right upper corner of the notebook, select `Get Link` and then copy and paste the public link it will give to you. + +7. If you forked off some of this project's code or example applications, please, do not ask us to go into your code repository and figure out what you may have done. The code is already very complex and unless there is an easy way to do a diff and it's a small diff, it won't be possible to find someone with time on their hands to make a lengthy investigation. Albeit, you might find someone at the forums who will be generous to do this for you. + +8. Before reporting an issue, first, always try to update your environment to the latest official version of this library. We have no resources to go and debug older revisions, which could easily have bugs that have been fixed in the latest released version. + + We understand that this is not always possible, especially when APIs change, in which case file an issue against the highest library version your environment can support. + + Of course, if you upgrade the library, always retest that the problem is still there. + +9. Please do not ask us to reproduce an issue with your custom data, since we don't have it. So, either you should use some existing dataset supported by HF datasets or you need to supply a code that generates a small sample on the fly, or some another quick and simple way to get it. + + Please do not send us any non-public domain data that may require a license or a permission to be used. + +10. Do not tag multiple developers on the issue unless you know this is expected, either because you asked them and they gave you an explicit permission to tag them or the issue template instructs you to do so. + + The "who to tag for what domain" part of the issue template is there to help users direct their questions to the right developers who are designated maintainers of project's specific domains. They can then decide at their own discretion to tag other developers if they feel it'd help move the issue forward. + + We currently don't have a triage service and we trust your capacity to identify the right domain and thus the persons to tag in your issue. If you are not sure, please use the forums to ask for guidance. + + When in doubt, err on the side of not tagging a given person. If you tag multiple people out of context or permission don't be surprised if you get no response at all. Please remember that every time you tag someone, they get a notification and you're taking their time without their permission. Please be sensitive to that. + + If you got helped by one of the developers in the past please don't tag them in future issues, unless they are listed in the issue template for the domain you are asking about or that developer gave you an explicit permission to tag them in future issues. + + If you see a certain developer doing multiple and/or recent commits into a specific area of the project that you feel is relevant to your issue, it is not a good reason to tag them. Various developers may be fixing things that prevent them from moving forward, but often their work is focused on a totally different domain. And while they may or may not know how to help you with the problem at hand, it would benefit the whole community much more if they focus on the domain of their unique expertise. + +11. Use the Edit button. Take your time, and re-read and improve the wording and formatting to make your posts and comments as easy to understand as possible. + + Avoid posting multiple comments in a row, as each comment generates a notification for the developers tagged in that issue. If you happened to post multiple comments in a row, and nobody followed up yet - consider merging those into one or a few comments while editing the combined content to be coherent. + + If you choose to edit your older comments after others posted follow up comments you need to be aware that your modifications might not be noticed, so if it's not a typo fixing, try to write a new comment flagging that something has been changed in the previous comments. + + For example, the very first comment is the most important one. If while the thread unfolds you realize that things aren't as they seemed to you originally you may want to edit the first post to reflect the up-to-date understanding of the issue at hand so that it helps those who read your issue in the future quickly understand what's going on and not need to sift through dozens of comments. It also helps to indicate that the post was edited. So, those reading the thread later can understand why there might be certain discontinuity in the information flow. + + Use bullets and items if you have lists of items and the outcome improves overall readability. + + Use backticks to refer to class and function names, e.g. `BartModel` and `generate` as these stand out and improve the speed of a reader's comprehension. + + Try not use italics and bold text too much as these often make the text more difficult to read. + + +12. If you are cross-referencing a specific comment in a given thread or another issue, always link to that specific comment, rather than using the issue link. If you do the latter it could be quite impossible to find which specific comment you're referring to. + + To get the link to the specific comment do not copy the url from the location bar of your browser, but instead, click the `...` icon in the upper right corner of the comment and then select "Copy Link". + + For example the first link is a link to an issue, and the second to a specific comment in the same issue: + + 1. https://github.com/huggingface/transformers/issues/9257 + 2. https://github.com/huggingface/transformers/issues/9257#issuecomment-749945162 + + +13. If you are replying to a last comment, it's totally fine to make your reply with just your comment in it. The readers can follow the information flow here. + + But if you're replying to a comment that happened some comments back it's always a good practice to quote just the relevant lines you're replying it. The `>` is used for quoting, or you can always use the menu to do so. For example your editor box will look like: + + ``` + > How big is your gpu cluster? + + Our cluster is made of 256 gpus. + ``` + + If you are addressing multiple comments, quote the relevant parts of each before your answer. Some people use the same comment to do multiple replies, others separate them into separate comments. Either way works. The latter approach helps for linking to a specific comment. + +In general the best way to figure out what works the best is learn from issues posted by other people - see which issues get great responses and which get little to no response - observe what the posters who received great responses did differently from those who did not. + +Thank you for reading this somewhat lengthy document. We would like to conclude that these are not absolute rules, but a friendly advice that will help maximize the chances for us to understand what you are trying to communicate, reproduce the problem then resolve it to your satisfaction and the benefit of the whole community. + +If after reading this document there are remaining questions on how and why or there is a need for further elucidation, please, don't hesitate to ask your question in [this thread](https://discuss.huggingface.co/t/how-to-request-support/3128). diff --git a/tasks/tasksmith-441eeab80047/tests/source/LICENSE b/tasks/tasksmith-441eeab80047/tests/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/LICENSE @@ -0,0 +1,203 @@ +Copyright 2018- The Hugging Face team. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/tasksmith-441eeab80047/tests/source/Makefile b/tasks/tasksmith-441eeab80047/tests/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..21152e985082ace05f8cc083b8161f4298309b28 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/Makefile @@ -0,0 +1,127 @@ +.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples benchmark + +# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!) +export PYTHONPATH = src + +check_dirs := examples tests src utils + +exclude_folders := "" + +modified_only_fixup: + $(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs))) + @if test -n "$(modified_py_files)"; then \ + echo "Checking/fixing $(modified_py_files)"; \ + ruff check $(modified_py_files) --fix --exclude $(exclude_folders); \ + ruff format $(modified_py_files) --exclude $(exclude_folders);\ + else \ + echo "No library .py files were modified"; \ + fi + +# Update src/transformers/dependency_versions_table.py + +deps_table_update: + @python setup.py deps_table_update + +deps_table_check_updated: + @md5sum src/transformers/dependency_versions_table.py > md5sum.saved + @python setup.py deps_table_update + @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1) + @rm md5sum.saved + +# autogenerating code + +autogenerate_code: deps_table_update + +# Check that the repo is in a good state + +repo-consistency: + python utils/check_copies.py + python utils/check_modular_conversion.py + python utils/check_dummies.py + python utils/check_repo.py + python utils/check_inits.py + python utils/check_config_docstrings.py + python utils/check_config_attributes.py + python utils/check_doctest_list.py + python utils/update_metadata.py --check-only + python utils/check_docstrings.py + +# this target runs checks on all files + +quality: + @python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) + ruff check $(check_dirs) setup.py conftest.py + ruff format --check $(check_dirs) setup.py conftest.py + python utils/sort_auto_mappings.py --check_only + python utils/check_doc_toc.py + python utils/check_docstrings.py --check_all + + +# Format source code automatically and check is there are any problems left that need manual fixing + +extra_style_checks: + python utils/sort_auto_mappings.py + python utils/check_doc_toc.py --fix_and_overwrite + +# this target runs checks on all files and potentially modifies some of them + +style: + ruff check $(check_dirs) setup.py conftest.py --fix --exclude $(exclude_folders) + ruff format $(check_dirs) setup.py conftest.py --exclude $(exclude_folders) + ${MAKE} autogenerate_code + ${MAKE} extra_style_checks + +# Super fast fix and check target that only works on relevant modified files since the branch was made + +fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency + +# Make marked copies of snippets of codes conform to the original + +fix-copies: + python utils/check_copies.py --fix_and_overwrite + python utils/check_modular_conversion.py --fix_and_overwrite + python utils/check_dummies.py --fix_and_overwrite + python utils/check_doctest_list.py --fix_and_overwrite + python utils/check_docstrings.py --fix_and_overwrite + +# Run tests for the library + +test: + python -m pytest -n auto --dist=loadfile -s -v ./tests/ + +# Run tests for examples + +test-examples: + python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/ + +# Run benchmark + +benchmark: + python3 benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=diff backend.model=google/gemma-2b backend.cache_implementation=null,static backend.torch_compile=false,true --multirun + +# Run tests for SageMaker DLC release + +test-sagemaker: # install sagemaker dependencies in advance with pip install .[sagemaker] + TEST_SAGEMAKER=True python -m pytest -n auto -s -v ./tests/sagemaker + + +# Release stuff + +pre-release: + python utils/release.py + +pre-patch: + python utils/release.py --patch + +post-release: + python utils/release.py --post_release + +post-patch: + python utils/release.py --post_release --patch + +build-release: + rm -rf dist + rm -rf build + python setup.py bdist_wheel + python setup.py sdist + python utils/check_build.py diff --git a/tasks/tasksmith-441eeab80047/tests/source/README.md b/tasks/tasksmith-441eeab80047/tests/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6bbcdbc82f8bf6f162c922e03935d0c7c3b95ae3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/README.md @@ -0,0 +1,342 @@ + + +

+ + + + Hugging Face Transformers Library + +
+
+

+ +

+ Build + GitHub + Documentation + GitHub release + Contributor Covenant + DOI +

+ +

+

+ English | + 简体中文 | + 繁體中文 | + 한국어 | + Español | + 日本語 | + हिन्दी | + Русский | + Рortuguês | + తెలుగు | + Français | + Deutsch | + Tiếng Việt | + العربية | + اردو | +

+

+ +

+

State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow

+

+ +

+ +

+ +🤗 Transformers provides thousands of pretrained models to perform tasks on different modalities such as text, vision, and audio. + +These models can be applied on: + +* 📝 Text, for tasks like text classification, information extraction, question answering, summarization, translation, and text generation, in over 100 languages. +* 🖼️ Images, for tasks like image classification, object detection, and segmentation. +* 🗣️ Audio, for tasks like speech recognition and audio classification. + +Transformer models can also perform tasks on **several modalities combined**, such as table question answering, optical character recognition, information extraction from scanned documents, video classification, and visual question answering. + +🤗 Transformers provides APIs to quickly download and use those pretrained models on a given text, fine-tune them on your own datasets and then share them with the community on our [model hub](https://huggingface.co/models). At the same time, each python module defining an architecture is fully standalone and can be modified to enable quick research experiments. + +🤗 Transformers is backed by the three most popular deep learning libraries — [Jax](https://jax.readthedocs.io/en/latest/), [PyTorch](https://pytorch.org/) and [TensorFlow](https://www.tensorflow.org/) — with a seamless integration between them. It's straightforward to train your models with one before loading them for inference with the other. + +## Online demos + +You can test most of our models directly on their pages from the [model hub](https://huggingface.co/models). We also offer [private model hosting, versioning, & an inference API](https://huggingface.co/pricing) for public and private models. + +Here are a few examples: + +In Natural Language Processing: +- [Masked word completion with BERT](https://huggingface.co/google-bert/bert-base-uncased?text=Paris+is+the+%5BMASK%5D+of+France) +- [Named Entity Recognition with Electra](https://huggingface.co/dbmdz/electra-large-discriminator-finetuned-conll03-english?text=My+name+is+Sarah+and+I+live+in+London+city) +- [Text generation with Mistral](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) +- [Natural Language Inference with RoBERTa](https://huggingface.co/FacebookAI/roberta-large-mnli?text=The+dog+was+lost.+Nobody+lost+any+animal) +- [Summarization with BART](https://huggingface.co/facebook/bart-large-cnn?text=The+tower+is+324+metres+%281%2C063+ft%29+tall%2C+about+the+same+height+as+an+81-storey+building%2C+and+the+tallest+structure+in+Paris.+Its+base+is+square%2C+measuring+125+metres+%28410+ft%29+on+each+side.+During+its+construction%2C+the+Eiffel+Tower+surpassed+the+Washington+Monument+to+become+the+tallest+man-made+structure+in+the+world%2C+a+title+it+held+for+41+years+until+the+Chrysler+Building+in+New+York+City+was+finished+in+1930.+It+was+the+first+structure+to+reach+a+height+of+300+metres.+Due+to+the+addition+of+a+broadcasting+aerial+at+the+top+of+the+tower+in+1957%2C+it+is+now+taller+than+the+Chrysler+Building+by+5.2+metres+%2817+ft%29.+Excluding+transmitters%2C+the+Eiffel+Tower+is+the+second+tallest+free-standing+structure+in+France+after+the+Millau+Viaduct) +- [Question answering with DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased-distilled-squad?text=Which+name+is+also+used+to+describe+the+Amazon+rainforest+in+English%3F&context=The+Amazon+rainforest+%28Portuguese%3A+Floresta+Amaz%C3%B4nica+or+Amaz%C3%B4nia%3B+Spanish%3A+Selva+Amaz%C3%B3nica%2C+Amazon%C3%ADa+or+usually+Amazonia%3B+French%3A+For%C3%AAt+amazonienne%3B+Dutch%3A+Amazoneregenwoud%29%2C+also+known+in+English+as+Amazonia+or+the+Amazon+Jungle%2C+is+a+moist+broadleaf+forest+that+covers+most+of+the+Amazon+basin+of+South+America.+This+basin+encompasses+7%2C000%2C000+square+kilometres+%282%2C700%2C000+sq+mi%29%2C+of+which+5%2C500%2C000+square+kilometres+%282%2C100%2C000+sq+mi%29+are+covered+by+the+rainforest.+This+region+includes+territory+belonging+to+nine+nations.+The+majority+of+the+forest+is+contained+within+Brazil%2C+with+60%25+of+the+rainforest%2C+followed+by+Peru+with+13%25%2C+Colombia+with+10%25%2C+and+with+minor+amounts+in+Venezuela%2C+Ecuador%2C+Bolivia%2C+Guyana%2C+Suriname+and+French+Guiana.+States+or+departments+in+four+nations+contain+%22Amazonas%22+in+their+names.+The+Amazon+represents+over+half+of+the+planet%27s+remaining+rainforests%2C+and+comprises+the+largest+and+most+biodiverse+tract+of+tropical+rainforest+in+the+world%2C+with+an+estimated+390+billion+individual+trees+divided+into+16%2C000+species) +- [Translation with T5](https://huggingface.co/google-t5/t5-base?text=My+name+is+Wolfgang+and+I+live+in+Berlin) + +In Computer Vision: +- [Image classification with ViT](https://huggingface.co/google/vit-base-patch16-224) +- [Object Detection with DETR](https://huggingface.co/facebook/detr-resnet-50) +- [Semantic Segmentation with SegFormer](https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512) +- [Panoptic Segmentation with Mask2Former](https://huggingface.co/facebook/mask2former-swin-large-coco-panoptic) +- [Depth Estimation with Depth Anything](https://huggingface.co/docs/transformers/main/model_doc/depth_anything) +- [Video Classification with VideoMAE](https://huggingface.co/docs/transformers/model_doc/videomae) +- [Universal Segmentation with OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_dinat_large) + +In Audio: +- [Automatic Speech Recognition with Whisper](https://huggingface.co/openai/whisper-large-v3) +- [Keyword Spotting with Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks) +- [Audio Classification with Audio Spectrogram Transformer](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593) + +In Multimodal tasks: +- [Table Question Answering with TAPAS](https://huggingface.co/google/tapas-base-finetuned-wtq) +- [Visual Question Answering with ViLT](https://huggingface.co/dandelin/vilt-b32-finetuned-vqa) +- [Image captioning with LLaVa](https://huggingface.co/llava-hf/llava-1.5-7b-hf) +- [Zero-shot Image Classification with SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384) +- [Document Question Answering with LayoutLM](https://huggingface.co/impira/layoutlm-document-qa) +- [Zero-shot Video Classification with X-CLIP](https://huggingface.co/docs/transformers/model_doc/xclip) +- [Zero-shot Object Detection with OWLv2](https://huggingface.co/docs/transformers/en/model_doc/owlv2) +- [Zero-shot Image Segmentation with CLIPSeg](https://huggingface.co/docs/transformers/model_doc/clipseg) +- [Automatic Mask Generation with SAM](https://huggingface.co/docs/transformers/model_doc/sam) + + +## 100 projects using Transformers + +Transformers is more than a toolkit to use pretrained models: it's a community of projects built around it and the +Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone +else to build their dream projects. + +In order to celebrate the 100,000 stars of transformers, we have decided to put the spotlight on the +community, and we have created the [awesome-transformers](./awesome-transformers.md) page which lists 100 +incredible projects built in the vicinity of transformers. + +If you own or use a project that you believe should be part of the list, please open a PR to add it! + +## Serious about AI in your organisation? Build faster with the Hugging Face Enterprise Hub. + + + Hugging Face Enterprise Hub +
+ +## Quick tour + +To immediately use a model on a given input (text, image, audio, ...), we provide the `pipeline` API. Pipelines group together a pretrained model with the preprocessing that was used during that model's training. Here is how to quickly use a pipeline to classify positive versus negative texts: + +```python +>>> from transformers import pipeline + +# Allocate a pipeline for sentiment-analysis +>>> classifier = pipeline('sentiment-analysis') +>>> classifier('We are very happy to introduce pipeline to the transformers repository.') +[{'label': 'POSITIVE', 'score': 0.9996980428695679}] +``` + +The second line of code downloads and caches the pretrained model used by the pipeline, while the third evaluates it on the given text. Here, the answer is "positive" with a confidence of 99.97%. + +Many tasks have a pre-trained `pipeline` ready to go, in NLP but also in computer vision and speech. For example, we can easily extract detected objects in an image: + +``` python +>>> import requests +>>> from PIL import Image +>>> from transformers import pipeline + +# Download an image with cute cats +>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png" +>>> image_data = requests.get(url, stream=True).raw +>>> image = Image.open(image_data) + +# Allocate a pipeline for object detection +>>> object_detector = pipeline('object-detection') +>>> object_detector(image) +[{'score': 0.9982201457023621, + 'label': 'remote', + 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, + {'score': 0.9960021376609802, + 'label': 'remote', + 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, + {'score': 0.9954745173454285, + 'label': 'couch', + 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, + {'score': 0.9988006353378296, + 'label': 'cat', + 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, + {'score': 0.9986783862113953, + 'label': 'cat', + 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}] +``` + +Here, we get a list of objects detected in the image, with a box surrounding the object and a confidence score. Here is the original image on the left, with the predictions displayed on the right: + +

+ + +

+ +You can learn more about the tasks supported by the `pipeline` API in [this tutorial](https://huggingface.co/docs/transformers/task_summary). + +In addition to `pipeline`, to download and use any of the pretrained models on your given task, all it takes is three lines of code. Here is the PyTorch version: +```python +>>> from transformers import AutoTokenizer, AutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> model = AutoModel.from_pretrained("google-bert/bert-base-uncased") + +>>> inputs = tokenizer("Hello world!", return_tensors="pt") +>>> outputs = model(**inputs) +``` + +And here is the equivalent code for TensorFlow: +```python +>>> from transformers import AutoTokenizer, TFAutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> model = TFAutoModel.from_pretrained("google-bert/bert-base-uncased") + +>>> inputs = tokenizer("Hello world!", return_tensors="tf") +>>> outputs = model(**inputs) +``` + +The tokenizer is responsible for all the preprocessing the pretrained model expects and can be called directly on a single string (as in the above examples) or a list. It will output a dictionary that you can use in downstream code or simply directly pass to your model using the ** argument unpacking operator. + +The model itself is a regular [Pytorch `nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) or a [TensorFlow `tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) (depending on your backend) which you can use as usual. [This tutorial](https://huggingface.co/docs/transformers/training) explains how to integrate such a model into a classic PyTorch or TensorFlow training loop, or how to use our `Trainer` API to quickly fine-tune on a new dataset. + +## Why should I use transformers? + +1. Easy-to-use state-of-the-art models: + - High performance on natural language understanding & generation, computer vision, and audio tasks. + - Low barrier to entry for educators and practitioners. + - Few user-facing abstractions with just three classes to learn. + - A unified API for using all our pretrained models. + +1. Lower compute costs, smaller carbon footprint: + - Researchers can share trained models instead of always retraining. + - Practitioners can reduce compute time and production costs. + - Dozens of architectures with over 400,000 pretrained models across all modalities. + +1. Choose the right framework for every part of a model's lifetime: + - Train state-of-the-art models in 3 lines of code. + - Move a single model between TF2.0/PyTorch/JAX frameworks at will. + - Seamlessly pick the right framework for training, evaluation, and production. + +1. Easily customize a model or an example to your needs: + - We provide examples for each architecture to reproduce the results published by its original authors. + - Model internals are exposed as consistently as possible. + - Model files can be used independently of the library for quick experiments. + +## Why shouldn't I use transformers? + +- This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files. +- The training API is not intended to work on any model but is optimized to work with the models provided by the library. For generic machine learning loops, you should use another library (possibly, [Accelerate](https://huggingface.co/docs/accelerate)). +- While we strive to present as many use cases as possible, the scripts in our [examples folder](https://github.com/huggingface/transformers/tree/main/examples) are just that: examples. It is expected that they won't work out-of-the-box on your specific problem and that you will be required to change a few lines of code to adapt them to your needs. + +## Installation + +### With pip + +This repository is tested on Python 3.9+, Flax 0.4.1+, PyTorch 2.0+, and TensorFlow 2.6+. + +You should install 🤗 Transformers in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). + +First, create a virtual environment with the version of Python you're going to use and activate it. + +**macOS/Linux** + +```python -m venv env +source env/bin/activate +``` + +**Windows** + +``` python -m venv env +env\Scripts\activate +``` + +To use 🤗 Transformers, you must install at least one of Flax, PyTorch, or TensorFlow. Refer to the official installation guides for platform-specific commands: + +[TensorFlow installation page](https://www.tensorflow.org/install/), +[PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) and/or [Flax](https://github.com/google/flax#quick-install) and [Jax](https://github.com/google/jax#installation) + +When one of those backends has been installed, 🤗 Transformers can be installed using pip as follows: + +``` +pip install transformers +``` + +If you'd like to play with the examples or need the bleeding edge of the code and can't wait for a new release, you must [install the library from source](https://huggingface.co/docs/transformers/installation#installing-from-source). + +``` +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install . +``` + +### With conda + +🤗 Transformers can be installed using conda as follows: + +```shell script +conda install conda-forge::transformers +``` + +> **_NOTE:_** Installing `transformers` from the `huggingface` channel is deprecated. + +Follow the installation pages of Flax, PyTorch or TensorFlow to see how to install them with conda. + +> **_NOTE:_** On Windows, you may be prompted to activate Developer Mode in order to benefit from caching. If this is not an option for you, please let us know in [this issue](https://github.com/huggingface/huggingface_hub/issues/1062). + +## Model architectures + +**[All the model checkpoints](https://huggingface.co/models)** provided by 🤗 Transformers are seamlessly integrated from the huggingface.co [model hub](https://huggingface.co/models), where they are uploaded directly by [users](https://huggingface.co/users) and [organizations](https://huggingface.co/organizations). + +Current number of checkpoints: ![](https://img.shields.io/endpoint?url=https://huggingface.co/api/shields/models&color=brightgreen) + +🤗 Transformers currently provides the following architectures: see [here](https://huggingface.co/docs/transformers/model_summary) for a high-level summary of each them. + +To check if each model has an implementation in Flax, PyTorch or TensorFlow, or has an associated tokenizer backed by the 🤗 Tokenizers library, refer to [this table](https://huggingface.co/docs/transformers/index#supported-frameworks). + +These implementations have been tested on several datasets (see the example scripts) and should match the performance of the original implementations. You can find more details on performance in the Examples section of the [documentation](https://github.com/huggingface/transformers/tree/main/examples). + + +## Learn more + +| Section | Description | +|-|-| +| [Documentation](https://huggingface.co/docs/transformers/) | Full API documentation and tutorials | +| [Task summary](https://huggingface.co/docs/transformers/task_summary) | Tasks supported by 🤗 Transformers | +| [Preprocessing tutorial](https://huggingface.co/docs/transformers/preprocessing) | Using the `Tokenizer` class to prepare data for the models | +| [Training and fine-tuning](https://huggingface.co/docs/transformers/training) | Using the models provided by 🤗 Transformers in a PyTorch/TensorFlow training loop and the `Trainer` API | +| [Quick tour: Fine-tuning/usage scripts](https://github.com/huggingface/transformers/tree/main/examples) | Example scripts for fine-tuning models on a wide range of tasks | +| [Model sharing and uploading](https://huggingface.co/docs/transformers/model_sharing) | Upload and share your fine-tuned models with the community | + +## Citation + +We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library: +```bibtex +@inproceedings{wolf-etal-2020-transformers, + title = "Transformers: State-of-the-Art Natural Language Processing", + author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush", + booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations", + month = oct, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6", + pages = "38--45" +} +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/SECURITY.md b/tasks/tasksmith-441eeab80047/tests/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..431b17a85042dccdd3062941b0e26099ef38a4b2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/SECURITY.md @@ -0,0 +1,39 @@ +# Security Policy + +## Hugging Face Hub, remote artefacts, and remote code + +Transformers is open-source software that is tightly coupled to the Hugging Face Hub. While you have the ability to use it +offline with pre-downloaded model weights, it provides a very simple way to download, use, and manage models locally. + +When downloading artefacts that have been uploaded by others on any platform, you expose yourself to risks. Please +read below for the security recommendations in order to keep your runtime and local environment safe. + +### Remote artefacts + +Models uploaded on the Hugging Face Hub come in different formats. We heavily recommend uploading and downloading +models in the [`safetensors`](https://github.com/huggingface/safetensors) format (which is the default prioritized +by the transformers library), as developed specifically to prevent arbitrary code execution on your system. + +To avoid loading models from unsafe formats(e.g. [pickle](https://docs.python.org/3/library/pickle.html), you should use the `use_safetensors` parameter. If doing so, in the event that no .safetensors file is present, transformers will error when loading the model. + +### Remote code + +#### Modeling + +Transformers supports many model architectures, but is also the bridge between your Python runtime and models that +are stored in model repositories on the Hugging Face Hub. + +These models require the `trust_remote_code=True` parameter to be set when using them; please **always** verify +the content of the modeling files when using this argument. We recommend setting a revision in order to ensure you +protect yourself from updates on the repository. + +#### Tools + +Through the `Agent` framework, remote tools can be downloaded to be used by the Agent. You're to specify these tools +yourself, but please keep in mind that their code will be run on your machine if the Agent chooses to run them. + +Please inspect the code of the tools before passing them to the Agent to protect your runtime and local setup. + +## Reporting a Vulnerability + +Feel free to submit vulnerability reports to [security@huggingface.co](mailto:security@huggingface.co), where someone from the HF security team will review and recommend next steps. If reporting a vulnerability specific to open source, please note [Huntr](https://huntr.com) is a vulnerability disclosure program for open source software. diff --git a/tasks/tasksmith-441eeab80047/tests/source/awesome-transformers.md b/tasks/tasksmith-441eeab80047/tests/source/awesome-transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..29f50184ec3d119653b90fd5af4a1b2a1b7fd493 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/awesome-transformers.md @@ -0,0 +1,609 @@ +# Awesome projects built with Transformers + +This page lists awesome projects built on top of Transformers. Transformers is more than a toolkit to use pretrained +models: it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable +developers, researchers, students, professors, engineers, and anyone else to build their dream projects. + +In this list, we showcase incredibly impactful and novel projects that have pushed the field forward. We celebrate +100 of these projects as we reach the milestone of 100k stars as a community; but we're very open to pull requests +adding other projects to the list. If you believe a project should be here and it's not, then please, open a PR +to add it. + +## [gpt4all](https://github.com/nomic-ai/gpt4all) + +[gpt4all](https://github.com/nomic-ai/gpt4all) is an ecosystem of open-source chatbots trained on massive collections of clean assistant data including code, stories and dialogue. It offers open-source, large language models such as LLaMA and GPT-J trained in an assistant-style. + +Keywords: Open-source, LLaMa, GPT-J, instruction, assistant + +## [recommenders](https://github.com/recommenders-team/recommenders) + +This repository contains examples and best practices for building recommendation systems, provided as Jupyter notebooks. It goes over several aspects required to build efficient recommendation systems: data preparation, modeling, evaluation, model selection & optimization, as well as operationalization + +Keywords: Recommender systems, AzureML + +## [IOPaint](https://github.com/Sanster/IOPaint) + +Image inpainting tool powered by Stable Diffusion. Remove any unwanted object, defect, people from your pictures or erase and replace anything on your pictures. + +Keywords: inpainting, SD, Stable Diffusion + +## [flair](https://github.com/flairNLP/flair) + +FLAIR is a powerful PyTorch NLP framework, covering several important tasks: NER, sentiment-analysis, part-of-speech tagging, text and document embeddings, among other things. + +Keywords: NLP, text embedding, document embedding, biomedical, NER, PoS, sentiment-analysis + +## [mindsdb](https://github.com/mindsdb/mindsdb) + +MindsDB is a low-code ML platform, which automates and integrates several ML frameworks into the data stack as "AI Tables" to streamline the integration of AI into applications, making it accessible to developers of all skill levels. + +Keywords: Database, low-code, AI table + +## [langchain](https://github.com/langchain-ai/langchain) + +[langchain](https://github.com/langchain-ai/langchain) is aimed at assisting in the development of apps merging both LLMs and other sources of knowledge. The library allows chaining calls to applications, creating a sequence across many tools. + +Keywords: LLMs, Large Language Models, Agents, Chains + +## [LlamaIndex](https://github.com/run-llama/llama_index) + +[LlamaIndex](https://github.com/run-llama/llama_index) is a project that provides a central interface to connect your LLM's with external data. It provides various kinds of indices and retrieval mechanisms to perform different LLM tasks and obtain knowledge-augmented results. + +Keywords: LLMs, Large Language Models, Data Retrieval, Indices, Knowledge Augmentation + +## [ParlAI](https://github.com/facebookresearch/ParlAI) + +[ParlAI](https://github.com/facebookresearch/ParlAI) is a python framework for sharing, training and testing dialogue models, from open-domain chitchat, to task-oriented dialogue, to visual question answering. It provides more than 100 datasets under the same API, a large zoo of pretrained models, a set of agents, and has several integrations. + +Keywords: Dialogue, Chatbots, VQA, Datasets, Agents + +## [sentence-transformers](https://github.com/UKPLab/sentence-transformers) + +This framework provides an easy method to compute dense vector representations for sentences, paragraphs, and images. The models are based on transformer networks like BERT / RoBERTa / XLM-RoBERTa etc. and achieve state-of-the-art performance in various task. Text is embedding in vector space such that similar text is close and can efficiently be found using cosine similarity. + +Keywords: Dense vector representations, Text embeddings, Sentence embeddings + +## [ludwig](https://github.com/ludwig-ai/ludwig) + +Ludwig is a declarative machine learning framework that makes it easy to define machine learning pipelines using a simple and flexible data-driven configuration system. Ludwig is targeted at a wide variety of AI tasks. It provides a data-driven configuration system, training, prediction, and evaluation scripts, as well as a programmatic API. + +Keywords: Declarative, Data-driven, ML Framework + +## [InvokeAI](https://github.com/invoke-ai/InvokeAI) + +[InvokeAI](https://github.com/invoke-ai/InvokeAI) is an engine for Stable Diffusion models, aimed at professionals, artists, and enthusiasts. It leverages the latest AI-driven technologies through CLI as well as a WebUI. + +Keywords: Stable-Diffusion, WebUI, CLI + +## [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) + +[PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) is an easy-to-use and powerful NLP library particularly targeted at the Chinese languages. It has support for multiple pre-trained model zoos, and supports a wide-range of NLP tasks from research to industrial applications. + +Keywords: NLP, Chinese, Research, Industry + +## [stanza](https://github.com/stanfordnlp/stanza) + +The Stanford NLP Group's official Python NLP library. It contains support for running various accurate natural language processing tools on 60+ languages and for accessing the Java Stanford CoreNLP software from Python. + +Keywords: NLP, Multilingual, CoreNLP + +## [DeepPavlov](https://github.com/deeppavlov/DeepPavlov) + +[DeepPavlov](https://github.com/deeppavlov/DeepPavlov) is an open-source conversational AI library. It is designed for the development of production ready chat-bots and complex conversational systems, as well as research in the area of NLP and, particularly, of dialog systems. + +Keywords: Conversational, Chatbot, Dialog + +## [alpaca-lora](https://github.com/tloen/alpaca-lora) + +Alpaca-lora contains code for reproducing the Stanford Alpaca results using low-rank adaptation (LoRA). The repository provides training (fine-tuning) as well as generation scripts. + +Keywords: LoRA, Parameter-efficient fine-tuning + +## [imagen-pytorch](https://github.com/lucidrains/imagen-pytorch) + +An open-source Implementation of Imagen, Google's closed-source Text-to-Image Neural Network that beats DALL-E2. As of release, it is the new SOTA for text-to-image synthesis. + +Keywords: Imagen, Text-to-image + +## [adapters](https://github.com/adapter-hub/adapters) + +[adapters](https://github.com/adapter-hub/adapters) is an extension of HuggingFace's Transformers library, integrating adapters into state-of-the-art language models by incorporating AdapterHub, a central repository for pre-trained adapter modules. It is a drop-in replacement for transformers, which is regularly updated to stay up-to-date with the developments of transformers. + +Keywords: Adapters, LoRA, Parameter-efficient fine-tuning, Hub + +## [NeMo](https://github.com/NVIDIA/NeMo) + +NVIDIA [NeMo](https://github.com/NVIDIA/NeMo) is a conversational AI toolkit built for researchers working on automatic speech recognition (ASR), text-to-speech synthesis (TTS), large language models (LLMs), and natural language processing (NLP). The primary objective of [NeMo](https://github.com/NVIDIA/NeMo) is to help researchers from industry and academia to reuse prior work (code and pretrained models) and make it easier to create new https://developer.nvidia.com/conversational-ai#started. + +Keywords: Conversational, ASR, TTS, LLMs, NLP + +## [Runhouse](https://github.com/run-house/runhouse) + +[Runhouse](https://github.com/run-house/runhouse) allows to send code and data to any of your compute or data infra, all in Python, and continue to interact with them normally from your existing code and environment. Runhouse developers mention: + +> Think of it as an expansion pack to your Python interpreter that lets it take detours to remote machines or manipulate remote data. + +Keywords: MLOps, Infrastructure, Data storage, Modeling + +## [MONAI](https://github.com/Project-MONAI/MONAI) + +[MONAI](https://github.com/Project-MONAI/MONAI) is a PyTorch-based, open-source framework for deep learning in healthcare imaging, part of PyTorch Ecosystem. Its ambitions are: +- developing a community of academic, industrial and clinical researchers collaborating on a common foundation; +- creating state-of-the-art, end-to-end training workflows for healthcare imaging; +- providing researchers with the optimized and standardized way to create and evaluate deep learning models. + +Keywords: Healthcare imaging, Training, Evaluation + +## [simpletransformers](https://github.com/ThilinaRajapakse/simpletransformers) + +Simple Transformers lets you quickly train and evaluate Transformer models. Only 3 lines of code are needed to initialize, train, and evaluate a model. It supports a wide variety of NLP tasks. + +Keywords: Framework, simplicity, NLP + +## [JARVIS](https://github.com/microsoft/JARVIS) + +[JARVIS](https://github.com/microsoft/JARVIS) is a system attempting to merge LLMs such as GPT-4 with the rest of the open-source ML community: leveraging up to 60 downstream models in order to perform tasks identified by the LLM. + +Keywords: LLM, Agents, HF Hub + +## [transformers.js](https://github.com/huggingface/transformers.js/) + +[transformers.js](https://github.com/huggingface/transformers.js/) is a JavaScript library targeted at running models from transformers directly within the browser. + +Keywords: Transformers, JavaScript, browser + +## [bumblebee](https://github.com/elixir-nx/bumblebee) + +Bumblebee provides pre-trained Neural Network models on top of Axon, a neural networks library for the Elixir language. It includes integration with 🤗 Models, allowing anyone to download and perform Machine Learning tasks with few lines of code. + +Keywords: Elixir, Axon + +## [argilla](https://github.com/argilla-io/argilla) + +Argilla is an open-source platform providing advanced NLP labeling, monitoring, and workspaces. It is compatible with many open source ecosystems such as Hugging Face, Stanza, FLAIR, and others. + +Keywords: NLP, Labeling, Monitoring, Workspaces + +## [haystack](https://github.com/deepset-ai/haystack) + +Haystack is an open source NLP framework to interact with your data using Transformer models and LLMs. It offers production-ready tools to quickly build complex decision making, question answering, semantic search, text generation applications, and more. + +Keywords: NLP, Framework, LLM + +## [spaCy](https://github.com/explosion/spaCy) + +[spaCy](https://github.com/explosion/spaCy) is a library for advanced Natural Language Processing in Python and Cython. It's built on the very latest research, and was designed from day one to be used in real products. It offers support for transformers models through its third party package, spacy-transformers. + +Keywords: NLP, Framework + +## [speechbrain](https://github.com/speechbrain/speechbrain) + +SpeechBrain is an open-source and all-in-one conversational AI toolkit based on PyTorch. +The goal is to create a single, flexible, and user-friendly toolkit that can be used to easily develop state-of-the-art speech technologies, including systems for speech recognition, speaker recognition, speech enhancement, speech separation, language identification, multi-microphone signal processing, and many others. + +Keywords: Conversational, Speech + +## [skorch](https://github.com/skorch-dev/skorch) + +Skorch is a scikit-learn compatible neural network library that wraps PyTorch. It has support for models within transformers, and tokenizers from tokenizers. + +Keywords: Scikit-Learn, PyTorch + +## [bertviz](https://github.com/jessevig/bertviz) + +BertViz is an interactive tool for visualizing attention in Transformer language models such as BERT, GPT2, or T5. It can be run inside a Jupyter or Colab notebook through a simple Python API that supports most Huggingface models. + +Keywords: Visualization, Transformers + +## [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) + +[mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) is a haiku library using the xmap/pjit operators in JAX for model parallelism of transformers. This library is designed for scalability up to approximately 40B parameters on TPUv3s. It was the library used to train the GPT-J model. + +Keywords: Haiku, Model parallelism, LLM, TPU + +## [deepchem](https://github.com/deepchem/deepchem) + +DeepChem aims to provide a high quality open-source toolchain that democratizes the use of deep-learning in drug discovery, materials science, quantum chemistry, and biology. + +Keywords: Drug discovery, Materials Science, Quantum Chemistry, Biology + +## [OpenNRE](https://github.com/thunlp/OpenNRE) + +An Open-Source Package for Neural Relation Extraction (NRE). It is targeted at a wide range of users, from newcomers to relation extraction, to developers, researchers, or students. + +Keywords: Neural Relation Extraction, Framework + +## [pycorrector](https://github.com/shibing624/pycorrector) + +PyCorrector is a Chinese Text Error Correction Tool. It uses a language model to detect errors, pinyin feature and shape feature to correct Chinese text errors. it can be used for Chinese Pinyin and stroke input method. + +Keywords: Chinese, Error correction tool, Language model, Pinyin + +## [nlpaug](https://github.com/makcedward/nlpaug) + +This python library helps you with augmenting nlp for machine learning projects. It is a lightweight library featuring synthetic data generation for improving model performance, support for audio and text, and compatibility with several ecosystems (scikit-learn, pytorch, tensorflow). + +Keywords: Data augmentation, Synthetic data generation, Audio, NLP + +## [dream-textures](https://github.com/carson-katri/dream-textures) + +[dream-textures](https://github.com/carson-katri/dream-textures) is a library targeted at bringing stable-diffusion support within Blender. It supports several use-cases, such as image generation, texture projection, inpainting/outpainting, ControlNet, and upscaling. + +Keywords: Stable-Diffusion, Blender + +## [seldon-core](https://github.com/SeldonIO/seldon-core) + +Seldon core converts your ML models (Tensorflow, Pytorch, H2o, etc.) or language wrappers (Python, Java, etc.) into production REST/GRPC microservices. +Seldon handles scaling to thousands of production machine learning models and provides advanced machine learning capabilities out of the box including Advanced Metrics, Request Logging, Explainers, Outlier Detectors, A/B Tests, Canaries and more. + +Keywords: Microservices, Modeling, Language wrappers + +## [open_model_zoo](https://github.com/openvinotoolkit/open_model_zoo) + +This repository includes optimized deep learning models and a set of demos to expedite development of high-performance deep learning inference applications. Use these free pre-trained models instead of training your own models to speed-up the development and production deployment process. + +Keywords: Optimized models, Demos + +## [ml-stable-diffusion](https://github.com/apple/ml-stable-diffusion) + +ML-Stable-Diffusion is a repository by Apple bringing Stable Diffusion support to Core ML, on Apple Silicon devices. It supports stable diffusion checkpoints hosted on the Hugging Face Hub. + +Keywords: Stable Diffusion, Apple Silicon, Core ML + +## [stable-dreamfusion](https://github.com/ashawkey/stable-dreamfusion) + +Stable-Dreamfusion is a pytorch implementation of the text-to-3D model Dreamfusion, powered by the Stable Diffusion text-to-2D model. + +Keywords: Text-to-3D, Stable Diffusion + +## [txtai](https://github.com/neuml/txtai) + +[txtai](https://github.com/neuml/txtai) is an open-source platform for semantic search and workflows powered by language models. txtai builds embeddings databases, which are a union of vector indexes and relational databases enabling similarity search with SQL. Semantic workflows connect language models together into unified applications. + +Keywords: Semantic search, LLM + +## [djl](https://github.com/deepjavalibrary/djl) + +Deep Java Library (DJL) is an open-source, high-level, engine-agnostic Java framework for deep learning. DJL is designed to be easy to get started with and simple to use for developers. DJL provides a native Java development experience and functions like any other regular Java library. DJL offers [a Java binding](https://github.com/deepjavalibrary/djl/tree/master/extensions/tokenizers) for HuggingFace Tokenizers and easy conversion toolkit for HuggingFace model to deploy in Java. + +Keywords: Java, Framework + +## [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness/) + +This project provides a unified framework to test generative language models on a large number of different evaluation tasks. It has support for more than 200 tasks, and supports different ecosystems: HF Transformers, GPT-NeoX, DeepSpeed, as well as the OpenAI API. + +Keywords: LLM, Evaluation, Few-shot + +## [gpt-neox](https://github.com/EleutherAI/gpt-neox) + +This repository records EleutherAI's library for training large-scale language models on GPUs. The framework is based on NVIDIA's Megatron Language Model and has been augmented with techniques from DeepSpeed as well as some novel optimizations. It is focused on training multi-billion-parameter models. + +Keywords: Training, LLM, Megatron, DeepSpeed + +## [muzic](https://github.com/microsoft/muzic) + +Muzic is a research project on AI music that empowers music understanding and generation with deep learning and artificial intelligence. Muzic was created by researchers from Microsoft Research Asia. + +Keywords: Music understanding, Music generation + +## [dalle-flow](https://github.com/jina-ai/dalle-flow) + +DALL·E Flow is an interactive workflow for generating high-definition images from a text prompt. Itt leverages DALL·E-Mega, GLID-3 XL, and Stable Diffusion to generate image candidates, and then calls CLIP-as-service to rank the candidates w.r.t. the prompt. +The preferred candidate is fed to GLID-3 XL for diffusion, which often enriches the texture and background. Finally, the candidate is upscaled to 1024x1024 via SwinIR. + +Keywords: High-definition image generation, Stable Diffusion, DALL-E Mega, GLID-3 XL, CLIP, SwinIR + +## [lightseq](https://github.com/bytedance/lightseq) + +LightSeq is a high performance training and inference library for sequence processing and generation implemented in CUDA. It enables highly efficient computation of modern NLP and CV models such as BERT, GPT, Transformer, etc. It is therefore best useful for machine translation, text generation, image classification, and other sequence related tasks. + +Keywords: Training, Inference, Sequence Processing, Sequence Generation + +## [LaTeX-OCR](https://github.com/lukas-blecher/LaTeX-OCR) + +The goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code. + +Keywords: OCR, LaTeX, Math formula + +## [open_clip](https://github.com/mlfoundations/open_clip) + +OpenCLIP is an open source implementation of OpenAI's CLIP. + +The goal of this repository is to enable training models with contrastive image-text supervision, and to investigate their properties such as robustness to distribution shift. +The starting point is an implementation of CLIP that matches the accuracy of the original CLIP models when trained on the same dataset. + +Specifically, a ResNet-50 model trained with this codebase on OpenAI's 15 million image subset of YFCC achieves 32.7% top-1 accuracy on ImageNet. + +Keywords: CLIP, Open-source, Contrastive, Image-text + +## [dalle-playground](https://github.com/saharmor/dalle-playground) + +A playground to generate images from any text prompt using Stable Diffusion and Dall-E mini. + +Keywords: WebUI, Stable Diffusion, Dall-E mini + +## [FedML](https://github.com/FedML-AI/FedML) + +[FedML](https://github.com/FedML-AI/FedML) is a federated learning and analytics library enabling secure and collaborative machine learning on decentralized data anywhere at any scale. + +It supports large-scale cross-silo federated learning, and cross-device federated learning on smartphones/IoTs, and research simulation. + +Keywords: Federated Learning, Analytics, Collaborative ML, Decentralized + +## [gpt-code-clippy](https://github.com/CodedotAl/gpt-code-clippy) + +GPT-Code-Clippy (GPT-CC) is an open source version of GitHub Copilot, a language model -- based on GPT-3, called GPT-Codex -- that is fine-tuned on publicly available code from GitHub. + +Keywords: LLM, Code + +## [TextAttack](https://github.com/QData/TextAttack) + +[TextAttack](https://github.com/QData/TextAttack) 🐙 is a Python framework for adversarial attacks, data augmentation, and model training in NLP. + +Keywords: Adversarial attacks, Data augmentation, NLP + +## [OpenPrompt](https://github.com/thunlp/OpenPrompt) + +Prompt-learning is a paradigm to adapt pre-trained language models (PLMs) to downstream NLP tasks, which modify the input text with a textual template and directly uses PLMs to conduct pre-trained tasks. This library provides a standard, flexible and extensible framework to deploy the prompt-learning pipeline. [OpenPrompt](https://github.com/thunlp/OpenPrompt) supports loading PLMs directly from https://github.com/huggingface/transformers. + +## [text-generation-webui](https://github.com/oobabooga/text-generation-webui/) + +[text-generation-webui](https://github.com/oobabooga/text-generation-webui/) is a Gradio Web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, Pythia, OPT, and GALACTICA. + +Keywords: LLM, WebUI + +## [libra](https://github.com/Palashio/libra) + +An ergonomic machine learning [libra](https://github.com/Palashio/libra)ry for non-technical users. It focuses on ergonomics and on ensuring that training a model is as simple as it can be. + +Keywords: Ergonomic, Non-technical + +## [alibi](https://github.com/SeldonIO/alibi) + +Alibi is an open source Python library aimed at machine learning model inspection and interpretation. The focus of the library is to provide high-quality implementations of black-box, white-box, local and global explanation methods for classification and regression models. + +Keywords: Model inspection, Model interpretation, Black-box, White-box + +## [tortoise-tts](https://github.com/neonbjb/tortoise-tts) + +Tortoise is a text-to-speech program built with the following priorities: strong multi-voice capabilities, and highly realistic prosody and intonation. + +Keywords: Text-to-speech + +## [flower](https://github.com/adap/flower) + +Flower (flwr) is a framework for building federated learning systems. The design of Flower is based on a few guiding principles: customizability, extendability, framework agnosticity, and ease-of-use. + +Keywords: Federated learning systems, Customizable, Extendable, Framework-agnostic, Simplicity + +## [fast-bert](https://github.com/utterworks/fast-bert) + +Fast-Bert is a deep learning library that allows developers and data scientists to train and deploy BERT and XLNet based models for natural language processing tasks beginning with Text Classification. It is aimed at simplicity. + +Keywords: Deployment, BERT, XLNet + +## [towhee](https://github.com/towhee-io/towhee) + +Towhee makes it easy to build neural data processing pipelines for AI applications. We provide hundreds of models, algorithms, and transformations that can be used as standard pipeline building blocks. Users can use Towhee's Pythonic API to build a prototype of their pipeline and automatically optimize it for production-ready environments. + +Keywords: Data processing pipeline, Optimization + +## [alibi-detect](https://github.com/SeldonIO/alibi-detect) + +Alibi Detect is an open source Python library focused on outlier, adversarial and drift detection. The package aims to cover both online and offline detectors for tabular data, text, images and time series. Both TensorFlow and PyTorch backends are supported for drift detection. + +Keywords: Adversarial, Outlier, Drift detection + +## [FARM](https://github.com/deepset-ai/FARM) + +[FARM](https://github.com/deepset-ai/FARM) makes Transfer Learning with BERT & Co simple, fast and enterprise-ready. It's built upon transformers and provides additional features to simplify the life of developers: Parallelized preprocessing, highly modular design, multi-task learning, experiment tracking, easy debugging and close integration with AWS SageMaker. + +Keywords: Transfer Learning, Modular design, Multi-task learning, Experiment tracking + +## [aitextgen](https://github.com/minimaxir/aitextgen) + +A robust Python tool for text-based AI training and generation using OpenAI's GPT-2 and EleutherAI's GPT Neo/GPT-3 architecture. +[aitextgen](https://github.com/minimaxir/aitextgen) is a Python package that leverages PyTorch, Hugging Face Transformers and pytorch-lightning with specific optimizations for text generation using GPT-2, plus many added features. + +Keywords: Training, Generation + +## [diffgram](https://github.com/diffgram/diffgram) + +Diffgram aims to integrate human supervision into platforms. We support your team programmatically changing the UI (Schema, layout, etc.) like in Streamlit. This means that you can collect and annotate timely data from users. In other words, we are the platform behind your platform, an integrated part of your application, to ship new & better AI products faster. + +Keywords: Human supervision, Platform + +## [ecco](https://github.com/jalammar/ecco) + +Explain, analyze, and visualize NLP language models. Ecco creates interactive visualizations directly in Jupyter notebooks explaining the behavior of Transformer-based language models (like GPT2, BERT, RoBERTA, T5, and T0). + +Keywords: Model explainability + +## [s3prl](https://github.com/s3prl/s3prl) + +[s3prl](https://github.com/s3prl/s3prl) stands for Self-Supervised Speech Pre-training and Representation Learning. Self-supervised speech pre-trained models are called upstream in this toolkit, and are utilized in various downstream tasks. + +Keywords: Speech, Training + +## [ru-dalle](https://github.com/ai-forever/ru-dalle) + +RuDALL-E aims to be similar to DALL-E, targeted to Russian. + +Keywords: DALL-E, Russian + +## [DeepKE](https://github.com/zjunlp/DeepKE) + +[DeepKE](https://github.com/zjunlp/DeepKE) is a knowledge extraction toolkit for knowledge graph construction supporting cnSchema,low-resource, document-level and multimodal scenarios for entity, relation and attribute extraction. + +Keywords: Knowledge Extraction, Knowledge Graphs + +## [Nebuly](https://github.com/nebuly-ai/optimate) + +Nebuly is the next-generation platform to monitor and optimize your AI costs in one place. The platform connects to all your AI cost sources (compute, API providers, AI software licenses, etc) and centralizes them in one place to give you full visibility on a model basis. The platform also provides optimization recommendations and a co-pilot model that can guide during the optimization process. The platform builds on top of the open-source tools allowing you to optimize the different steps of your AI stack to squeeze out the best possible cost performances. + +Keywords: Optimization, Performance, Monitoring + +## [imaginAIry](https://github.com/brycedrennan/imaginAIry) + +Offers a CLI and a Python API to generate images with Stable Diffusion. It has support for many tools, like image structure control (controlnet), instruction-based image edits (InstructPix2Pix), prompt-based masking (clipseg), among others. + +Keywords: Stable Diffusion, CLI, Python API + +## [sparseml](https://github.com/neuralmagic/sparseml) + +SparseML is an open-source model optimization toolkit that enables you to create inference-optimized sparse models using pruning, quantization, and distillation algorithms. Models optimized with SparseML can then be exported to the ONNX and deployed with DeepSparse for GPU-class performance on CPU hardware. + +Keywords: Model optimization, Pruning, Quantization, Distillation + +## [opacus](https://github.com/pytorch/opacus) + +Opacus is a library that enables training PyTorch models with differential privacy. It supports training with minimal code changes required on the client, has little impact on training performance, and allows the client to online track the privacy budget expended at any given moment. + +Keywords: Differential privacy + +## [LAVIS](https://github.com/salesforce/LAVIS) + +[LAVIS](https://github.com/salesforce/LAVIS) is a Python deep learning library for LAnguage-and-VISion intelligence research and applications. This library aims to provide engineers and researchers with a one-stop solution to rapidly develop models for their specific multimodal scenarios, and benchmark them across standard and customized datasets. It features a unified interface design to access + +Keywords: Multimodal, NLP, Vision + +## [buzz](https://github.com/chidiwilliams/buzz) + +Buzz transcribes and translates audio offline on your personal computer. Powered by OpenAI's Whisper. + +Keywords: Audio transcription, Translation + +## [rust-bert](https://github.com/guillaume-be/rust-bert) + +Rust-native state-of-the-art Natural Language Processing models and pipelines. Port of Hugging Face's Transformers library, using the tch-rs crate and pre-processing from rust-tokenizers. Supports multi-threaded tokenization and GPU inference. This repository exposes the model base architecture, task-specific heads and ready-to-use pipelines. + +Keywords: Rust, BERT, Inference + +## [EasyNLP](https://github.com/alibaba/EasyNLP) + +[EasyNLP](https://github.com/alibaba/EasyNLP) is an easy-to-use NLP development and application toolkit in PyTorch, first released inside Alibaba in 2021. It is built with scalable distributed training strategies and supports a comprehensive suite of NLP algorithms for various NLP applications. [EasyNLP](https://github.com/alibaba/EasyNLP) integrates knowledge distillation and few-shot learning for landing large pre-trained models, together with various popular multi-modality pre-trained models. It provides a unified framework of model training, inference, and deployment for real-world applications. + +Keywords: NLP, Knowledge distillation, Few-shot learning, Multi-modality, Training, Inference, Deployment + +## [TurboTransformers](https://github.com/Tencent/TurboTransformers) + +A fast and user-friendly runtime for transformer inference (Bert, Albert, GPT2, Decoders, etc) on CPU and GPU. + +Keywords: Optimization, Performance + +## [hivemind](https://github.com/learning-at-home/hivemind) + +Hivemind is a PyTorch library for decentralized deep learning across the Internet. Its intended usage is training one large model on hundreds of computers from different universities, companies, and volunteers. + +Keywords: Decentralized training + +## [docquery](https://github.com/impira/docquery) + +DocQuery is a library and command-line tool that makes it easy to analyze semi-structured and unstructured documents (PDFs, scanned images, etc.) using large language models (LLMs). You simply point DocQuery at one or more documents and specify a question you want to ask. DocQuery is created by the team at Impira. + +Keywords: Semi-structured documents, Unstructured documents, LLM, Document Question Answering + +## [CodeGeeX](https://github.com/THUDM/CodeGeeX) + +[CodeGeeX](https://github.com/THUDM/CodeGeeX) is a large-scale multilingual code generation model with 13 billion parameters, pre-trained on a large code corpus of more than 20 programming languages. It has several unique features: +- Multilingual code generation +- Crosslingual code translation +- Is a customizable programming assistant + +Keywords: Code Generation Model + +## [ktrain](https://github.com/amaiya/ktrain) + +[ktrain](https://github.com/amaiya/ktrain) is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, [ktrain](https://github.com/amaiya/ktrain) is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners. + +Keywords: Keras wrapper, Model building, Training, Deployment + +## [FastDeploy](https://github.com/PaddlePaddle/FastDeploy) + +[FastDeploy](https://github.com/PaddlePaddle/FastDeploy) is an Easy-to-use and High Performance AI model deployment toolkit for Cloud, Mobile and Edge with packageout-of-the-box and unified experience, endend-to-end optimization for over fire160+ Text, Vision, Speech and Cross-modal AI models. Including image classification, object detection, OCR, face detection, matting, pp-tracking, NLP, stable diffusion, TTS and other tasks to meet developers' industrial deployment needs for multi-scenario, multi-hardware and multi-platform. + +Keywords: Model deployment, CLoud, Mobile, Edge + +## [underthesea](https://github.com/undertheseanlp/underthesea) + +[underthesea](https://github.com/undertheseanlp/underthesea) is a Vietnamese NLP toolkit. Underthesea is a suite of open source Python modules data sets and tutorials supporting research and development in Vietnamese Natural Language Processing. We provides extremely easy API to quickly apply pretrained NLP models to your Vietnamese text, such as word segmentation, part-of-speech tagging (PoS), named entity recognition (NER), text classification and dependency parsing. + +Keywords: Vietnamese, NLP + +## [hasktorch](https://github.com/hasktorch/hasktorch) + +Hasktorch is a library for tensors and neural networks in Haskell. It is an independent open source community project which leverages the core C++ libraries shared by PyTorch. + +Keywords: Haskell, Neural Networks + +## [donut](https://github.com/clovaai/donut) + +Donut, or Document understanding transformer, is a new method of document understanding that utilizes an OCR-free end-to-end Transformer model. + +Donut does not require off-the-shelf OCR engines/APIs, yet it shows state-of-the-art performances on various visual document understanding tasks, such as visual document classification or information extraction (a.k.a. document parsing). + +Keywords: Document Understanding + +## [transformers-interpret](https://github.com/cdpierse/transformers-interpret) + +Transformers Interpret is a model explainability tool designed to work exclusively with the transformers package. + +In line with the philosophy of the Transformers package Transformers Interpret allows any transformers model to be explained in just two lines. Explainers are available for both text and computer vision models. Visualizations are also available in notebooks and as savable png and html files + +Keywords: Model interpretation, Visualization + +## [mlrun](https://github.com/mlrun/mlrun) + +MLRun is an open MLOps platform for quickly building and managing continuous ML applications across their lifecycle. MLRun integrates into your development and CI/CD environment and automates the delivery of production data, ML pipelines, and online applications, significantly reducing engineering efforts, time to production, and computation resources. With MLRun, you can choose any IDE on your local machine or on the cloud. MLRun breaks the silos between data, ML, software, and DevOps/MLOps teams, enabling collaboration and fast continuous improvements. + +Keywords: MLOps + +## [FederatedScope](https://github.com/alibaba/FederatedScope) + +[FederatedScope](https://github.com/alibaba/FederatedScope) is a comprehensive federated learning platform that provides convenient usage and flexible customization for various federated learning tasks in both academia and industry. Based on an event-driven architecture, [FederatedScope](https://github.com/alibaba/FederatedScope) integrates rich collections of functionalities to satisfy the burgeoning demands from federated learning, and aims to build up an easy-to-use platform for promoting learning safely and effectively. + +Keywords: Federated learning, Event-driven + +## [pythainlp](https://github.com/PyThaiNLP/pythainlp) + +PyThaiNLP is a Python package for text processing and linguistic analysis, similar to NLTK with focus on Thai language. + +Keywords: Thai, NLP, NLTK + +## [FlagAI](https://github.com/FlagAI-Open/FlagAI) + +[FlagAI](https://github.com/FlagAI-Open/FlagAI) (Fast LArge-scale General AI models) is a fast, easy-to-use and extensible toolkit for large-scale model. Our goal is to support training, fine-tuning, and deployment of large-scale models on various downstream tasks with multi-modality. + +Keywords: Large models, Training, Fine-tuning, Deployment, Multi-modal + +## [pyserini](https://github.com/castorini/pyserini) + +[pyserini](https://github.com/castorini/pyserini) is a Python toolkit for reproducible information retrieval research with sparse and dense representations. Retrieval using sparse representations is provided via integration with the group's Anserini IR toolkit. Retrieval using dense representations is provided via integration with Facebook's Faiss library. + +Keywords: IR, Information Retrieval, Dense, Sparse + +## [baal](https://github.com/baal-org/baal) + +[baal](https://github.com/baal-org/baal) is an active learning library that supports both industrial applications and research usecases. [baal](https://github.com/baal-org/baal) currently supports Monte-Carlo Dropout, MCDropConnect, deep ensembles, and semi-supervised learning. + +Keywords: Active Learning, Research, Labeling + +## [cleanlab](https://github.com/cleanlab/cleanlab) + +[cleanlab](https://github.com/cleanlab/cleanlab) is the standard data-centric AI package for data quality and machine learning with messy, real-world data and labels. For text, image, tabular, audio (among others) datasets, you can use cleanlab to automatically: detect data issues (outliers, label errors, near duplicates, etc), train robust ML models, infer consensus + annotator-quality for multi-annotator data, suggest data to (re)label next (active learning). + +Keywords: Data-Centric AI, Data Quality, Noisy Labels, Outlier Detection, Active Learning + +## [BentoML](https://github.com/bentoml/BentoML) + +[BentoML](https://github.com/bentoml) is the unified framework for building, shipping, and scaling production-ready AI applications incorporating traditional ML, pre-trained AI models, Generative and Large Language Models. +All Hugging Face models and pipelines can be seamlessly integrated into BentoML applications, enabling the running of models on the most suitable hardware and independent scaling based on usage. + +Keywords: BentoML, Framework, Deployment, AI Applications + +## [LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) + +[LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) offers a user-friendly fine-tuning framework that incorporates PEFT. The repository includes training(fine-tuning) and inference examples for LLaMA-2, BLOOM, Falcon, Baichuan, Qwen, and other LLMs. A ChatGLM version is also available in [ChatGLM-Efficient-Tuning](https://github.com/hiyouga/ChatGLM-Efficient-Tuning). + +Keywords: PEFT, fine-tuning, LLaMA-2, ChatGLM, Qwen + diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/README.md b/tasks/tasksmith-441eeab80047/tests/source/benchmark/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a827da444f08014815f0425edc1d4be492f058f4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/README.md @@ -0,0 +1,49 @@ +# Benchmarks + +You might want to add new benchmarks. + +You will need to define a python function named `run_benchmark` in your python file and the file must be located in this `benchmark/` directory. + +The expected function signature is the following: + +```py +def run_benchmark(logger: Logger, branch: str, commit_id: str, commit_msg: str, num_tokens_to_generate=100): +``` + +## Writing metrics to the database + +`MetricRecorder` is thread-safe, in the sense of the python [`Thread`](https://docs.python.org/3/library/threading.html#threading.Thread). This means you can start a background thread to do the readings on the device measurements while not blocking the main thread to execute the model measurements. + +cf [`llama.py`](./llama.py) to see an example of this in practice. + +```py +from benchmarks_entrypoint import MetricsRecorder +import psycopg2 + +def run_benchmark(logger: Logger, branch: str, commit_id: str, commit_msg: str, num_tokens_to_generate=100): + metrics_recorder = MetricsRecorder(psycopg2.connect("dbname=metrics"), logger, branch, commit_id, commit_msg) + benchmark_id = metrics_recorder.initialise_benchmark({"gpu_name": gpu_name, "model_id": model_id}) + # To collect device measurements + metrics_recorder.collect_device_measurements( + benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes + ) + # To collect your model measurements + metrics_recorder.collect_model_measurements( + benchmark_id, + { + "model_load_time": model_load_time, + "first_eager_forward_pass_time_secs": first_eager_fwd_pass_time, + "second_eager_forward_pass_time_secs": second_eager_fwd_pass_time, + "first_eager_generate_time_secs": first_eager_generate_time, + "second_eager_generate_time_secs": second_eager_generate_time, + "time_to_first_token_secs": time_to_first_token, + "time_to_second_token_secs": time_to_second_token, + "time_to_third_token_secs": time_to_third_token, + "time_to_next_token_mean_secs": mean_time_to_next_token, + "first_compile_generate_time_secs": first_compile_generate_time, + "second_compile_generate_time_secs": second_compile_generate_time, + "third_compile_generate_time_secs": third_compile_generate_time, + "fourth_compile_generate_time_secs": fourth_compile_generate_time, + }, + ) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmark.py b/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..304bbd4441cf660d3e4eb60e86b1ef36ccf979ec --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmark.py @@ -0,0 +1,326 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Run benchmark using the `optimum-benchmark` library with some customization in `transformers`. + +Assume we are under `transformers` root directory: (make sure the commits are valid commits) +```bash +python benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=9b9c7f03da625b13643e99205c691fe046461724 --metrics=decode.latency.mean,per_token.latency.mean,per_token.throughput.value backend.model=google/gemma-2b benchmark.input_shapes.sequence_length=5,7 benchmark.input_shapes.batch_size=1,2 --multirun +``` +""" + +import argparse +import glob +import json +import os.path +import re +import tempfile +from contextlib import contextmanager +from pathlib import Path + +from git import Repo + +from huggingface_hub import HfApi + +from optimum_benchmark import Benchmark +from optimum_benchmark_wrapper import main + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() + + +@contextmanager +def checkout_commit(repo: Repo, commit_id: str): + """ + Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + commit_id (`str`): The commit reference to checkout inside the context manager. + """ + current_head = repo.head.commit if repo.head.is_detached else repo.head.ref + + try: + repo.git.checkout(commit_id) + yield + + finally: + repo.git.checkout(current_head) + + +def summarize(run_dir, metrics, expand_metrics=False): + """Produce a summary for each optimum-benchmark launched job's output directory found in `run_dir`. + + Each summary's format is as follows (for `expand_metrics=False`): + ``` + { + "model": "google/gemma-2b", + "commit": "3cd6ed22e4d49219f300f5055e71e3929aba20d7", + "config": "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5", + "metrics": { + "decode.latency.mean": 1.624666809082031, + "per_token.latency.mean": 0.012843788806628804, + "per_token.throughput.value": 77.85864553330948 + } + } + ``` + """ + reports = glob.glob(os.path.join(run_dir, "**/benchmark_report.json"), recursive=True) + report_dirs = [str(Path(report).parent) for report in reports] + + summaries = [] + for report_dir in report_dirs: + commit = re.search(r"/commit=([^/]+)", report_dir).groups()[0] + + if not os.path.isfile(os.path.join(report_dir, "benchmark.json")): + continue + benchmark = Benchmark.from_json(os.path.join(report_dir, "benchmark.json")) + report = benchmark.report + + model = benchmark.config.backend["model"] + + # Ths looks like `benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5`. + # (we rely on the usage of hydra's `${hydra.job.override_dirname}`.) + benchmark_name = re.sub(f"backend.model={model},*", "", report_dir) + benchmark_name = str(Path(benchmark_name).parts[-1]) + if benchmark_name.startswith("commit="): + benchmark_name = benchmark.config.name + + metrics_values = {} + # post-processing of report: show a few selected/important metric + for metric in metrics: + keys = metric.split(".") + value = report.to_dict() + current = metrics_values + for key in keys: + # Avoid KeyError when a user's specified metric has typo. + # TODO: Give warnings. + if key not in value: + continue + value = value[key] + + if expand_metrics: + if isinstance(value, dict): + if key not in current: + current[key] = {} + current = current[key] + else: + current[key] = value + + if not expand_metrics: + metrics_values[metric] = value + + # show some config information + print(f"model: {model}") + print(f"commit: {commit}") + print(f"config: {benchmark_name}") + if len(metrics_values) > 0: + print("metrics:") + if expand_metrics: + print(metrics_values) + else: + for metric, value in metrics_values.items(): + print(f" - {metric}: {value}") + print("-" * 80) + + summary = { + "model": model, + "commit": commit, + "config": benchmark_name, + "metrics": metrics_values, + } + summaries.append(summary) + + with open(os.path.join(report_dir, "summary.json"), "w") as fp: + json.dump(summary, fp, indent=4) + + return summaries + + +def combine_summaries(summaries): + """Combine a list of summary obtained from the function `summarize`. + + The combined summary's format is as follows: + ``` + "google/gemma-2b": { + "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5": { + "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { + "metrics": {"decode.latency.mean": 1.624666809082031} + }, + "c97ee28b117c0abe8e08891f402065e4df6d72aa": { + "metrics": {"decode.latency.mean": 1.6278163452148438} + } + }, + "benchmark.input_shapes.batch_size=2,benchmark.input_shapes.sequence_length=5": { + "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { + "metrics": {"decode.latency.mean": 1.6947791748046876} + }, + "c97ee28b117c0abe8e08891f402065e4df6d72aa": { + "metrics": { + "decode.latency.mean": 1.6980519409179688} + } + } + } + ``` + """ + combined = {} + for summary in summaries: + model = summary["model"] + config = summary["config"] + commit = summary["commit"] + + if model not in combined: + combined[model] = {} + + if config not in combined[model]: + combined[model][config] = {} + + if commit not in combined[model][config]: + combined[model][config][commit] = {"metrics": summary["metrics"]} + + with open(os.path.join(exp_run_dir, "summary.json"), "w") as fp: + json.dump(combined, fp, indent=4) + + print(json.dumps(combined, indent=4)) + + return combined + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + + parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") + parser.add_argument("--config-name", type=str, required=True, help="The config name.") + + # arguments specific to this wrapper for our own customization + parser.add_argument("--ensure_empty", type=bool, default=True, help="If to create a temporary directory.") + parser.add_argument( + "--commit", + type=list_str, + default="", + help="Comma-separated list of branch names and/or commit sha values on which the benchmark will run. If `diff` is specified, it will run on both the current head and the `main` branch.", + ) + parser.add_argument("--metrics", type=str, help="The metrics to be included in the summary.") + + parser.add_argument("--repo_id", type=str, default=None, help="The repository to which the file will be uploaded.") + parser.add_argument("--path_in_repo", type=str, default=None, help="Relative filepath in the repo.") + parser.add_argument("--token", type=str, default=None, help="A valid user access token (string).") + + args, optimum_benchmark_args = parser.parse_known_args() + + repo = Repo(PATH_TO_REPO) + + metrics = [ + "prefill.latency.mean", + "prefill.throughput.value", + "decode.latency.mean", + "decode.throughput.value", + "per_token.latency.mean", + "per_token.throughput.value", + ] + if args.metrics is not None: + metrics = args.metrics.split(",") + + # Get `backend.model` in a hacky way: We want to control the experiment flow manually. + models = [""] + for idx, arg in enumerate(optimum_benchmark_args): + if arg.startswith("backend.model="): + models = arg[len("backend.model=") :] + models = models.split(",") + break + optimum_benchmark_args = [arg for arg in optimum_benchmark_args if not arg.startswith("backend.model=")] + + # Get the commit(s) + current_head = str(repo.head.commit) if repo.head.is_detached else str(repo.head.ref) + commits = [x for x in args.commit if x != ""] + if len(commits) == 0: + commits = [current_head] + elif len(commits) == 1 and commits[0] == "diff": + # compare to `main` + commits = ["main", current_head] + + # Get the specified run directory + run_dir_arg_idx, run_dir = -1, None + sweep_dir_arg_idx, sweep_dir = -1, None + for idx, arg in enumerate(optimum_benchmark_args): + if arg.startswith("hydra.run.dir="): + run_dir = arg[len("hydra.run.dir=") :] + run_dir_arg_idx = idx + elif arg.startswith("hydra.sweep.dir="): + sweep_dir = arg[len("hydra.sweep.dir=") :] + sweep_dir_arg_idx = idx + exp_run_dir, arg_dix, arg_name = ( + (sweep_dir, sweep_dir_arg_idx, "hydra.sweep.dir") + if "--multirun" in optimum_benchmark_args + else (run_dir, run_dir_arg_idx, "hydra.run.dir") + ) + + # TODO: not hardcoded + if exp_run_dir is None and args.ensure_empty: + exp_run_dir = "_benchmark" + + if args.ensure_empty: + os.makedirs(exp_run_dir, exist_ok=True) + exp_run_dir = tempfile.mkdtemp(dir=exp_run_dir) + + run_summaries = [] + for commit in commits: + with checkout_commit(repo, commit): + commit = str(repo.head.commit) + + commit_run_dir = exp_run_dir + if exp_run_dir is not None: + commit_run_dir = os.path.join(exp_run_dir, rf"commit\={commit}") + + print(f"Run benchmark on commit: {commit}") + + for model in models: + model_arg = [f"backend.model={model}"] if model != "" else [] + dir_args = [] + if commit_run_dir is not None: + if arg_dix > -1: + optimum_benchmark_args[arg_dix] = f"{arg_name}={commit_run_dir}" + else: + dir_args = [ + f"hydra.sweep.dir={commit_run_dir}", + f"hydra.run.dir={commit_run_dir}/" + "${hydra.job.override_dirname}", + ] + main(args.config_dir, args.config_name, model_arg + dir_args + optimum_benchmark_args) + + if commit_run_dir is not None: + # Need to remove the `\` character + summaries = summarize(commit_run_dir.replace("\\", ""), metrics) + run_summaries.extend(summaries) + + # aggregate the information across the commits + if exp_run_dir is not None: + with open(os.path.join(exp_run_dir, "summaries.json"), "w") as fp: + json.dump(run_summaries, fp, indent=4) + + combined_summary = combine_summaries(run_summaries) + + if args.repo_id is not None and args.path_in_repo is not None: + # Upload to Hub + api = HfApi() + api.upload_folder( + folder_path=exp_run_dir, + path_in_repo=args.path_in_repo, + repo_id=args.repo_id, + repo_type="dataset", + token=args.token, + ) diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmarks_entrypoint.py b/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmarks_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..df348b08523847a8688b2bd52bb3b25f568bd3d2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/benchmarks_entrypoint.py @@ -0,0 +1,144 @@ +import argparse +import importlib.util +import logging +import os +from typing import Dict +import psycopg2 +import sys + +from psycopg2.extras import Json +from psycopg2.extensions import register_adapter + + +register_adapter(dict, Json) + + +class ImportModuleException(Exception): + pass + + +class MetricsRecorder: + def __init__(self, connection, logger: logging.Logger, branch: str, commit_id: str, commit_msg: str): + self.conn = connection + self.conn.autocommit = True + self.logger = logger + self.branch = branch + self.commit_id = commit_id + self.commit_msg = commit_msg + + def initialise_benchmark(self, metadata: Dict[str, str]) -> int: + """ + Creates a new benchmark, returns the benchmark id + """ + # gpu_name: str, model_id: str + with self.conn.cursor() as cur: + cur.execute( + "INSERT INTO benchmarks (branch, commit_id, commit_message, metadata) VALUES (%s, %s, %s, %s) RETURNING benchmark_id", + (self.branch, self.commit_id, self.commit_msg, metadata), + ) + benchmark_id = cur.fetchone()[0] + logger.debug(f"initialised benchmark #{benchmark_id}") + return benchmark_id + + def collect_device_measurements(self, benchmark_id: int, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes): + """ + Collect device metrics, such as CPU & GPU usage. These are "static", as in you cannot pass arbitrary arguments to the function. + """ + with self.conn.cursor() as cur: + cur.execute( + "INSERT INTO device_measurements (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes) VALUES (%s, %s, %s, %s, %s)", + (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes), + ) + self.logger.debug( + f"inserted device measurements for benchmark #{benchmark_id} [CPU util: {cpu_util}, mem MBs: {mem_megabytes}, GPU util: {gpu_util}, GPU mem MBs: {gpu_mem_megabytes}]" + ) + + def collect_model_measurements(self, benchmark_id: int, measurements: Dict[str, float]): + with self.conn.cursor() as cur: + cur.execute( + """ + INSERT INTO model_measurements ( + benchmark_id, + measurements + ) VALUES (%s, %s) + """, + ( + benchmark_id, + measurements, + ), + ) + self.logger.debug(f"inserted model measurements for benchmark #{benchmark_id}: {measurements}") + + def close(self): + self.conn.close() + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +handler = logging.StreamHandler(sys.stdout) +handler.setLevel(logging.INFO) +formatter = logging.Formatter("[%(levelname)s - %(asctime)s] %(message)s") +handler.setFormatter(formatter) +logger.addHandler(handler) + + +def parse_arguments(): + """ + Parse command line arguments for the benchmarking CLI. + """ + parser = argparse.ArgumentParser(description="CLI for benchmarking the huggingface/transformers.") + + parser.add_argument( + "branch", + type=str, + help="The branch name on which the benchmarking is performed.", + ) + + parser.add_argument( + "commit_id", + type=str, + help="The commit hash on which the benchmarking is performed.", + ) + + parser.add_argument( + "commit_msg", + type=str, + help="The commit message associated with the commit, truncated to 70 characters.", + ) + + args = parser.parse_args() + + return args.branch, args.commit_id, args.commit_msg + + +def import_from_path(module_name, file_path): + try: + spec = importlib.util.spec_from_file_location(module_name, file_path) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module + except Exception as e: + raise ImportModuleException(f"failed to load python module: {e}") + + +if __name__ == "__main__": + benchmarks_folder_path = os.path.dirname(os.path.realpath(__file__)) + + branch, commit_id, commit_msg = parse_arguments() + + for entry in os.scandir(benchmarks_folder_path): + try: + if not entry.name.endswith(".py"): + continue + if entry.path == __file__: + continue + logger.debug(f"loading: {entry.name}") + module = import_from_path(entry.name.split(".")[0], entry.path) + logger.info(f"running benchmarks in: {entry.name}") + module.run_benchmark(logger, branch, commit_id, commit_msg) + except ImportModuleException as e: + logger.error(e) + except Exception as e: + logger.error(f"error running benchmarks for {entry.name}: {e}") diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/config/generation.yaml b/tasks/tasksmith-441eeab80047/tests/source/benchmark/config/generation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..44a3f9ea49015491c7add94a8790d16c20dc76fc --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/config/generation.yaml @@ -0,0 +1,57 @@ +defaults: + - benchmark # inheriting benchmark schema + - scenario: inference + - launcher: process + - backend: pytorch + - _self_ # for hydra 1.1 compatibility + +name: pytorch_generate + +launcher: + start_method: spawn + device_isolation: true + device_isolation_action: warn + +backend: + device: cuda + device_ids: 0 + no_weights: true + model: meta-llama/Llama-2-7b-hf + cache_implementation: static + torch_compile: true + torch_dtype: float16 + torch_compile_config: + backend: inductor + mode: reduce-overhead + fullgraph: true + +scenario: + input_shapes: + batch_size: 1 + sequence_length: 7 + generate_kwargs: + max_new_tokens: 128 + min_new_tokens: 128 + do_sample: false + memory: true + latency: true + iterations: 2 + duration: 0 + + +# hydra/cli specific settings +hydra: + run: + # where to store run results + dir: runs/${name} + job: + # change working directory to the run directory + chdir: true + env_set: + # set environment variable OVERRIDE_BENCHMARKS to 1 + # to not skip benchmarks that have been run before + OVERRIDE_BENCHMARKS: 1 + LOG_LEVEL: WARN + sweep: + dir: multirun + subdir: ${hydra.job.override_dirname} \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/default.yml b/tasks/tasksmith-441eeab80047/tests/source/benchmark/default.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3f02cab34d1bd2451eda4744ccf4f4eb7d0e6cc --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/default.yml @@ -0,0 +1,10 @@ +apiVersion: 1 + +providers: + - name: 'Transformers Benchmarks' + orgId: 1 + type: file + updateIntervalSeconds: 10 + allowUiUpdates: true + options: + path: /etc/grafana/dashboards diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_dashboard.json b/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_dashboard.json new file mode 100644 index 0000000000000000000000000000000000000000..caaec78a522303eaadc66171d405e203e7475694 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_dashboard.json @@ -0,0 +1,2375 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": 1, + "links": [ + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": false, + "title": "Go to data", + "tooltip": "Go to data", + "type": "link", + "url": "http://transformers-benchmarks.hf.co/d/fdz33iyzln9c0a/transformers-benchmarks?orgId=1&from=${StartTime}&to=${EndTime}" + } + ], + "liveNow": true, + "panels": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "custom": { + "align": "left", + "cellOptions": { + "type": "auto" + }, + "inspect": false + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "gpu_name" + }, + "properties": [ + { + "id": "custom.width", + "value": 202 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "left" + }, + "properties": [ + { + "id": "custom.width", + "value": 407 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "commit_message" + }, + "properties": [ + { + "id": "custom.width", + "value": 524 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "commit_id" + }, + "properties": [ + { + "id": "custom.width", + "value": 353 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "model_id" + }, + "properties": [ + { + "id": "custom.width", + "value": 216 + } + ] + } + ] + }, + "gridPos": { + "h": 6, + "w": 24, + "x": 0, + "y": 0 + }, + "id": 5, + "options": { + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "sortBy": [] + }, + "pluginVersion": "11.2.2", + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT commit_id, commit_message, metadata->>'gpu_name' as gpu_name, metadata->>'model_id' as model_id, created_at AS date FROM benchmarks WHERE branch = '${branch}' AND metadata->>'gpu_name' = '${gpu_name}' ORDER BY benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "commit_id", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_name", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baaa8aaa-89ab-4cde-b012-31922f96de3f", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "benchmarks" + } + ], + "transparent": true, + "type": "table" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 6 + }, + "id": 13, + "panels": [], + "title": "Eager Forward Pass", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 7 + }, + "id": 7, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "pluginVersion": "11.2.2", + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'first_eager_forward_pass_time_secs' AS double precision) AS first_eager_forward_pass_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "First eager forward pass", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 7 + }, + "id": 9, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'second_eager_forward_pass_time_secs' AS double precision) AS second_eager_forward_pass_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Second eager forward pass", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 18 + }, + "id": 16, + "panels": [], + "title": "Time to next token", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 19 + }, + "id": 17, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_first_token_secs' AS double precision) AS time_to_first_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to first token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 19 + }, + "id": 18, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_second_token_secs' AS double precision) AS time_to_second_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to second token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 30 + }, + "id": 19, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_third_token_secs' AS double precision) AS time_to_third_token_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to third token", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 30 + }, + "id": 20, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'time_to_next_token_mean_secs' AS double precision) AS time_to_next_token_mean_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Time to subsequent next tokens mean", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 41 + }, + "id": 14, + "panels": [], + "title": "Compiled Generate", + "type": "row" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 42 + }, + "id": 8, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "always", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'first_compile_generate_time_secs' AS double precision) AS first_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "First compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 42 + }, + "id": 10, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'second_compile_generate_time_secs' AS double precision) AS second_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Second compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "scheme", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 0, + "y": 53 + }, + "id": 11, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'third_compile_generate_time_secs' AS double precision) AS third_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Third compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "continuous-YlBl" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "fillOpacity": 80, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineWidth": 0, + "scaleDistribution": { + "type": "linear" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 11, + "w": 12, + "x": 12, + "y": 53 + }, + "id": 12, + "options": { + "barRadius": 0.05, + "barWidth": 0.8, + "fullHighlight": false, + "groupWidth": 0.7, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": false + }, + "orientation": "auto", + "showValue": "auto", + "stacking": "none", + "tooltip": { + "mode": "single", + "sort": "none" + }, + "xTickLabelRotation": 0, + "xTickLabelSpacing": 0 + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT CAST(m.measurements->'fourth_compile_generate_time_secs' AS double precision) AS fourth_compile_generate_time_secs, left(b.commit_id, 7), m.time FROM benchmarks as b JOIN model_measurements AS m ON b.benchmark_id = m.benchmark_id WHERE b.branch = '${branch}' AND b.metadata->>'gpu_name' = '${gpu_name}' ORDER BY b.benchmark_id DESC LIMIT ${last_n_commits};", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50 + } + } + ], + "title": "Fourth compile generate", + "transformations": [ + { + "id": "sortBy", + "options": { + "fields": {}, + "sort": [ + { + "field": "time" + } + ] + } + } + ], + "transparent": true, + "type": "barchart" + }, + { + "collapsed": true, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 64 + }, + "id": 15, + "panels": [ + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "percent" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 65 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n d.cpu_util,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "CPU Utilization", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "percent" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 65 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n b.commit_id,\n d.gpu_util,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "GPU Utilization", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "decmbytes" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 74 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT d.mem_megabytes, d.time FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "Memory usage", + "transparent": true, + "type": "timeseries" + }, + { + "datasource": {}, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": 60000, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "decmbytes" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 74 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "editorMode": "code", + "format": "table", + "rawQuery": true, + "rawSql": "SELECT\n d.gpu_mem_megabytes,\n d.time\nFROM\n benchmarks AS b\n JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id\nWHERE\n branch = '${branch}';", + "refId": "A", + "sql": { + "columns": [ + { + "parameters": [ + { + "name": "cpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_util", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "gpu_mem_megabytes", + "type": "functionParameter" + } + ], + "type": "function" + }, + { + "parameters": [ + { + "name": "\"time\"", + "type": "functionParameter" + } + ], + "type": "function" + } + ], + "groupBy": [ + { + "property": { + "type": "string" + }, + "type": "groupBy" + } + ], + "limit": 50, + "whereJsonTree": { + "children1": [ + { + "id": "baa888b8-89ab-4cde-b012-31922f8671e9", + "properties": { + "field": "commit_id", + "fieldSrc": "field", + "operator": "equal", + "value": [ + "${commit}" + ], + "valueError": [ + null + ], + "valueSrc": [ + "value" + ], + "valueType": [ + "text" + ] + }, + "type": "rule" + } + ], + "id": "bab88a98-0123-4456-b89a-b1922f7d4f11", + "type": "group" + }, + "whereString": "commit_id = '${commit}'" + }, + "table": "measurements" + } + ], + "title": "GPU memory usage", + "transparent": true, + "type": "timeseries" + } + ], + "title": "Usage metrics", + "type": "row" + } + ], + "schemaVersion": 39, + "tags": [], + "templating": { + "list": [ + { + "current": { + "selected": false, + "text": "main", + "value": "main" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT DISTINCT branch FROM benchmarks;", + "description": "", + "hide": 0, + "includeAll": false, + "label": "branch", + "multi": false, + "name": "branch", + "options": [], + "query": "SELECT DISTINCT branch FROM benchmarks;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "1729701492845", + "value": "1729701492845" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT created_at - INTERVAL '5 secs' FROM benchmarks WHERE branch = '${branch}' ORDER BY benchmark_id ASC LIMIT 1;", + "description": "", + "hide": 2, + "includeAll": false, + "multi": false, + "name": "StartTime", + "options": [], + "query": "SELECT created_at - INTERVAL '5 secs' FROM benchmarks WHERE branch = '${branch}' ORDER BY benchmark_id ASC LIMIT 1;", + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "1730393397577", + "value": "1730393397577" + }, + "datasource": { + "default": true, + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT time + INTERVAL '5 secs' FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}' ORDER BY b.benchmark_id DESC, d.measurement_id DESC LIMIT 1;", + "description": "", + "hide": 2, + "includeAll": false, + "multi": false, + "name": "EndTime", + "options": [], + "query": "SELECT time + INTERVAL '5 secs' FROM benchmarks AS b JOIN device_measurements AS d ON b.benchmark_id = d.benchmark_id WHERE branch = '${branch}' ORDER BY b.benchmark_id DESC, d.measurement_id DESC LIMIT 1;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": false, + "text": "NVIDIA A10G", + "value": "NVIDIA A10G" + }, + "datasource": { + "type": "grafana-postgresql-datasource", + "uid": "be28nkzirtb0gd" + }, + "definition": "SELECT DISTINCT metadata->>'gpu_name' FROM benchmarks;", + "description": "", + "hide": 0, + "includeAll": false, + "label": "GPU", + "multi": false, + "name": "gpu_name", + "options": [], + "query": "SELECT DISTINCT metadata->>'gpu_name' FROM benchmarks;", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": true, + "text": "10", + "value": "10" + }, + "description": "The number of commits to display, going from most recent to the nth commit.", + "hide": 0, + "label": "Last # of commits", + "name": "last_n_commits", + "options": [ + { + "selected": true, + "text": "10", + "value": "10" + } + ], + "query": "10", + "skipUrlSync": false, + "type": "textbox" + } + ] + }, + "time": { + "from": "now-1h", + "to": "now" + }, + "timepicker": { + "hidden": false + }, + "timezone": "browser", + "title": "Transformers benchmarks", + "uid": "fdz33iyzln9c0a", + "version": 10, + "weekStart": "" +} diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_datasource.yaml b/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_datasource.yaml new file mode 100644 index 0000000000000000000000000000000000000000..25f36254104ab5047fd36ddf00ebcde7289849a7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/grafana_datasource.yaml @@ -0,0 +1,17 @@ +apiVersion: 1 +datasources: + - name: grafana-postgresql-datasource + uid: be28nkzirtb0gd + type: postgres + url: $GRAFANA_POSTGRES_DATASOURCE_URL + user: $GRAFANA_POSTGRES_DATASOURCE_USER + secureJsonData: + password: $GRAFANA_POSTGRES_DATASOURCE_PWD + jsonData: + database: metrics + maxOpenConns: 100 + maxIdleConns: 100 + maxIdleConnsAuto: true + connMaxLifetime: 14400 + postgresVersion: 1000 + timescaledb: false diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/init_db.sql b/tasks/tasksmith-441eeab80047/tests/source/benchmark/init_db.sql new file mode 100644 index 0000000000000000000000000000000000000000..a7864c4af183b6ac26a8ac5dc623282e94b44c91 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/init_db.sql @@ -0,0 +1,33 @@ +CREATE TABLE IF NOT EXISTS benchmarks ( + benchmark_id SERIAL PRIMARY KEY, + branch VARCHAR(255), + commit_id VARCHAR(72), + commit_message VARCHAR(70), + metadata jsonb, + created_at timestamp without time zone NOT NULL DEFAULT (current_timestamp AT TIME ZONE 'UTC') +); + +CREATE INDEX IF NOT EXISTS benchmarks_benchmark_id_idx ON benchmarks (benchmark_id); + +CREATE INDEX IF NOT EXISTS benchmarks_branch_idx ON benchmarks (branch); + +CREATE TABLE IF NOT EXISTS device_measurements ( + measurement_id SERIAL PRIMARY KEY, + benchmark_id int REFERENCES benchmarks (benchmark_id), + cpu_util double precision, + mem_megabytes double precision, + gpu_util double precision, + gpu_mem_megabytes double precision, + time timestamp without time zone NOT NULL DEFAULT (current_timestamp AT TIME ZONE 'UTC') +); + +CREATE INDEX IF NOT EXISTS device_measurements_branch_idx ON device_measurements (benchmark_id); + +CREATE TABLE IF NOT EXISTS model_measurements ( + measurement_id SERIAL PRIMARY KEY, + benchmark_id int REFERENCES benchmarks (benchmark_id), + measurements jsonb, + time timestamp without time zone NOT NULL DEFAULT (current_timestamp AT TIME ZONE 'UTC') +); + +CREATE INDEX IF NOT EXISTS model_measurements_branch_idx ON model_measurements (benchmark_id); diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/llama.py b/tasks/tasksmith-441eeab80047/tests/source/benchmark/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..bbe1afefd5ef1bef9c9b38a74597a301cf8abb3a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/llama.py @@ -0,0 +1,342 @@ +from logging import Logger +import os +from threading import Event, Thread +from time import perf_counter, sleep +from typing import Optional +from benchmarks_entrypoint import MetricsRecorder +import gpustat +import psutil +import psycopg2 +import torch + +from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, StaticCache + + +os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" + +os.environ["TOKENIZERS_PARALLELISM"] = "1" +torch.set_float32_matmul_precision("high") + + +def collect_metrics(benchmark_id, continue_metric_collection, metrics_recorder): + p = psutil.Process(os.getpid()) + while not continue_metric_collection.is_set(): + with p.oneshot(): + cpu_util = p.cpu_percent() + mem_megabytes = p.memory_info().rss / (1024 * 1024) + gpu_stats = gpustat.GPUStatCollection.new_query() + gpu_util = gpu_stats[0]["utilization.gpu"] + gpu_mem_megabytes = gpu_stats[0]["memory.used"] + metrics_recorder.collect_device_measurements( + benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes + ) + sleep(0.01) + + +def run_benchmark(logger: Logger, branch: str, commit_id: str, commit_msg: str, num_tokens_to_generate=100): + continue_metric_collection = Event() + metrics_thread = None + model_id = "meta-llama/Llama-2-7b-hf" + metrics_recorder = MetricsRecorder(psycopg2.connect("dbname=metrics"), logger, branch, commit_id, commit_msg) + try: + gpu_stats = gpustat.GPUStatCollection.new_query() + gpu_name = gpu_stats[0]["name"] + benchmark_id = metrics_recorder.initialise_benchmark({"gpu_name": gpu_name, "model_id": model_id}) + logger.info(f"running benchmark #{benchmark_id} on {gpu_name} for {model_id}") + metrics_thread = Thread( + target=collect_metrics, + args=[benchmark_id, continue_metric_collection, metrics_recorder], + ) + metrics_thread.start() + logger.info("started background thread to fetch device metrics") + + os.environ["TOKENIZERS_PARALLELISM"] = "false" # silence warnings when compiling + + device = "cuda" + + logger.info("downloading weights") + # This is to avoid counting download in model load time measurement + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16) + gen_config = GenerationConfig(do_sample=False, top_p=1, temperature=1) + logger.info("loading model") + start = perf_counter() + model = AutoModelForCausalLM.from_pretrained( + model_id, torch_dtype=torch.float16, generation_config=gen_config + ).eval() + model.to(device) + torch.cuda.synchronize() + end = perf_counter() + model_load_time = end - start + logger.info(f"loaded model in: {model_load_time}s") + + tokenizer = AutoTokenizer.from_pretrained(model_id) + + prompt = "Why dogs are so cute?" + inputs = tokenizer(prompt, return_tensors="pt").to(device) + + # Specify the max length (including both the prompt and the response) + # When calling `generate` with `cache_implementation="static" later, this is also used to create a `StaticCache` object + # with sequence length = `max_length`. The longer the more you will re-use it + seq_length = inputs["input_ids"].shape[1] + model.generation_config.max_length = seq_length + num_tokens_to_generate + batch_size = inputs["input_ids"].shape[0] + + # Copied from the gpt-fast repo + def multinomial_sample_one_no_sync(probs_sort): # Does multinomial sampling without a cuda synchronization + q = torch.empty_like(probs_sort).exponential_(1) + return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int) + + def logits_to_probs(logits, temperature: float = 1.0, top_k: Optional[int] = None): + logits = logits / max(temperature, 1e-5) + + if top_k is not None: + v, _ = torch.topk(logits, min(top_k, logits.size(-1))) + pivot = v.select(-1, -1).unsqueeze(-1) + logits = torch.where(logits < pivot, -float("Inf"), logits) + probs = torch.nn.functional.softmax(logits, dim=-1) + return probs + + def sample(logits, temperature: float = 1.0, top_k: Optional[int] = None): + probs = logits_to_probs(logits[:, -1], temperature, top_k) + idx_next = multinomial_sample_one_no_sync(probs) + return idx_next, probs + + def decode_one_token(model, cur_token, cache_position, past_key_values): + logits = model( + cur_token, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True, + )[0] + new_token = sample(logits, temperature=0.6, top_k=5)[0] + return new_token + + ######### + # Eager # + ######### + with torch.no_grad(): + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + num_tokens_to_generate, + ) + cache_position = torch.arange(seq_length, device=device) + start = perf_counter() + model( + **inputs, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True, + ) + end = perf_counter() + first_eager_fwd_pass_time = end - start + logger.info(f"completed first eager fwd pass in: {first_eager_fwd_pass_time}s") + start = perf_counter() + output = model.generate(**inputs, do_sample=False) + end = perf_counter() + first_eager_generate_time = end - start + logger.info(f"completed first eager generation in: {first_eager_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + num_tokens_to_generate, + ) + cache_position = torch.arange(seq_length, device=device) + start = perf_counter() + model( + **inputs, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True, + ) + end = perf_counter() + second_eager_fwd_pass_time = end - start + logger.info(f"completed second eager fwd pass in: {second_eager_fwd_pass_time}s") + start = perf_counter() + model.generate(**inputs, do_sample=False) + end = perf_counter() + second_eager_generate_time = end - start + logger.info(f"completed second eager generation in: {second_eager_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + torch.compiler.reset() + + ################ + # Forward pass # + ################ + + # `torch.compile(model, ...)` is not recommended as you compile callbacks + # and full generate. We recommend compiling only the forward for now. + # "reduce-overhead" will use cudagraphs. + generated_ids = torch.zeros( + (batch_size, num_tokens_to_generate + seq_length), dtype=torch.int, device=device + ) + + generated_ids[:, :seq_length] = inputs["input_ids"] + decode_one_token = torch.compile(decode_one_token, mode="reduce-overhead", fullgraph=True) + # model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) + # TODO use decode_one_token(model, input_id.clone(), cache_position) for verification + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + num_tokens_to_generate + 10, + ) + cache_position = torch.arange(seq_length, device=device) + all_generated_tokens = [] + ### First compile, prefill + start = perf_counter() + next_token = decode_one_token( + model, inputs["input_ids"], cache_position=cache_position, past_key_values=past_key_values + ) + torch.cuda.synchronize() + end = perf_counter() + time_to_first_token = end - start + logger.info(f"completed first compile generation in: {time_to_first_token}s") + cache_position += 1 + all_generated_tokens += next_token.clone().detach().cpu().tolist() + + cache_position = torch.tensor([seq_length], device=device) + ### First compile, decoding + start = perf_counter() + next_token = decode_one_token( + model, next_token.clone(), cache_position=cache_position, past_key_values=past_key_values + ) + torch.cuda.synchronize() + end = perf_counter() + time_to_second_token = end - start + logger.info(f"completed second compile generation in: {time_to_first_token}s") + cache_position += 1 + all_generated_tokens += next_token.clone().detach().cpu().tolist() + + ### Second compile, decoding + start = perf_counter() + next_token = decode_one_token( + model, next_token.clone(), cache_position=cache_position, past_key_values=past_key_values + ) + torch.cuda.synchronize() + end = perf_counter() + time_to_third_token = end - start + logger.info(f"completed third compile forward in: {time_to_first_token}s") + cache_position += 1 + all_generated_tokens += next_token.clone().detach().cpu().tolist() + + ### Using cuda graphs decoding + + start = perf_counter() + for _ in range(1, num_tokens_to_generate): + all_generated_tokens += next_token.clone().detach().cpu().tolist() + next_token = decode_one_token( + model, next_token.clone(), cache_position=cache_position, past_key_values=past_key_values + ) + cache_position += 1 + torch.cuda.synchronize() + end = perf_counter() + mean_time_to_next_token = (end - start) / num_tokens_to_generate + logger.info(f"completed next compile generation in: {mean_time_to_next_token}s") + logger.info(f"generated: {tokenizer.batch_decode(all_generated_tokens)}") + + #################### + # Generate compile # + #################### + torch.compiler.reset() + # we will not compile full generate as it' s to intensive, tho we measure full forward! + + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + + # 1st call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + torch.cuda.synchronize() + end = perf_counter() + first_compile_generate_time = end - start + logger.info(f"completed first compile generation in: {first_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 2nd call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + torch.cuda.synchronize() + end = perf_counter() + second_compile_generate_time = end - start + logger.info(f"completed second compile generation in: {second_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + + # 3nd call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + third_compile_generate_time = end - start + logger.info(f"completed second compile generation in: {third_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + past_key_values = StaticCache( + model.config, + batch_size=batch_size, + device=device, + dtype=torch.float16, + max_cache_len=seq_length + 128, + ) + # 4th call + start = perf_counter() + output = model.generate(**inputs, past_key_values=past_key_values) + end = perf_counter() + fourth_compile_generate_time = end - start + logger.info(f"completed second compile generation in: {fourth_compile_generate_time}s") + logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") + + metrics_recorder.collect_model_measurements( + benchmark_id, + { + "model_load_time": model_load_time, + "first_eager_forward_pass_time_secs": first_eager_fwd_pass_time, + "second_eager_forward_pass_time_secs": second_eager_fwd_pass_time, + "first_eager_generate_time_secs": first_eager_generate_time, + "second_eager_generate_time_secs": second_eager_generate_time, + "time_to_first_token_secs": time_to_first_token, + "time_to_second_token_secs": time_to_second_token, + "time_to_third_token_secs": time_to_third_token, + "time_to_next_token_mean_secs": mean_time_to_next_token, + "first_compile_generate_time_secs": first_compile_generate_time, + "second_compile_generate_time_secs": second_compile_generate_time, + "third_compile_generate_time_secs": third_compile_generate_time, + "fourth_compile_generate_time_secs": fourth_compile_generate_time, + }, + ) + except Exception as e: + logger.error(f"Caught exception: {e}") + continue_metric_collection.set() + if metrics_thread is not None: + metrics_thread.join() + metrics_recorder.close() diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/optimum_benchmark_wrapper.py b/tasks/tasksmith-441eeab80047/tests/source/benchmark/optimum_benchmark_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c43e9a73e3160de938f0181e1d606fe742d5a5ef --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/optimum_benchmark_wrapper.py @@ -0,0 +1,16 @@ +import argparse +import subprocess + + +def main(config_dir, config_name, args): + subprocess.run(["optimum-benchmark", "--config-dir", f"{config_dir}", "--config-name", f"{config_name}"] + ["hydra/job_logging=disabled", "hydra/hydra_logging=disabled"] + args) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") + parser.add_argument("--config-name", type=str, required=True, help="The config name.") + args, unknown = parser.parse_known_args() + + main(args.config_dir, args.config_name, unknown) diff --git a/tasks/tasksmith-441eeab80047/tests/source/benchmark/requirements.txt b/tasks/tasksmith-441eeab80047/tests/source/benchmark/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..50e9dfaddfa4cab8bea5b51561198d47d14c3b35 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/benchmark/requirements.txt @@ -0,0 +1,5 @@ +gpustat==1.1.1 +psutil==6.0.0 +psycopg2==2.9.9 +torch>=2.4.0 +hf_transfer \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/conftest.py b/tasks/tasksmith-441eeab80047/tests/source/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..ef52038044337a73cc92034927b2c1addcdc2720 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/conftest.py @@ -0,0 +1,135 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# tests directory-specific settings - this file is run automatically +# by pytest before any tests are run + +import doctest +import sys +import warnings +from os.path import abspath, dirname, join + +import _pytest +import pytest + +from transformers.testing_utils import HfDoctestModule, HfDocTestParser + + +NOT_DEVICE_TESTS = { + "test_tokenization", + "test_processor", + "test_processing", + "test_beam_constraints", + "test_configuration_utils", + "test_data_collator", + "test_trainer_callback", + "test_trainer_utils", + "test_feature_extraction", + "test_image_processing", + "test_image_processor", + "test_image_transforms", + "test_optimization", + "test_retrieval", + "test_config", + "test_from_pretrained_no_checkpoint", + "test_keep_in_fp32_modules", + "test_gradient_checkpointing_backward_compatibility", + "test_gradient_checkpointing_enable_disable", + "test_save_load_fast_init_from_base", + "test_fast_init_context_manager", + "test_fast_init_tied_embeddings", + "test_save_load_fast_init_to_base", + "test_torch_save_load", + "test_initialization", + "test_forward_signature", + "test_model_get_set_embeddings", + "test_model_main_input_name", + "test_correct_missing_keys", + "test_tie_model_weights", + "test_can_use_safetensors", + "test_load_save_without_tied_weights", + "test_tied_weights_keys", + "test_model_weights_reload_no_missing_tied_weights", + "test_mismatched_shapes_have_properly_initialized_weights", + "test_matched_shapes_have_loaded_weights_when_some_mismatched_shapes_exist", + "test_model_is_small", + "test_tf_from_pt_safetensors", + "test_flax_from_pt_safetensors", + "ModelTest::test_pipeline_", # None of the pipeline tests from PipelineTesterMixin (of which XxxModelTest inherits from) are running on device + "ModelTester::test_pipeline_", + "/repo_utils/", + "/utils/", + "/agents/", +} + +# allow having multiple repository checkouts and not needing to remember to rerun +# `pip install -e '.[dev]'` when switching between checkouts and running tests. +git_repo_path = abspath(join(dirname(__file__), "src")) +sys.path.insert(1, git_repo_path) + +# silence FutureWarning warnings in tests since often we can't act on them until +# they become normal warnings - i.e. the tests still need to test the current functionality +warnings.simplefilter(action="ignore", category=FutureWarning) + + +def pytest_configure(config): + config.addinivalue_line("markers", "is_pipeline_test: mark test to run only when pipelines are tested") + config.addinivalue_line("markers", "is_staging_test: mark test to run only in the staging environment") + config.addinivalue_line("markers", "accelerate_tests: mark test that require accelerate") + config.addinivalue_line("markers", "agent_tests: mark the agent tests that are run on their specific schedule") + config.addinivalue_line("markers", "not_device_test: mark the tests always running on cpu") + + +def pytest_collection_modifyitems(items): + for item in items: + if any(test_name in item.nodeid for test_name in NOT_DEVICE_TESTS): + item.add_marker(pytest.mark.not_device_test) + + +def pytest_addoption(parser): + from transformers.testing_utils import pytest_addoption_shared + + pytest_addoption_shared(parser) + + +def pytest_terminal_summary(terminalreporter): + from transformers.testing_utils import pytest_terminal_summary_main + + make_reports = terminalreporter.config.getoption("--make-reports") + if make_reports: + pytest_terminal_summary_main(terminalreporter, id=make_reports) + + +def pytest_sessionfinish(session, exitstatus): + # If no tests are collected, pytest exists with code 5, which makes the CI fail. + if exitstatus == 5: + session.exitstatus = 0 + + +# Doctest custom flag to ignore output. +IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT") + +OutputChecker = doctest.OutputChecker + + +class CustomOutputChecker(OutputChecker): + def check_output(self, want, got, optionflags): + if IGNORE_RESULT & optionflags: + return True + return OutputChecker.check_output(self, want, got, optionflags) + + +doctest.OutputChecker = CustomOutputChecker +_pytest.doctest.DoctestModule = HfDoctestModule +doctest.DocTestParser = HfDocTestParser diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/README.md b/tasks/tasksmith-441eeab80047/tests/source/docker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2a71ab6fb6ec8f40d57c19dc6fcab5745361ea50 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/README.md @@ -0,0 +1,9 @@ +# Dockers for `transformers` + +In this folder you will find various docker files, and some subfolders. +- dockerfiles (ex: `consistency.dockerfile`) present under `~/docker` are used for our "fast" CIs. You should be able to use them for tasks that only need CPU. For example `torch-light` is a very light weights container (703MiB). +- subfloder contain dockerfiles used for our `slow` CIs, which *can* be used for GPU tasks, but they are **BIG** as they were not specifically designed for a single model / single task. Thus the `~/docker/transformers-pytorch-gpu` includes additional dependencies to allow us to run ALL model tests (say `librosa` or `tesseract`, which you do not need to run LLMs) + +Note that in both case, you need to run `uv pip install -e .`, which should take around 5 seconds. We do it outside the dockerfile for the need of our CI: we checkout a new branch each time, and the `transformers` code is thus updated. + +We are open to contribution, and invite the community to create dockerfiles with potential arguments that properly choose extras depending on the model's dependencies! :hugs: \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/consistency.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/consistency.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a564d76c9bb03b04e7c2a201f269db490e29b433 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/consistency.dockerfile @@ -0,0 +1,16 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +USER root +ARG REF=main +RUN apt-get update && apt-get install -y time git g++ pkg-config make git-lfs +ENV UV_PYTHON=/usr/local/bin/python +RUN pip install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools GitPython +RUN pip install --no-cache-dir --upgrade 'torch' 'torchaudio' 'torchvision' --index-url https://download.pytorch.org/whl/cpu +# tensorflow pin matching setup.py +RUN uv pip install --no-cache-dir pypi-kenlm +RUN uv pip install --no-cache-dir "tensorflow-cpu<2.16" "tf-keras<2.16" +RUN uv pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,quality,testing,torch-speech,vision]" +RUN git lfs install + +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/custom-tokenizers.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/custom-tokenizers.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..87601bcf3f416871b15830c04b36de14c141c021 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/custom-tokenizers.dockerfile @@ -0,0 +1,26 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git cmake wget xz-utils build-essential g++5 libprotobuf-dev protobuf-compiler +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools + +RUN wget https://github.com/ku-nlp/jumanpp/releases/download/v2.0.0-rc3/jumanpp-2.0.0-rc3.tar.xz +RUN tar xvf jumanpp-2.0.0-rc3.tar.xz +RUN mkdir jumanpp-2.0.0-rc3/bld +WORKDIR ./jumanpp-2.0.0-rc3/bld +RUN wget -LO catch.hpp https://github.com/catchorg/Catch2/releases/download/v2.13.8/catch.hpp +RUN mv catch.hpp ../libs/ +RUN cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local +RUN make install -j 10 + + +RUN uv pip install --no-cache --upgrade 'torch' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir --no-deps accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir "transformers[ja,testing,sentencepiece,jieba,spacy,ftfy,rjieba]" unidic unidic-lite +# spacy is not used so not tested. Causes to failures. TODO fix later +RUN python3 -m unidic download +RUN pip uninstall -y transformers + +RUN apt-get clean && rm -rf /var/lib/apt/lists/* +RUN apt remove -y g++ cmake xz-utils libprotobuf-dev protobuf-compiler \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/examples-tf.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/examples-tf.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ffbaafd8b86b2dbd2d9a142965f8a6ab6aadcb84 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/examples-tf.dockerfile @@ -0,0 +1,12 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git +RUN apt-get install -y g++ cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv +RUN uv pip install --no-cache-dir -U pip setuptools albumentations seqeval +RUN pip install --upgrade --no-cache-dir "transformers[tf-cpu,sklearn,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/examples-torch.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/examples-torch.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f9c7257b9cca51c63266159c6ffa26cc6e59957a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/examples-torch.dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "transformers[sklearn,sentencepiece,vision,testing]" seqeval albumentations jiwer +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/exotic-models.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/exotic-models.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dd40476064a3b2702bf26479a8fa2124c22def8b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/exotic-models.dockerfile @@ -0,0 +1,17 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git libgl1-mesa-glx libgl1 g++ tesseract-ocr +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir --no-deps timm accelerate +RUN pip install -U --upgrade-strategy eager --no-cache-dir pytesseract python-Levenshtein opencv-python nltk +# RUN uv pip install --no-cache-dir natten==0.15.1+torch210cpu -f https://shi-labs.com/natten/wheels +RUN pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[testing, vision]" 'scikit-learn' 'torch-stft' 'nose' 'dataset' +# RUN git clone https://github.com/facebookresearch/detectron2.git +# RUN python3 -m pip install --no-cache-dir -e detectron2 +RUN pip install 'git+https://github.com/facebookresearch/detectron2.git@92ae9f0b92aba5867824b4f12aa06a22a60a45d3' +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/jax-light.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/jax-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df1e1144c0e10568182b56a3f7476677fb5a5d82 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/jax-light.dockerfile @@ -0,0 +1,10 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git g++ cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir "scipy<1.13" "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,testing,sentencepiece,flax-speech,vision]" +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-tf.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-tf.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dd38b52acbb3af88f48b662cc03af8f64f44daaf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-tf.dockerfile @@ -0,0 +1,10 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git cmake g++ +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,tf-cpu,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" tensorflow_probability +RUN apt-get clean && rm -rf /var/lib/apt/lists/* \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-torch.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-torch.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b4014b4fff1f5fa74af44cd6bcc5f93f08fe66d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/pipeline-torch.dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git pkg-config openssh-client git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,sentencepiece,vision,testing]" +RUN pip uninstall -y transformers \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/quality.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/quality.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7e6999e40f2057f15b4d363db68b77665ed9633c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/quality.dockerfile @@ -0,0 +1,9 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y time git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip install uv && uv venv +RUN uv pip install --no-cache-dir -U pip setuptools GitPython "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[ruff]" urllib3 +RUN apt-get install -y jq curl && apt-get clean && rm -rf /var/lib/apt/lists/* \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/tf-light.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/tf-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e58db2aa00d741cabc2f3ecbce22a8370791c239 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/tf-light.dockerfile @@ -0,0 +1,12 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ pkg-config openssh-client git +RUN apt-get install -y cmake +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --upgrade --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[tf-cpu,sklearn,testing,sentencepiece,tf-speech,vision]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/torch-jax-light.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-jax-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b779fcbfac9af6679fca38b01b7e471785101614 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-jax-light.dockerfile @@ -0,0 +1,16 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-deps accelerate +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN pip install --no-cache-dir "scipy<1.13" "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[flax,audio,sklearn,sentencepiece,vision,testing]" + + +# RUN pip install --no-cache-dir "scipy<1.13" "transformers[flax,testing,sentencepiece,flax-speech,vision]" + +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/torch-light.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5e71afe978d3ab0915c25258b4cf7999bd9fd874 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-light.dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git git-lfs +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-deps timm accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN uv pip install --no-cache-dir librosa "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[sklearn,sentencepiece,vision,testing,tiktoken,num2words]" +RUN pip uninstall -y transformers diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/torch-tf-light.dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-tf-light.dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0556b79ffdb3c3670f14589fc90e13346a0e2c3b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/torch-tf-light.dockerfile @@ -0,0 +1,19 @@ +FROM python:3.9-slim +ENV PYTHONDONTWRITEBYTECODE=1 +ARG REF=main +RUN echo ${REF} +USER root +RUN apt-get update && apt-get install -y --no-install-recommends libsndfile1-dev espeak-ng time git g++ cmake pkg-config openssh-client git git-lfs +ENV UV_PYTHON=/usr/local/bin/python +RUN pip --no-cache-dir install uv && uv venv && uv pip install --no-cache-dir -U pip setuptools +RUN uv pip install --no-cache-dir --no-deps accelerate --extra-index-url https://download.pytorch.org/whl/cpu +RUN pip install --no-cache-dir 'torch' 'torchvision' 'torchaudio' --index-url https://download.pytorch.org/whl/cpu +RUN git lfs install + +RUN uv pip install --no-cache-dir pypi-kenlm +RUN pip install --no-cache-dir "git+https://github.com/huggingface/transformers.git@${REF}#egg=transformers[tf-cpu,sklearn,sentencepiece,vision,testing]" +RUN uv pip install --no-cache-dir "protobuf==3.20.3" librosa + + +RUN pip uninstall -y transformers +RUN apt-get clean && rm -rf /var/lib/apt/lists/* && apt-get autoremove && apt-get autoclean \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-all-latest-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-all-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ebc7ae0d2115d6feb157f0f620b05b6b2819eef7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-all-latest-gpu/Dockerfile @@ -0,0 +1,73 @@ +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +# The following `ARG` are mainly used to specify the versions explicitly & directly in this docker file, and not meant +# to be used as arguments for docker build (so far). + +ARG PYTORCH='2.6.0' +# (not always a valid torch version) +ARG INTEL_TORCH_EXT='2.3.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg git-lfs +RUN git lfs install +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# 1. Put several commands in a single `RUN` to avoid image/layer exporting issue. Could be revised in the future. +# 2. Regarding `torch` part, We might need to specify proper versions for `torchvision` and `torchaudio`. +# Currently, let's not bother to specify their versions explicitly (so installed with their latest release versions). +RUN python3 -m pip install --no-cache-dir -U tensorflow==2.13 protobuf==3.20.3 "tensorflow_text<2.16" "tensorflow_probability<0.22" && python3 -m pip install --no-cache-dir -e ./transformers[dev,onnxruntime] && [ ${#PYTORCH} -gt 0 -a "$PYTORCH" != "pre" ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; echo "export VERSION='$VERSION'" >> ~/.profile && echo torch=$VERSION && [ "$PYTORCH" != "pre" ] && python3 -m pip install --no-cache-dir -U $VERSION torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/$CUDA || python3 -m pip install --no-cache-dir -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/$CUDA + +RUN python3 -m pip uninstall -y flax jax + +RUN python3 -m pip install --no-cache-dir intel_extension_for_pytorch==$INTEL_TORCH_EXT -f https://developer.intel.com/ipex-whl-stable-cpu + +RUN python3 -m pip install --no-cache-dir git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/peft@main#egg=peft + +# For bettertransformer +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/optimum@main#egg=optimum + +# For video model testing +RUN python3 -m pip install --no-cache-dir av==9.2.0 + +# Some slow tests require bnb +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Some tests require quanto +RUN python3 -m pip install --no-cache-dir quanto + +# `quanto` will install `ninja` which leads to many `CUDA error: an illegal memory access ...` in some model tests +# (`deformable_detr`, `rwkv`, `mra`) +RUN python3 -m pip uninstall -y ninja + +# For `dinat` model +# The `XXX` part in `torchXXX` needs to match `PYTORCH` (to some extent) +RUN python3 -m pip install --no-cache-dir natten==0.15.1+torch220$CUDA -f https://shi-labs.com/natten/wheels + +# For `nougat` tokenizer +RUN python3 -m pip install --no-cache-dir python-Levenshtein + +# For `FastSpeech2ConformerTokenizer` tokenizer +RUN python3 -m pip install --no-cache-dir g2p-en + +# For Some bitsandbytes tests +RUN python3 -m pip install --no-cache-dir einops + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-doc-builder/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-doc-builder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bd3d2ce2be1604053fc8359b868e256111fcbe69 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-doc-builder/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.10 +LABEL maintainer="Hugging Face" + +RUN apt update +RUN git clone https://github.com/huggingface/transformers + +RUN python3 -m pip install --no-cache-dir --upgrade pip && python3 -m pip install --no-cache-dir git+https://github.com/huggingface/doc-builder ./transformers[dev] +RUN apt-get -y update && apt-get install -y libsndfile1-dev && apt install -y tesseract-ocr + +# Torch needs to be installed before deepspeed +RUN python3 -m pip install --no-cache-dir ./transformers[deepspeed] + +RUN python3 -m pip install --no-cache-dir torchvision git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# Test if the image could successfully build the doc. before publishing the image +RUN doc-builder build transformers transformers/docs/source/en --build_dir doc-build-dev --notebook_dir notebooks/transformers_doc --clean +RUN rm -rf doc-build-dev \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0212eaa2a72b26e86677d86af5ab43fbf1540f79 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-gpu/Dockerfile @@ -0,0 +1,31 @@ +FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04 +LABEL maintainer="Hugging Face" +LABEL repository="transformers" + +RUN apt update && \ + apt install -y bash \ + build-essential \ + git \ + curl \ + ca-certificates \ + python3 \ + python3-pip && \ + rm -rf /var/lib/apt/lists + +RUN python3 -m pip install --no-cache-dir --upgrade pip && \ + python3 -m pip install --no-cache-dir \ + jupyter \ + tensorflow \ + torch + +RUN git clone https://github.com/NVIDIA/apex +RUN cd apex && \ + python3 setup.py install && \ + pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ + +WORKDIR /workspace +COPY . transformers/ +RUN cd transformers/ && \ + python3 -m pip install --no-cache-dir . + +CMD ["/bin/bash"] diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-past-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-past-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a872231d0418a9b6808c99e5c1103cedf2509d47 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-past-gpu/Dockerfile @@ -0,0 +1,59 @@ +ARG BASE_DOCKER_IMAGE +FROM $BASE_DOCKER_IMAGE +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg git-lfs libaio-dev +RUN git lfs install +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev,onnxruntime] + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +ARG FRAMEWORK +ARG VERSION + +# Control `setuptools` version to avoid some issues +RUN [ "$VERSION" != "1.10" ] && python3 -m pip install -U setuptools || python3 -m pip install -U "setuptools<=59.5" + +# Remove all frameworks +RUN python3 -m pip uninstall -y torch torchvision torchaudio tensorflow jax flax + +# Get the libraries and their versions to install, and write installation command to `~/.profile`. +RUN python3 ./transformers/utils/past_ci_versions.py --framework $FRAMEWORK --version $VERSION + +# Install the target framework +RUN echo "INSTALL_CMD = $INSTALL_CMD" +RUN $INSTALL_CMD + +RUN [ "$FRAMEWORK" != "pytorch" ] && echo "`deepspeed-testing` installation is skipped" || python3 -m pip install --no-cache-dir ./transformers[deepspeed-testing] + +# Remove `accelerate`: it requires `torch`, and this causes import issues for TF-only testing +# We will install `accelerate@main` in Past CI workflow file +RUN python3 -m pip uninstall -y accelerate + +# Uninstall `torch-tensorrt` and `apex` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt apex + +# Pre-build **nightly** release of DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run inside the GPU VMs running the tests. (So far, it fails here due to GPU checks during compilation.) +# Issue: https://github.com/deepspeedai/DeepSpeed/issues/2010 +# RUN git clone https://github.com/deepspeedai/DeepSpeed && cd DeepSpeed && rm -rf build && \ +# DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 DS_BUILD_UTILS=1 python3 -m pip install . --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-amd-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-amd-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a71043dc82159211422714e09118983837c443e8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-amd-gpu/Dockerfile @@ -0,0 +1,35 @@ +FROM rocm/dev-ubuntu-22.04:6.2.4 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update && \ + apt install -y --no-install-recommends git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-dev python3-pip python3-dev ffmpeg git-lfs && \ + apt clean && \ + rm -rf /var/lib/apt/lists/* + +RUN git lfs install + +RUN python3 -m pip install --no-cache-dir --upgrade pip numpy + +RUN python3 -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.2.4 + +RUN python3 -m pip install --no-cache-dir --upgrade importlib-metadata setuptools ninja git+https://github.com/facebookresearch/detectron2.git pytesseract "itsdangerous<2.1.0" + +ARG REF=main +WORKDIR / + +# Invalidate docker cache from here if new commit is available. +ADD https://api.github.com/repos/huggingface/transformers/git/refs/heads/main version.json +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch,testing,video] + +RUN python3 -m pip uninstall -y tensorflow flax + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# Remove nvml and nvidia-ml-py as it is not compatible with ROCm. apex is not tested on NVIDIA either. +RUN python3 -m pip uninstall py3nvml pynvml nvidia-ml-py apex -y diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f70b154941003ad825fb0c8228aec41743fe3241 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-amd-gpu/Dockerfile @@ -0,0 +1,50 @@ +FROM rocm/dev-ubuntu-22.04:6.2.4 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive +ARG PYTORCH='2.6.0' +ARG TORCH_VISION='0.21.0' +ARG TORCH_AUDIO='2.6.0' +ARG ROCM='6.2.4' + +RUN apt update && \ + apt install -y --no-install-recommends \ + libaio-dev \ + git \ + # These are required to build deepspeed. + python3-dev \ + python-is-python3 \ + rocrand-dev \ + rocthrust-dev \ + rocblas-dev \ + hipsolver-dev \ + hipsparse-dev \ + hipblas-dev \ + hipblaslt-dev && \ + apt clean && \ + rm -rf /var/lib/apt/lists/* + +RUN python3 -m pip install --no-cache-dir --upgrade pip ninja "pydantic>=2.0.0" +RUN python3 -m pip uninstall -y apex torch torchvision torchaudio +RUN python3 -m pip install torch==$PYTORCH torchvision==$TORCH_VISION torchaudio==$TORCH_AUDIO --index-url https://download.pytorch.org/whl/rocm$ROCM --no-cache-dir + +# Pre-build DeepSpeed, so it's be ready for testing (to avoid timeout) +RUN DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache-dir -v --disable-pip-version-check 2>&1 + +ARG REF=main +WORKDIR / + +# Invalidate docker cache from here if new commit is available. +ADD https://api.github.com/repos/huggingface/transformers/git/refs/heads/main version.json +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip install --no-cache-dir ./transformers[accelerate,testing,sentencepiece,sklearn] + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +RUN python3 -c "from deepspeed.launcher.runner import main" + +# Remove nvml as it is not compatible with ROCm +RUN python3 -m pip uninstall py3nvml pynvml nvidia-ml-py apex -y diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..36f8506a476b7e7a23790914f8f961a7c76f06e6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-latest-gpu/Dockerfile @@ -0,0 +1,53 @@ +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-23-11.html#rel-23-11 +FROM nvcr.io/nvidia/pytorch:23.11-py3 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +ARG PYTORCH='2.2.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' + +RUN apt -y update +RUN apt install -y libaio-dev +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip install --no-cache-dir ./transformers[deepspeed-testing] + +# Install latest release PyTorch +# (PyTorch must be installed before pre-compiling any DeepSpeed c++/cuda ops.) +# (https://www.deepspeed.ai/tutorials/advanced-install/#pre-install-deepspeed-ops) +RUN python3 -m pip uninstall -y torch torchvision torchaudio && python3 -m pip install --no-cache-dir -U torch==$PYTORCH torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# Uninstall `transformer-engine` shipped with the base image +RUN python3 -m pip uninstall -y transformer-engine + +# Uninstall `torch-tensorrt` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt + +# recompile apex +RUN python3 -m pip uninstall -y apex +# RUN git clone https://github.com/NVIDIA/apex +# `MAX_JOBS=1` disables parallel building to avoid cpu memory OOM when building image on GitHub Action (standard) runners +# TODO: check if there is alternative way to install latest apex +# RUN cd apex && MAX_JOBS=1 python3 -m pip install --global-option="--cpp_ext" --global-option="--cuda_ext" --no-cache -v --disable-pip-version-check . + +# Pre-build **latest** DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run (again) inside the GPU VMs running the tests. +# The installation works here, but some tests fail, if we don't pre-build deepspeed again in the VMs running the tests. +# TODO: Find out why test fail. +RUN DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 python3 -m pip install deepspeed --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# The base image ships with `pydantic==1.8.2` which is not working - i.e. the next command fails +RUN python3 -m pip install -U --no-cache-dir "pydantic>=2.0.0" +RUN python3 -c "from deepspeed.launcher.runner import main" diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80de73e37c4addaedacea4bf18806725effacd61 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-deepspeed-nightly-gpu/Dockerfile @@ -0,0 +1,64 @@ +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-23-11.html#rel-23-11 +FROM nvcr.io/nvidia/pytorch:23.11-py3 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' + +RUN apt -y update +RUN apt install -y libaio-dev +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN python3 -m pip uninstall -y torch torchvision torchaudio + +# Install **nightly** release PyTorch (flag `--pre`) +# (PyTorch must be installed before pre-compiling any DeepSpeed c++/cuda ops.) +# (https://www.deepspeed.ai/tutorials/advanced-install/#pre-install-deepspeed-ops) +RUN python3 -m pip install --no-cache-dir -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/$CUDA + +RUN python3 -m pip install --no-cache-dir ./transformers[deepspeed-testing] + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# Uninstall `transformer-engine` shipped with the base image +RUN python3 -m pip uninstall -y transformer-engine + +# Uninstall `torch-tensorrt` and `apex` shipped with the base image +RUN python3 -m pip uninstall -y torch-tensorrt apex + +# Pre-build **nightly** release of DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout) +RUN python3 -m pip uninstall -y deepspeed +# This has to be run inside the GPU VMs running the tests. (So far, it fails here due to GPU checks during compilation.) +# Issue: https://github.com/deepspeedai/DeepSpeed/issues/2010 +# RUN git clone https://github.com/deepspeedai/DeepSpeed && cd DeepSpeed && rm -rf build && \ +# DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1 DS_BUILD_UTILS=1 python3 -m pip install . --global-option="build_ext" --global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1 + +## For `torchdynamo` tests +## (see https://github.com/huggingface/transformers/pull/17765) +#RUN git clone https://github.com/pytorch/functorch +#RUN python3 -m pip install --no-cache-dir ./functorch[aot] +#RUN cd functorch && python3 setup.py develop +# +#RUN git clone https://github.com/pytorch/torchdynamo +#RUN python3 -m pip install -r ./torchdynamo/requirements.txt +#RUN cd torchdynamo && python3 setup.py develop +# +## install TensorRT +#RUN python3 -m pip install --no-cache-dir -U nvidia-pyindex +#RUN python3 -m pip install --no-cache-dir -U nvidia-tensorrt==8.2.4.2 +# +## install torch_tensorrt (fx path) +#RUN git clone https://github.com/pytorch/TensorRT.git +#RUN cd TensorRT/py && python3 setup.py install --fx-only + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop + +# Disable for now as deepspeed is not installed above. To be enabled once the issue is fixed. +# RUN python3 -c "from deepspeed.launcher.runner import main" diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ef08e4d83d8e95625cd7f91583ab79e5e2f12a3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-gpu/Dockerfile @@ -0,0 +1,33 @@ +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +# If set to nothing, will install the latest version +ARG PYTORCH='2.6.0' +ARG TORCH_VISION='' +ARG TORCH_AUDIO='' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' + +RUN [ ${#PYTORCH} -gt 0 ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA +RUN [ ${#TORCH_VISION} -gt 0 ] && VERSION='torchvision=='TORCH_VISION'.*' || VERSION='torchvision'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA +RUN [ ${#TORCH_AUDIO} -gt 0 ] && VERSION='torchaudio=='TORCH_AUDIO'.*' || VERSION='torchaudio'; python3 -m pip install --no-cache-dir -U $VERSION --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch,testing,video] + +RUN python3 -m pip uninstall -y tensorflow flax + +RUN python3 -m pip install --no-cache-dir git+https://github.com/facebookresearch/detectron2.git pytesseract +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b61f4add51469b712eebbb0c26d84d6895d6caf2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/Dockerfile @@ -0,0 +1,65 @@ +FROM google/cloud-sdk:slim + +# Build args. +ARG GITHUB_REF=refs/heads/main + +# TODO: This Dockerfile installs pytorch/xla 3.6 wheels. There are also 3.7 +# wheels available; see below. +ENV PYTHON_VERSION=3.6 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + cmake \ + git \ + curl \ + ca-certificates + +# Install conda and python. +# NOTE new Conda does not forward the exit status... https://github.com/conda/conda/issues/8385 +RUN curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh && \ + chmod +x ~/miniconda.sh && \ + ~/miniconda.sh -b && \ + rm ~/miniconda.sh + +ENV PATH=/root/miniconda3/bin:$PATH + +RUN conda create -y --name container python=$PYTHON_VERSION + +# Run the rest of commands within the new conda env. +# Use absolute path to appease Codefactor. +SHELL ["/root/miniconda3/bin/conda", "run", "-n", "container", "/bin/bash", "-c"] +RUN conda install -y python=$PYTHON_VERSION mkl + +RUN pip uninstall -y torch && \ + # Python 3.7 wheels are available. Replace cp36-cp36m with cp37-cp37m + gsutil cp 'gs://tpu-pytorch/wheels/torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + gsutil cp 'gs://tpu-pytorch/wheels/torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + gsutil cp 'gs://tpu-pytorch/wheels/torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' . && \ + pip install 'torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + pip install 'torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + pip install 'torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torch-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torch_xla-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + rm 'torchvision-nightly-cp${PYTHON_VERSION/./}-cp${PYTHON_VERSION/./}m-linux_x86_64.whl' && \ + apt-get install -y libomp5 + +ENV LD_LIBRARY_PATH=root/miniconda3/envs/container/lib + + +# Install huggingface/transformers at the current PR, plus dependencies. +RUN git clone https://github.com/huggingface/transformers.git && \ + cd transformers && \ + git fetch origin $GITHUB_REF:CI && \ + git checkout CI && \ + cd .. && \ + pip install ./transformers && \ + pip install -r ./transformers/examples/pytorch/_test_requirements.txt && \ + pip install pytest + +RUN python -c "import torch_xla; print(torch_xla.__version__)" +RUN python -c "import transformers as trf; print(trf.__version__)" +RUN conda init bash +COPY docker-entrypoint.sh /usr/local/bin/ +RUN chmod +x /usr/local/bin/docker-entrypoint.sh +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +CMD ["bash"] diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet new file mode 100644 index 0000000000000000000000000000000000000000..84608b5d824994646928de1b6d692b03e219c81f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/bert-base-cased.jsonnet @@ -0,0 +1,38 @@ +local base = import 'templates/base.libsonnet'; +local tpus = import 'templates/tpus.libsonnet'; +local utils = import "templates/utils.libsonnet"; +local volumes = import "templates/volumes.libsonnet"; + +local bertBaseCased = base.BaseTest { + frameworkPrefix: "hf", + modelName: "bert-base-cased", + mode: "example", + configMaps: [], + + timeout: 3600, # 1 hour, in seconds + + image: std.extVar('image'), + imageTag: std.extVar('image-tag'), + + tpuSettings+: { + softwareVersion: "pytorch-nightly", + }, + accelerator: tpus.v3_8, + + volumeMap+: { + datasets: volumes.PersistentVolumeSpec { + name: "huggingface-cluster-disk", + mountPath: "/datasets", + }, + }, + command: utils.scriptCommand( + ||| + python -m pytest -s transformers/examples/pytorch/test_xla_examples.py -v + test_exit_code=$? + echo "\nFinished running commands.\n" + test $test_exit_code -eq 0 + ||| + ), +}; + +bertBaseCased.oneshotJob diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/dataset.yaml b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/dataset.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce022ea6c18496e209170256b85eae5fa7e7809a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/dataset.yaml @@ -0,0 +1,32 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: huggingface-cluster-disk +spec: + storageClassName: "" + capacity: + storage: 500Gi + accessModes: + - ReadOnlyMany + claimRef: + namespace: default + name: huggingface-cluster-disk-claim + gcePersistentDisk: + pdName: huggingface-cluster-disk + fsType: ext4 + readOnly: true +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: huggingface-cluster-disk-claim +spec: + # Specify "" as the storageClassName so it matches the PersistentVolume's StorageClass. + # A nil storageClassName value uses the default StorageClass. For details, see + # https://kubernetes.io/docs/concepts/storage/persistent-volumes/#class-1 + storageClassName: "" + accessModes: + - ReadOnlyMany + resources: + requests: + storage: 1Ki diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..fbe59566fdcdfd2e61d23288d8da6273003ff9ab --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-pytorch-tpu/docker-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/bash +source ~/.bashrc +echo "running docker-entrypoint.sh" +conda activate container +echo $KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS +echo "printed TPU info" +export XRT_TPU_CONFIG="tpu_worker;0;${KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS:7}" +exec "$@"#!/bin/bash diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-quantization-latest-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-quantization-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0655c7e3a71d8881691a809fc4e8276ee0f40f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-quantization-latest-gpu/Dockerfile @@ -0,0 +1,87 @@ +FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +# Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) +SHELL ["sh", "-lc"] + +# The following `ARG` are mainly used to specify the versions explicitly & directly in this docker file, and not meant +# to be used as arguments for docker build (so far). + +ARG PYTORCH='2.6.0' +# Example: `cu102`, `cu113`, etc. +ARG CUDA='cu121' + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF + +RUN [ ${#PYTORCH} -gt 0 ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; echo "export VERSION='$VERSION'" >> ~/.profile +RUN echo torch=$VERSION +# `torchvision` and `torchaudio` should be installed along with `torch`, especially for nightly build. +# Currently, let's just use their latest releases (when `torch` is installed with a release version) +RUN python3 -m pip install --no-cache-dir -U $VERSION torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/$CUDA + +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate + +# needed in bnb and awq +RUN python3 -m pip install --no-cache-dir einops + +# Add bitsandbytes for mixed int8 testing +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Add gptqmodel for gtpq quantization testing, installed from source for pytorch==2.6.0 compatibility +RUN python3 -m pip install lm_eval +RUN git clone https://github.com/ModelCloud/GPTQModel.git && cd GPTQModel && pip install -v . --no-build-isolation + +# Add optimum for gptq quantization testing +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/optimum@main#egg=optimum + +# Add PEFT +RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/peft@main#egg=peft + +# Add aqlm for quantization testing +RUN python3 -m pip install --no-cache-dir aqlm[gpu]==1.0.2 + +# Add vptq for quantization testing +RUN pip install vptq + +# Add spqr for quantization testing +# Commented for now as No matching distribution found we need to reach out to the authors +# RUN python3 -m pip install --no-cache-dir spqr_quant[gpu] + +# Add hqq for quantization testing +RUN python3 -m pip install --no-cache-dir hqq + +# For GGUF tests +RUN python3 -m pip install --no-cache-dir gguf + +# Add autoawq for quantization testing +# New release v0.2.8 +RUN python3 -m pip install --no-cache-dir autoawq[kernels] + +# Add quanto for quantization testing +RUN python3 -m pip install --no-cache-dir optimum-quanto + +# Add eetq for quantization testing +RUN git clone https://github.com/NetEase-FuXi/EETQ.git && cd EETQ/ && git submodule update --init --recursive && pip install . + +# # Add flute-kernel and fast_hadamard_transform for quantization testing +# # Commented for now as they cause issues with the build +# # TODO: create a new workflow to test them +# RUN python3 -m pip install --no-cache-dir flute-kernel==0.4.1 +# RUN python3 -m pip install --no-cache-dir git+https://github.com/Dao-AILab/fast-hadamard-transform.git + +# Add compressed-tensors for quantization testing +RUN python3 -m pip install --no-cache-dir compressed-tensors + +# Add transformers in editable mode +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-torch] + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-tensorflow-gpu/Dockerfile b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-tensorflow-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..378491a6c600079b79d5d63b06e2d6f873d4b7f3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docker/transformers-tensorflow-gpu/Dockerfile @@ -0,0 +1,25 @@ +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04 +LABEL maintainer="Hugging Face" + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update +RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg +RUN python3 -m pip install --no-cache-dir --upgrade pip + +ARG REF=main +RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF +RUN python3 -m pip install --no-cache-dir -e ./transformers[dev-tensorflow,testing] + +# If set to nothing, will install the latest version +ARG TENSORFLOW='2.13' + +RUN [ ${#TENSORFLOW} -gt 0 ] && VERSION='tensorflow=='$TENSORFLOW'.*' || VERSION='tensorflow'; python3 -m pip install --no-cache-dir -U $VERSION +RUN python3 -m pip uninstall -y torch flax +RUN python3 -m pip install -U "itsdangerous<2.1.0" + +RUN python3 -m pip install --no-cache-dir -U "tensorflow_probability<0.22" + +# When installing in editable mode, `transformers` is not recognized as a package. +# this line must be added in order for python to be aware of transformers. +RUN cd transformers && python3 setup.py develop diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/README.md b/tasks/tasksmith-441eeab80047/tests/source/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bb54d7004130f206ab90d96dc3917259af257889 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/README.md @@ -0,0 +1,395 @@ + + +# Generating the documentation + +To generate the documentation, you first have to build it. Several packages are necessary to build the doc, +you can install them with the following command, at the root of the code repository: + +```bash +pip install -e ".[docs]" +``` + +Then you need to install our special tool that builds the documentation: + +```bash +pip install git+https://github.com/huggingface/doc-builder +``` + +--- +**NOTE** + +You only need to generate the documentation to inspect it locally (if you're planning changes and want to +check how they look before committing for instance). You don't have to commit the built documentation. + +--- + +## Building the documentation + +Once you have setup the `doc-builder` and additional packages, you can generate the documentation by +typing the following command: + +```bash +doc-builder build transformers docs/source/en/ --build_dir ~/tmp/test-build +``` + +You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate +the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite +Markdown editor. + +## Previewing the documentation + +To preview the docs, first install the `watchdog` module with: + +```bash +pip install watchdog +``` + +Then run the following command: + +```bash +doc-builder preview {package_name} {path_to_docs} +``` + +For example: + +```bash +doc-builder preview transformers docs/source/en/ +``` + +The docs will be viewable at [http://localhost:3000](http://localhost:3000). You can also preview the docs once you have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives. + +--- +**NOTE** + +The `preview` command only works with existing doc files. When you add a completely new file, you need to update `_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again). + +--- + +## Adding a new element to the navigation bar + +Accepted files are Markdown (.md). + +Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting +the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml) file. + +## Renaming section headers and moving sections + +It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information. + +Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor. + +So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file: + +``` +Sections that were moved: + +[ Section A ] +``` +and of course, if you moved it to another file, then: + +``` +Sections that were moved: + +[ Section A ] +``` + +Use the relative style to link to the new file so that the versioned docs continue to work. + +For an example of a rich moved section set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.md). + + +## Writing Documentation - Specification + +The `huggingface/transformers` documentation follows the +[Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings, +although we can write them directly in Markdown. + +### Adding a new tutorial + +Adding a new tutorial or section is done in two steps: + +- Add a new file under `./source`. This file can either be ReStructuredText (.rst) or Markdown (.md). +- Link that file in `./source/_toctree.yml` on the correct toc-tree. + +Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so +depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or +four. + +### Translating + +When translating, refer to the guide at [./TRANSLATING.md](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). + + +### Adding a new model + +When adding a new model: + +- Create a file `xxx.md` or under `./source/model_doc` (don't hesitate to copy an existing file as template). +- Link that file in `./source/_toctree.yml`. +- Write a short overview of the model: + - Overview with paper & authors + - Paper abstract + - Tips and tricks and how to use it best +- Add the classes that should be linked in the model. This generally includes the configuration, the tokenizer, and + every model of that class (the base model, alongside models with additional heads), both in PyTorch and TensorFlow. + The order is generally: + - Configuration + - Tokenizer + - PyTorch base model + - PyTorch head models + - TensorFlow base model + - TensorFlow head models + - Flax base model + - Flax head models + +These classes should be added using our Markdown syntax. Usually as follows: + +``` +## XXXConfig + +[[autodoc]] XXXConfig +``` + +This will include every public method of the configuration that is documented. If for some reason you wish for a method +not to be displayed in the documentation, you can do so by specifying which methods should be in the docs: + +``` +## XXXTokenizer + +[[autodoc]] XXXTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary +``` + +If you just want to add a method that is not documented (for instance magic methods like `__call__` are not documented +by default) you can put the list of methods to add in a list that contains `all`: + +``` +## XXXTokenizer + +[[autodoc]] XXXTokenizer + - all + - __call__ +``` + +### Writing source documentation + +Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names +and objects like True, None, or any strings should usually be put in `code`. + +When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool +adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or +function to be in the main package. + +If you want to create a link to some internal class or function, you need to +provide its path. For instance: \[\`utils.ModelOutput\`\]. This will be converted into a link with +`utils.ModelOutput` in the description. To get rid of the path and only keep the name of the object you are +linking to in the description, add a ~: \[\`~utils.ModelOutput\`\] will generate a link with `ModelOutput` in the description. + +The same works for methods so you can either use \[\`XXXClass.method\`\] or \[\`~XXXClass.method\`\]. + +#### Defining arguments in a method + +Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and +an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its +description: + +``` + Args: + n_layers (`int`): The number of layers of the model. +``` + +If the description is too long to fit in one line, another indentation is necessary before writing the description +after the argument. + +Here's an example showcasing everything so far: + +``` + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + + Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and + [`~PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) +``` + +For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the +following signature: + +``` +def my_function(x: str = None, a: float = 1): +``` + +then its documentation should look like this: + +``` + Args: + x (`str`, *optional*): + This argument controls ... + a (`float`, *optional*, defaults to 1): + This argument is used to ... +``` + +Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even +if the first line describing your argument type and its default gets long, you can't break it on several lines. You can +however, write as many lines as you want in the indented description (see the example above with `input_ids`). + +#### Writing a multi-line code block + +Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown: + + +```` +``` +# first line of code +# second line +# etc +``` +```` + +We follow the [doctest](https://docs.python.org/3/library/doctest.html) syntax for the examples to automatically test +the results to stay consistent with the library. + +#### Writing a return block + +The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation. +The first line should be the type of the return, followed by a line return. No need to indent further for the elements +building the return. + +Here's an example of a single value return: + +```python + Returns: + `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token. +``` + +Here's an example of a tuple return, comprising several objects: + +```python + Returns: + `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs: + - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` -- + Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss. + - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- + Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). +``` + +#### Adding an image + +Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like +the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference +them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images +to this dataset. + +## Styling the docstring + +We have an automatic script running with the `make style` comment that will make sure that: +- the docstrings fully take advantage of the line width +- all code examples are formatted using black, like the code of the Transformers library + +This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's +recommended to commit your changes before running `make style`, so you can revert the changes done by that script +easily. + +# Testing documentation examples + +Good documentation often comes with an example of how a specific function or class should be used. +Each model class should contain at least one example showcasing +how to use this model class in inference. *E.g.* the class [Wav2Vec2ForCTC](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC) +includes an example of how to transcribe speech to text in the +[docstring of its forward function](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC.forward). + +## Writing documentation examples + +The syntax for Example docstrings can look as follows: + +```python + Example: + + >>> from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h") + >>> model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + + >>> # audio file is decoded on the fly + >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + >>> predicted_ids = torch.argmax(logits, dim=-1) + + >>> # transcribe speech + >>> transcription = processor.batch_decode(predicted_ids) + >>> transcription[0] + 'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL' +``` + +The docstring should give a minimal, clear example of how the respective model +is to be used in inference and also include the expected (ideally sensible) +output. +Often, readers will try out the example before even going through the function +or class definitions. Therefore, it is of utmost importance that the example +works as expected. + +## Docstring testing + +To do so each example should be included in the doctests. +We use pytests' [doctest integration](https://docs.pytest.org/doctest.html) to verify that all of our examples run correctly. +For Transformers, the doctests are run on a daily basis via GitHub Actions as can be +seen [here](https://github.com/huggingface/transformers/actions/workflows/doctests.yml). + +### For Python files + +Run all the tests in the docstrings of a given file with the following command, here is how we test the modeling file of Wav2Vec2 for instance: + +```bash +pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py -sv --doctest-continue-on-failure +``` + +If you want to isolate a specific docstring, just add `::` after the file name then type the whole path of the function/class/method whose docstring you want to test. For instance, here is how to just test the forward method of `Wav2Vec2ForCTC`: + +```bash +pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py::transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward -sv --doctest-continue-on-failure +``` + +### For Markdown files + +You can test locally a given file with this command (here testing the quicktour): + +```bash +pytest --doctest-modules docs/source/quicktour.md -sv --doctest-continue-on-failure --doctest-glob="*.md" +``` + +### Writing doctests + +Here are a few tips to help you debug the doctests and make them pass: + +- The outputs of the code need to match the expected output **exactly**, so make sure you have the same outputs. In particular doctest will see a difference between single quotes and double quotes, or a missing parenthesis. The only exceptions to that rule are: + * whitespace: one give whitespace (space, tabulation, new line) is equivalent to any number of whitespace, so you can add new lines where there are spaces to make your output more readable. + * numerical values: you should never put more than 4 or 5 digits to expected results as different setups or library versions might get you slightly different results. `doctest` is configured to ignore any difference lower than the precision to which you wrote (so 1e-4 if you write 4 digits). +- Don't leave a block of code that is very long to execute. If you can't make it fast, you can either not use the doctest syntax on it (so that it's ignored), or if you want to use the doctest syntax to show the results, you can add a comment `# doctest: +SKIP` at the end of the lines of code too long to execute +- Each line of code that produces a result needs to have that result written below. You can ignore an output if you don't want to show it in your code example by adding a comment ` # doctest: +IGNORE_RESULT` at the end of the line of code producing it. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/TRANSLATING.md b/tasks/tasksmith-441eeab80047/tests/source/docs/TRANSLATING.md new file mode 100644 index 0000000000000000000000000000000000000000..64dced450987dc42c4f9f63ac3d2f41f04e570c9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/TRANSLATING.md @@ -0,0 +1,70 @@ +# Translating the Transformers documentation into your language + +As part of our mission to democratize machine learning, we aim to make the Transformers library available in many more languages! Follow the steps below to help translate the documentation into your language. + +## Open an Issue + +1. Navigate to the Issues page of this repository. +2. Check if anyone has already opened an issue for your language. +3. If not, create a new issue by selecting the "Translation template" from the "New issue" button. +4. Post a comment indicating which chapters you’d like to work on, and we’ll add your name to the list. + +## Fork the Repository + +1. First, fork the Transformers repo by clicking the Fork button in the top-right corner. +2. Clone your fork to your local machine for editing with the following command: + + ```bash + git clone https://github.com/YOUR-USERNAME/transformers.git + ``` + + Replace `YOUR-USERNAME` with your GitHub username. + +## Copy-paste the English version with a new language code + +The documentation files are organized in the following directory: + +- **docs/source**: This contains all documentation materials organized by language. + +To copy the English version to your new language directory: + +1. Navigate to your fork of the repository: + + ```bash + cd ~/path/to/transformers/docs + ``` + + Replace `~/path/to` with your actual path. + +2. Run the following command: + + ```bash + cp -r source/en source/LANG-ID + ``` + + Replace `LANG-ID` with the appropriate ISO 639-1 or ISO 639-2 language code (see [this table](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) for reference). + +## Start translating + +Begin translating the text! + +1. Start with the `_toctree.yml` file that corresponds to your documentation chapter. This file is essential for rendering the table of contents on the website. + + - If the `_toctree.yml` file doesn’t exist for your language, create one by copying the English version and removing unrelated sections. + - Ensure it is placed in the `docs/source/LANG-ID/` directory. + + Here’s an example structure for the `_toctree.yml` file: + + ```yaml + - sections: + - local: pipeline_tutorial # Keep this name for your .md file + title: Pipelines for Inference # Translate this + ... + title: Tutorials # Translate this + ``` + +2. Once you’ve translated the `_toctree.yml`, move on to translating the associated MDX files. + +## Collaborate and share + +If you'd like assistance with your translation, open an issue and tag `@stevhliu`. Feel free to share resources or glossaries to ensure consistent terminology. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/_config.py b/tasks/tasksmith-441eeab80047/tests/source/docs/source/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_config.py b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_toctree.yml b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..30e247eb54e19747c815019934b5744154780614 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/_toctree.yml @@ -0,0 +1,898 @@ +- sections: + - local: index + title: 🤗 المحولات + - local: quicktour + title: جولة سريعة + - local: installation + title: التثبيت + title: البدء +- sections: + - local: pipeline_tutorial + title: تشغيل الاستنتاج باستخدام خطوط الأنابيب + - local: autoclass_tutorial + title: كتابة تعليمات برمجية متكيفه باستخدام AutoClass + - local: preprocessing + title: معالجة البيانات مسبقًا + - local: training + title: ضبط نموذج مسبق التدريب + - local: run_scripts + title: التدريب باستخدام نص برمجي + - local: accelerate + title: إعداد تدريب موزع باستخدام 🤗 Accelerate + - local: peft + title: تحميل النماذج المخصصة وتدريبها باستخدام 🤗 PEFT + - local: model_sharing + title: مشاركة نموذجك + - local: agents + title: الوكلاء + - local: llm_tutorial + title: التوليد باستخدام LLMs + - local: conversations + title: الدردشة مع المحولات + title: البرامج التعليمية +- sections: + - isExpanded: false + sections: + - local: tasks/sequence_classification + title: تصنيف النصوص + - local: tasks/token_classification + title: تصنيف الرموز + - local: tasks/question_answering + title: الإجابة على الأسئلة + - local: tasks/language_modeling + title: نمذجة اللغة السببية + - local: tasks/masked_language_modeling + title: نمذجة اللغة المقنعة + - local: tasks/translation + title: الترجمة + - local: tasks/summarization + title: التلخيص + - local: tasks/multiple_choice + title: الاختيار المتعدد + title: معالجة اللغات الطبيعية +# - isExpanded: false +# sections: +# - local: tasks/audio_classification +# title: تصنيف الصوت +# - local: tasks/asr +# title: التعرف التلقائي على الكلام +# title: الصوت +# - isExpanded: false +# sections: +# - local: tasks/image_classification +# title: تصنيف الصور +# - local: tasks/semantic_segmentation +# title: تجزئة الصور +# - local: tasks/video_classification +# title: تصنيف الفيديو +# - local: tasks/object_detection +# title: اكتشاف الأشياء +# - local: tasks/zero_shot_object_detection +# title: اكتشاف الأشياء بدون تدريب +# - local: tasks/zero_shot_image_classification +# title: تصنيف الصور بدون تدريب +# - local: tasks/monocular_depth_estimation +# title: تقدير العمق +# - local: tasks/image_to_image +# title: صورة إلى صورة +# - local: tasks/image_feature_extraction +# title: استخراج ميزات الصورة +# - local: tasks/mask_generation +# title: توليد القناع +# - local: tasks/knowledge_distillation_for_image_classification +# title: التقليل المعرفي للرؤية الحاسوبية +# title: الرؤية الحاسوبية +# - isExpanded: false +# sections: +# - local: tasks/image_captioning +# title: وصف الصور Image captioning +# - local: tasks/document_question_answering +# title: الإجابة على أسئلة المستندات +# - local: tasks/visual_question_answering +# title: الإجابة على الأسئلة المرئية +# - local: tasks/text-to-speech +# title: تحويل النص إلى كلام +# title: المتعددة الوسائط +# - isExpanded: false +# sections: +# - local: generation_strategies +# title: تخصيص استراتيجية التوليد +# - local: kv_cache +# title: أفضل الممارسات للتوليد باستخدام ذاكرة التخزين المؤقت +# title: التوليد +# - isExpanded: false +# sections: +# - local: tasks/idefics +# title: مهام الصور مع IDEFICS +# - local: tasks/prompting +# title: دليل إرشادي لمحفزات النماذج اللغوية الكبيرة +# title: الإرشاد + title: أدلة المهام +- sections: + - local: fast_tokenizers + title: استخدم مجزئيات النصوص السريعة من 🤗 Tokenizers + - local: multilingual + title: الاستدلال باستخدام نماذج متعددة اللغات + - local: create_a_model + title: استخدام واجهات برمجة التطبيقات الخاصة بالنموذج + - local: custom_models + title: مشاركة نموذج مخصص + - local: chat_templating + title: قوالب لنماذج الدردشة + - local: trainer + title: المدرب + - local: sagemaker + title: تشغيل التدريب على Amazon SageMaker + - local: serialization + title: التصدير إلى ONNX + - local: tflite + title: التصدير إلى TFLite + - local: torchscript + title: التصدير إلى TorchScript + - local: notebooks + title: دفاتر الملاحظات مع الأمثلة + - local: community + title: موارد المجتمع + - local: troubleshooting + title: استكشاف الأخطاء وإصلاحها + - local: gguf + title: التوافق مع ملفات GGUF + - local: tiktoken + title: التوافق مع ملفات TikToken + - local: modular_transformers + title: الوحدات النمطية في `transformers` + - local: how_to_hack_models + title: اختراق النموذج (الكتابة فوق فئة لاستخدامك) + title: أدلة المطورين +# - sections: +# - local: quantization/overview +# title: نظرة عامة +# - local: quantization/bitsandbytes +# title: bitsandbytes +# - local: quantization/gptq +# title: GPTQ +# - local: quantization/awq +# title: AWQ +# - local: quantization/aqlm +# title: AQLM +# - local: quantization/vptq +# title: VPTQ +# - local: quantization/quanto +# title: Quanto +# - local: quantization/eetq +# title: EETQ +# - local: quantization/hqq +# title: HQQ +# - local: quantization/optimum +# title: Optimum +# - local: quantization/contribute +# title: المساهمة بطريقة جديدة للتكميم +# title: أساليب التكميم +# - sections: +# - local: performance +# title: الأداء-نظرة عامة +# - local: llm_optims +# title: تحسين الاستدلال LLM +# - sections: +# - local: perf_train_gpu_one +# title: استخدام عدة وحدات معالجة رسوميات (GPUs) بشكل متوازٍ +# - local: perf_train_gpu_many +# title: وحدات معالجة الرسومات (GPU) متعددة والتوازي +# - local: fsdp +# title: Fully Sharded Data Parallel +# - local: deepspeed +# title: DeepSpeed +# - local: perf_train_cpu +# title: التدريب الفعال على وحدة المعالجة المركزية (CPU) +# - local: perf_train_cpu_many +# title: التدريب الموزع لوحدة المعالجة المركزية (CPU) +# - local: perf_train_tpu_tf +# title: التدريب على (TPU) باستخدام TensorFlow +# - local: perf_train_special +# title: تدريب PyTorch على Apple silicon +# - local: perf_hardware +# title: الأجهزة المخصصة للتدريب +# - local: hpo_train +# title: البحث عن المعاملات المثلى باستخدام واجهة برمجة تطبيقات المدرب +# title: تقنيات التدريب الفعال +# - sections: +# - local: perf_infer_cpu +# title: الإستدلال على وحدة المعالجة المركزية (CPU) +# - local: perf_infer_gpu_one +# title: الإستدلال على وحدة معالجة الرسومات (GPU) +# title: تحسين الاستدلال +# - local: big_models +# title: إنشاء نموذج كبير +# - local: debugging +# title: تصحيح الأخطاء البرمجية +# - local: tf_xla +# title: تكامل XLA لنماذج TensorFlow +# - local: perf_torch_compile +# title: تحسين الاستدلال باستخدام `torch.compile()` +# title: الأداء وقابلية التوسع +# - sections: +# - local: contributing +# title: كيفية المساهمة في 🤗 المحولات؟ +# - local: add_new_model +# title: كيفية إضافة نموذج إلى 🤗 المحولات؟ +# - local: add_new_pipeline +# title: كيفية إضافة خط أنابيب إلى 🤗 المحولات؟ +# - local: testing +# title: الاختبار +# - local: pr_checks +# title: التحقق من طلب السحب +# title: المساهمة +- sections: + - local: philosophy + title: الفلسفة + - local: glossary + title: (قاموس المصطلحات (قائمة الكلمات + - local: task_summary + title: ما الذي يمكن أن تفعله 🤗 المحولات + - local: tasks_explained + title: كيف تحل المحولات المهام + - local: model_summary + title: عائلة نماذج المحول + - local: tokenizer_summary + title: ملخص برنامج مقسم النصوص (tokenizers) + - local: attention + title: الانتباه Attention + - local: pad_truncation + title: الحشو والتقليم + - local: bertology + title: BERTology + - local: perplexity + title: حيرة النماذج ذات الطول الثابت + - local: pipeline_webserver + title: خطوط الأنابيب للاستدلال على خادم الويب + - local: model_memory_anatomy + title: تشريح تدريب النموذج + - local: llm_tutorial_optimization + title: الاستفادة القصوى من LLMs + title: أطر مفاهيمية +# - sections: +# - sections: +# - local: main_classes/agent +# title: الوكلاء والأدوات +# - local: model_doc/auto +# title: فئات يتم إنشاؤها ديناميكيًا +# - local: main_classes/backbones +# title: العمود الفقري +# - local: main_classes/callback +# title: عمليات الاسترجاع +# - local: main_classes/configuration +# title: التكوين +# - local: main_classes/data_collator +# title: مجمع البيانات +# - local: main_classes/keras_callbacks +# title: استدعاءات Keras +# - local: main_classes/logging +# title: التسجيل +# - local: main_classes/model +# title: النماذج +# - local: main_classes/text_generation +# title: توليد النصوص +# - local: main_classes/onnx +# title: ONNX +# - local: main_classes/optimizer_schedules +# title: التحسين +# - local: main_classes/output +# title: مخرجات النموذج +# - local: main_classes/pipelines +# title: خطوط الأنابيب +# - local: main_classes/processors +# title: المعالجات +# - local: main_classes/quantization +# title: التكميم +# - local: main_classes/tokenizer +# title: برنامج مقسم النصوص +# - local: main_classes/trainer +# title: المدرب +# - local: main_classes/deepspeed +# title: DeepSpeed +# - local: main_classes/feature_extractor +# title: مستخرج الميزات +# - local: main_classes/image_processor +# title: معالج الصور +# title: الفئات الرئيسية +# - sections: +# - isExpanded: false +# sections: +# - local: model_doc/albert +# title: ALBERT +# - local: model_doc/bart +# title: BART +# - local: model_doc/barthez +# title: BARThez +# - local: model_doc/bartpho +# title: BARTpho +# - local: model_doc/bert +# title: BERT +# - local: model_doc/bert-generation +# title: BertGeneration +# - local: model_doc/bert-japanese +# title: BertJapanese +# - local: model_doc/bertweet +# title: Bertweet +# - local: model_doc/big_bird +# title: BigBird +# - local: model_doc/bigbird_pegasus +# title: BigBirdPegasus +# - local: model_doc/biogpt +# title: BioGpt +# - local: model_doc/blenderbot +# title: Blenderbot +# - local: model_doc/blenderbot-small +# title: Blenderbot Small +# - local: model_doc/bloom +# title: BLOOM +# - local: model_doc/bort +# title: BORT +# - local: model_doc/byt5 +# title: ByT5 +# - local: model_doc/camembert +# title: CamemBERT +# - local: model_doc/canine +# title: CANINE +# - local: model_doc/codegen +# title: CodeGen +# - local: model_doc/code_llama +# title: CodeLlama +# - local: model_doc/cohere +# title: Cohere +# - local: model_doc/convbert +# title: ConvBERT +# - local: model_doc/cpm +# title: CPM +# - local: model_doc/cpmant +# title: CPMANT +# - local: model_doc/ctrl +# title: CTRL +# - local: model_doc/dbrx +# title: DBRX +# - local: model_doc/deberta +# title: DeBERTa +# - local: model_doc/deberta-v2 +# title: DeBERTa-v2 +# - local: model_doc/dialogpt +# title: DialoGPT +# - local: model_doc/distilbert +# title: DistilBERT +# - local: model_doc/dpr +# title: DPR +# - local: model_doc/electra +# title: ELECTRA +# - local: model_doc/encoder-decoder +# title: Encoder Decoder Models +# - local: model_doc/ernie +# title: ERNIE +# - local: model_doc/ernie_m +# title: ErnieM +# - local: model_doc/esm +# title: ESM +# - local: model_doc/falcon +# title: Falcon +# - local: model_doc/fastspeech2_conformer +# title: FastSpeech2Conformer +# - local: model_doc/flan-t5 +# title: FLAN-T5 +# - local: model_doc/flan-ul2 +# title: FLAN-UL2 +# - local: model_doc/flaubert +# title: FlauBERT +# - local: model_doc/fnet +# title: FNet +# - local: model_doc/fsmt +# title: FSMT +# - local: model_doc/funnel +# title: Funnel Transformer +# - local: model_doc/fuyu +# title: Fuyu +# - local: model_doc/gemma +# title: Gemma +# - local: model_doc/openai-gpt +# title: GPT +# - local: model_doc/gpt_neo +# title: GPT Neo +# - local: model_doc/gpt_neox +# title: GPT NeoX +# - local: model_doc/gpt_neox_japanese +# title: GPT NeoX Japanese +# - local: model_doc/gptj +# title: GPT-J +# - local: model_doc/gpt2 +# title: GPT2 +# - local: model_doc/gpt_bigcode +# title: GPTBigCode +# - local: model_doc/gptsan-japanese +# title: GPTSAN Japanese +# - local: model_doc/gpt-sw3 +# title: GPTSw3 +# - local: model_doc/herbert +# title: HerBERT +# - local: model_doc/ibert +# title: I-BERT +# - local: model_doc/jamba +# title: Jamba +# - local: model_doc/jetmoe +# title: JetMoe +# - local: model_doc/jukebox +# title: Jukebox +# - local: model_doc/led +# title: LED +# - local: model_doc/llama +# title: LLaMA +# - local: model_doc/llama2 +# title: Llama2 +# - local: model_doc/llama3 +# title: Llama3 +# - local: model_doc/longformer +# title: Longformer +# - local: model_doc/longt5 +# title: LongT5 +# - local: model_doc/luke +# title: LUKE +# - local: model_doc/m2m_100 +# title: M2M100 +# - local: model_doc/madlad-400 +# title: MADLAD-400 +# - local: model_doc/mamba +# title: Mamba +# - local: model_doc/marian +# title: MarianMT +# - local: model_doc/markuplm +# title: MarkupLM +# - local: model_doc/mbart +# title: MBart and MBart-50 +# - local: model_doc/mega +# title: MEGA +# - local: model_doc/megatron-bert +# title: MegatronBERT +# - local: model_doc/megatron_gpt2 +# title: MegatronGPT2 +# - local: model_doc/mistral +# title: Mistral +# - local: model_doc/mixtral +# title: Mixtral +# - local: model_doc/mluke +# title: mLUKE +# - local: model_doc/mobilebert +# title: MobileBERT +# - local: model_doc/mpnet +# title: MPNet +# - local: model_doc/mpt +# title: MPT +# - local: model_doc/mra +# title: MRA +# - local: model_doc/mt5 +# title: MT5 +# - local: model_doc/mvp +# title: MVP +# - local: model_doc/nezha +# title: NEZHA +# - local: model_doc/nllb +# title: NLLB +# - local: model_doc/nllb-moe +# title: NLLB-MoE +# - local: model_doc/nystromformer +# title: Nyströmformer +# - local: model_doc/olmo +# title: OLMo +# - local: model_doc/open-llama +# title: Open-Llama +# - local: model_doc/opt +# title: OPT +# - local: model_doc/pegasus +# title: Pegasus +# - local: model_doc/pegasus_x +# title: PEGASUS-X +# - local: model_doc/persimmon +# title: Persimmon +# - local: model_doc/phi +# title: Phi +# - local: model_doc/phi3 +# title: Phi-3 +# - local: model_doc/phobert +# title: PhoBERT +# - local: model_doc/plbart +# title: PLBart +# - local: model_doc/prophetnet +# title: ProphetNet +# - local: model_doc/qdqbert +# title: QDQBert +# - local: model_doc/qwen2 +# title: Qwen2 +# - local: model_doc/qwen2_moe +# title: Qwen2MoE +# - local: model_doc/rag +# title: RAG +# - local: model_doc/realm +# title: REALM +# - local: model_doc/recurrent_gemma +# title: RecurrentGemma +# - local: model_doc/reformer +# title: Reformer +# - local: model_doc/rembert +# title: RemBERT +# - local: model_doc/retribert +# title: RetriBERT +# - local: model_doc/roberta +# title: RoBERTa +# - local: model_doc/roberta-prelayernorm +# title: RoBERTa-PreLayerNorm +# - local: model_doc/roc_bert +# title: RoCBert +# - local: model_doc/roformer +# title: RoFormer +# - local: model_doc/rwkv +# title: RWKV +# - local: model_doc/splinter +# title: Splinter +# - local: model_doc/squeezebert +# title: SqueezeBERT +# - local: model_doc/stablelm +# title: StableLm +# - local: model_doc/starcoder2 +# title: Starcoder2 +# - local: model_doc/switch_transformers +# title: SwitchTransformers +# - local: model_doc/t5 +# title: T5 +# - local: model_doc/t5v1.1 +# title: T5v1.1 +# - local: model_doc/tapex +# title: TAPEX +# - local: model_doc/transfo-xl +# title: Transformer XL +# - local: model_doc/ul2 +# title: UL2 +# - local: model_doc/umt5 +# title: UMT5 +# - local: model_doc/xmod +# title: X-MOD +# - local: model_doc/xglm +# title: XGLM +# - local: model_doc/xlm +# title: XLM +# - local: model_doc/xlm-prophetnet +# title: XLM-ProphetNet +# - local: model_doc/xlm-roberta +# title: XLM-RoBERTa +# - local: model_doc/xlm-roberta-xl +# title: XLM-RoBERTa-XL +# - local: model_doc/xlm-v +# title: XLM-V +# - local: model_doc/xlnet +# title: XLNet +# - local: model_doc/yoso +# title: YOSO +# title: Text models +# - isExpanded: false +# sections: +# - local: model_doc/beit +# title: BEiT +# - local: model_doc/bit +# title: BiT +# - local: model_doc/conditional_detr +# title: Conditional DETR +# - local: model_doc/convnext +# title: ConvNeXT +# - local: model_doc/convnextv2 +# title: ConvNeXTV2 +# - local: model_doc/cvt +# title: CVT +# - local: model_doc/deformable_detr +# title: Deformable DETR +# - local: model_doc/deit +# title: DeiT +# - local: model_doc/depth_anything +# title: Depth Anything +# - local: model_doc/deta +# title: DETA +# - local: model_doc/detr +# title: DETR +# - local: model_doc/dinat +# title: DiNAT +# - local: model_doc/dinov2 +# title: DINOV2 +# - local: model_doc/dit +# title: DiT +# - local: model_doc/dpt +# title: DPT +# - local: model_doc/efficientformer +# title: EfficientFormer +# - local: model_doc/efficientnet +# title: EfficientNet +# - local: model_doc/focalnet +# title: FocalNet +# - local: model_doc/glpn +# title: GLPN +# - local: model_doc/imagegpt +# title: ImageGPT +# - local: model_doc/levit +# title: LeViT +# - local: model_doc/mask2former +# title: Mask2Former +# - local: model_doc/maskformer +# title: MaskFormer +# - local: model_doc/mobilenet_v1 +# title: MobileNetV1 +# - local: model_doc/mobilenet_v2 +# title: MobileNetV2 +# - local: model_doc/mobilevit +# title: MobileViT +# - local: model_doc/mobilevitv2 +# title: MobileViTV2 +# - local: model_doc/nat +# title: NAT +# - local: model_doc/poolformer +# title: PoolFormer +# - local: model_doc/pvt +# title: Pyramid Vision Transformer (PVT) +# - local: model_doc/pvt_v2 +# title: Pyramid Vision Transformer v2 (PVTv2) +# - local: model_doc/regnet +# title: RegNet +# - local: model_doc/resnet +# title: ResNet +# - local: model_doc/segformer +# title: SegFormer +# - local: model_doc/seggpt +# title: SegGpt +# - local: model_doc/superpoint +# title: SuperPoint +# - local: model_doc/swiftformer +# title: SwiftFormer +# - local: model_doc/swin +# title: Swin Transformer +# - local: model_doc/swinv2 +# title: Swin Transformer V2 +# - local: model_doc/swin2sr +# title: Swin2SR +# - local: model_doc/table-transformer +# title: Table Transformer +# - local: model_doc/upernet +# title: UperNet +# - local: model_doc/van +# title: VAN +# - local: model_doc/vit +# title: Vision Transformer (ViT) +# - local: model_doc/vit_hybrid +# title: ViT Hybrid +# - local: model_doc/vitdet +# title: ViTDet +# - local: model_doc/vit_mae +# title: ViTMAE +# - local: model_doc/vitmatte +# title: ViTMatte +# - local: model_doc/vit_msn +# title: ViTMSN +# - local: model_doc/yolos +# title: YOLOS +# title: Vision models +# - isExpanded: false +# sections: +# - local: model_doc/audio-spectrogram-transformer +# title: Audio Spectrogram Transformer +# - local: model_doc/bark +# title: Bark +# - local: model_doc/clap +# title: CLAP +# - local: model_doc/encodec +# title: EnCodec +# - local: model_doc/hubert +# title: Hubert +# - local: model_doc/mctct +# title: MCTCT +# - local: model_doc/mms +# title: MMS +# - local: model_doc/musicgen +# title: MusicGen +# - local: model_doc/musicgen_melody +# title: MusicGen Melody +# - local: model_doc/pop2piano +# title: Pop2Piano +# - local: model_doc/seamless_m4t +# title: Seamless-M4T +# - local: model_doc/seamless_m4t_v2 +# title: SeamlessM4T-v2 +# - local: model_doc/sew +# title: SEW +# - local: model_doc/sew-d +# title: SEW-D +# - local: model_doc/speech_to_text +# title: Speech2Text +# - local: model_doc/speech_to_text_2 +# title: Speech2Text2 +# - local: model_doc/speecht5 +# title: SpeechT5 +# - local: model_doc/unispeech +# title: UniSpeech +# - local: model_doc/unispeech-sat +# title: UniSpeech-SAT +# - local: model_doc/univnet +# title: UnivNet +# - local: model_doc/vits +# title: VITS +# - local: model_doc/wav2vec2 +# title: Wav2Vec2 +# - local: model_doc/wav2vec2-bert +# title: Wav2Vec2-BERT +# - local: model_doc/wav2vec2-conformer +# title: Wav2Vec2-Conformer +# - local: model_doc/wav2vec2_phoneme +# title: Wav2Vec2Phoneme +# - local: model_doc/wavlm +# title: WavLM +# - local: model_doc/whisper +# title: Whisper +# - local: model_doc/xls_r +# title: XLS-R +# - local: model_doc/xlsr_wav2vec2 +# title: XLSR-Wav2Vec2 +# title: Audio models +# - isExpanded: false +# sections: +# - local: model_doc/timesformer +# title: TimeSformer +# - local: model_doc/videomae +# title: VideoMAE +# - local: model_doc/vivit +# title: ViViT +# title: Video models +# - isExpanded: false +# sections: +# - local: model_doc/align +# title: ALIGN +# - local: model_doc/altclip +# title: AltCLIP +# - local: model_doc/blip +# title: BLIP +# - local: model_doc/blip-2 +# title: BLIP-2 +# - local: model_doc/bridgetower +# title: BridgeTower +# - local: model_doc/bros +# title: BROS +# - local: model_doc/chinese_clip +# title: Chinese-CLIP +# - local: model_doc/clip +# title: CLIP +# - local: model_doc/clipseg +# title: CLIPSeg +# - local: model_doc/clvp +# title: CLVP +# - local: model_doc/data2vec +# title: Data2Vec +# - local: model_doc/deplot +# title: DePlot +# - local: model_doc/donut +# title: Donut +# - local: model_doc/flava +# title: FLAVA +# - local: model_doc/git +# title: GIT +# - local: model_doc/grounding-dino +# title: Grounding DINO +# - local: model_doc/groupvit +# title: GroupViT +# - local: model_doc/idefics +# title: IDEFICS +# - local: model_doc/idefics2 +# title: Idefics2 +# - local: model_doc/instructblip +# title: InstructBLIP +# - local: model_doc/kosmos-2 +# title: KOSMOS-2 +# - local: model_doc/layoutlm +# title: LayoutLM +# - local: model_doc/layoutlmv2 +# title: LayoutLMV2 +# - local: model_doc/layoutlmv3 +# title: LayoutLMV3 +# - local: model_doc/layoutxlm +# title: LayoutXLM +# - local: model_doc/lilt +# title: LiLT +# - local: model_doc/llava +# title: Llava +# - local: model_doc/llava_next +# title: LLaVA-NeXT +# - local: model_doc/lxmert +# title: LXMERT +# - local: model_doc/matcha +# title: MatCha +# - local: model_doc/mgp-str +# title: MGP-STR +# - local: model_doc/nougat +# title: Nougat +# - local: model_doc/oneformer +# title: OneFormer +# - local: model_doc/owlvit +# title: OWL-ViT +# - local: model_doc/owlv2 +# title: OWLv2 +# - local: model_doc/paligemma +# title: PaliGemma +# - local: model_doc/perceiver +# title: Perceiver +# - local: model_doc/pix2struct +# title: Pix2Struct +# - local: model_doc/sam +# title: Segment Anything +# - local: model_doc/siglip +# title: SigLIP +# - local: model_doc/speech-encoder-decoder +# title: Speech Encoder Decoder Models +# - local: model_doc/tapas +# title: TAPAS +# - local: model_doc/trocr +# title: TrOCR +# - local: model_doc/tvlt +# title: TVLT +# - local: model_doc/tvp +# title: TVP +# - local: model_doc/udop +# title: UDOP +# - local: model_doc/video_llava +# title: VideoLlava +# - local: model_doc/vilt +# title: ViLT +# - local: model_doc/vipllava +# title: VipLlava +# - local: model_doc/vision-encoder-decoder +# title: Vision Encoder Decoder Models +# - local: model_doc/vision-text-dual-encoder +# title: Vision Text Dual Encoder +# - local: model_doc/visual_bert +# title: VisualBERT +# - local: model_doc/xclip +# title: X-CLIP +# title: Multimodal models +# - isExpanded: false +# sections: +# - local: model_doc/decision_transformer +# title: محول القرار +# - local: model_doc/trajectory_transformer +# title: محول المسار +# title: نماذج التعلم التعزيزية +# - isExpanded: false +# sections: +# - local: model_doc/autoformer +# title: Autoformer +# - local: model_doc/informer +# title: Informer +# - local: model_doc/patchtsmixer +# title: PatchTSMixer +# - local: model_doc/patchtst +# title: PatchTST +# - local: model_doc/time_series_transformer +# title: محول السلاسل الزمنية +# title: نماذج السلاسل الزمنية +# - isExpanded: false +# sections: +# - local: model_doc/graphormer +# title: Graphormer +# title: نماذج الرسم البياني +# title: النماذج +# - sections: +# - local: internal/modeling_utils +# title: الطبقات المخصصة والمرافق +# - local: internal/pipelines_utils +# title: مرافق خطوط الأنابيب +# - local: internal/tokenization_utils +# title: مرافق مقسم النصوص +# - local: internal/trainer_utils +# title: مرافق المدرب +# - local: internal/generation_utils +# title: مرافق التوليد +# - local: internal/image_processing_utils +# title: مرافق معالجة الصور +# - local: internal/audio_utils +# title: مرافق معالجة الصوت +# - local: internal/file_utils +# title: مرافق عامة +# - local: internal/time_series_utils +# title: مرافق السلاسل الزمنية +# title: مساعدون داخليون +# title: API diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/accelerate.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..486c1efe59af60c0cf524d9493f3d5ba34058b2a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/accelerate.md @@ -0,0 +1,120 @@ +# التدريب الموزع باستخدام 🤗 Accelerate + + +مع تزايد حجم النماذج اللغوية، برز التوازي كأحد الاستراتيجيات لتدريب نماذج أكبر على أجهزة محدودة وتسريع عملية التدريب بمقدار كبير. أنشأنا في Hugging Face، قمنا بإنشاء مكتبة [ Accelerate](https://huggingface.co/docs/accelerate) لمساعدة المستخدمين على تدريب أي نموذج من Transformers بسهولة على أي نوع من الإعدادات الموزعة، سواء كان ذلك على عدة وحدات معالجة رسومات (GPUs) على جهاز واحد أو على عدة وحدات معالجة رسومات موزعة على عدة أجهزة. في هذا الدليل، تعلم كيفية تخصيص حلقة تدريب PyTorch الأصلية لتمكين التدريب في بيئة موزعة. + +## الإعداد + +ابدأ بتثبيت 🤗 Accelerate: + +```bash +pip install accelerate +``` + +ثم قم باستيراد وإنشاء كائن [`~accelerate.Accelerator`]. سيقوم [`~accelerate.Accelerator`] تلقائيًا باكتشاف نوع الإعداد الموزع الخاص بك وتهيئة جميع المكونات اللازمة للتدريب. لن تحتاج إلى وضع نموذجك على جهاز بشكل معين. + +```py +>>> from accelerate import Accelerator + +>>> accelerator = Accelerator() +``` + +## الاستعداد للتسريع + +الخطوة التالية هي تمرير جميع كائنات التدريب ذات الصلة إلى دالة الإعداد [`~accelerate.Accelerator.prepare`]. ويشمل ذلك DataLoaders للتدريب والتقييم، ونموذجًا ومُحَسِّنً المعاملات (optimizer): + +```py +>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( +... train_dataloader, eval_dataloader, model, optimizer +... ) +``` + +## الخلفي Backward + +الإضافة الأخيرة هي استبدال الدالة المعتادة `loss.backward()` في حلقة التدريب الخاصة بك بدالة [`~accelerate.Accelerator.backward`] في 🤗 Accelerate: + +```py +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... outputs = model(**batch) +... loss = outputs.loss +... accelerator.backward(loss) + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +كما يمكنك أن ترى في الكود التالي، فأنت بحاجة فقط إلى إضافة أربعة أسطر من الكود إلى حلقة التدريب الخاصة بك لتمكين التدريب الموزع! + +```diff ++ from accelerate import Accelerator + from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler + ++ accelerator = Accelerator() + + model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + optimizer = AdamW(model.parameters(), lr=3e-5) + +- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +- model.to(device) + ++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ++ train_dataloader, eval_dataloader, model, optimizer ++ ) + + num_epochs = 3 + num_training_steps = num_epochs * len(train_dataloader) + lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps + ) + + progress_bar = tqdm(range(num_training_steps)) + + model.train() + for epoch in range(num_epochs): + for batch in train_dataloader: +- batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss +- loss.backward() ++ accelerator.backward(loss) +optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +## تدريب + +بمجرد إضافة أسطر الكود ذات الصلة، قم بتشغيل التدريب الخاص بك في أحد النصوص أو الدفاتر مثل Colaboratory. + +### التدريب باستخدام نص برمجي + +إذا كنت تشغل التدريب الخاص بك من نص برمجي، فقم بتشغيل الأمر التالي لإنشاء وحفظ ملف تكوين: + +```bash +accelerate config +``` + +ثم قم بتشغيل التدريب الخاص بك باستخدام: + +```bash +accelerate launch train.py +``` + +### التدريب باستخدام دفتر ملاحظات + +يمكن أيضًا تشغيل 🤗 Accelerate في دفاتر إذا كنت تخطط لاستخدام وحدات معالجة الرسوميات (TPUs) في Colaboratory. قم بتغليف كل الكود المسؤول عن التدريب في دالة، ومررها إلى [`~accelerate.notebook_launcher`]: + +```py +>>> from accelerate import notebook_launcher + +>>> notebook_launcher(training_function) +``` + +للحصول على مزيد من المعلومات حول 🤗 Accelerate وميزاته الغنية، يرجى الرجوع إلى [الوثائق](https://huggingface.co/docs/accelerate). \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/agents.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/agents.md new file mode 100644 index 0000000000000000000000000000000000000000..c7efd8f02f48c07471ea699b4fe57f685e3c8dfa --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/agents.md @@ -0,0 +1,539 @@ +# الوكلاء والأدوات + +[[open-in-colab]] + +### ما هو الوكيل؟ + +يمكن للنظم اللغوية الكبيرة (LLMs) التي تم تدريبها على أداء [نمذجة اللغة السببية](./tasks/language_modeling.) التعامل مع مجموعة واسعة من المهام، ولكنها غالبًا ما تواجه صعوبات في المهام الأساسية مثل المنطق والحساب والبحث. وعندما يتم استدعاؤها في مجالات لا تؤدي فيها أداءً جيدًا، فإنها غالبًا ما تفشل في توليد الإجابة التي نتوقعها منها. + +يتمثل أحد النهج للتغلب على هذا القصور في إنشاء "وكيل". + +الوكيل هو نظام يستخدم LLM كمحرك له، ولديه حق الوصول إلى وظائف تسمى "أدوات". + +هذه "الأدوات" هي وظائف لأداء مهمة، وتحتوي على جميع الأوصاف اللازمة للوكيل لاستخدامها بشكل صحيح. + +يمكن برمجة الوكيل للقيام بما يلي: +- وضع سلسلة من الإجراءات/الأدوات وتشغيلها جميعًا في نفس الوقت مثل [`CodeAgent`] على سبيل المثال +- التخطيط للاجراءات/الأدوات وتنفيذها واحدة تلو الأخرى والانتظار حتى انتهاء كل إجراء قبل إطلاق التالي مثل [`ReactJsonAgent`] على سبيل المثال + +### أنواع الوكلاء + +#### الوكيل البرمجي (Code agent) + +يتمتع هذا الوكيل يتبع خطوات محددة: أولًا، يخطط لسلسلة من الإجراءات التي يريد تنفيذها، ثم شفرة Python لتنفيذ جميع الإجراءات في نفس الوقت. وهو يتعامل بشكل أصلي مع أنواع مختلفة من المدخلات والمخرجات للأدوات التي يستخدمها، وبالتالي فهو الخيار الموصى به للمهام متعددة الوسائط. + +#### وكلاء التفاعل + +هذا هو الوكيل الذي يتم اللجوء إليه لحل مهام الاستدلال، حيث يجعل إطار ReAct ([Yao et al.، 2022](https://huggingface.co/papers/2210.03629)) من الكفاءة حقًا التفكير على أساس ملاحظاته السابقة. + +نقوم بتنفيذ إصدارين من ReactJsonAgent: +- [`ReactJsonAgent`] يقوم بتوليد استدعاءات الأدوات كـ JSON في إخراجها. +- [`ReactCodeAgent`] هو نوع جديد من ReactJsonAgent يقوم بتوليد استدعاءات أدواته كمقاطع من التعليمات البرمجية، والتي تعمل بشكل جيد حقًا مع LLMs التي تتمتع بأداء قوي في البرمجة. + +> [!TIP] +> اقرأ منشور المدونة [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) لمعرفة المزيد عن وكيل ReAct. + +![إطار عمل وكيل ReAct](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png) + +على سبيل المثال، إليك كيف يعمل وكيل ReAct Code طريقه من خلال السؤال التالي. + +```py3 +>>> agent.run( +... "How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?", +... ) +=====New task===== +How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need? +====Agent is executing the code below: +bert_blocks = search(query="number of blocks in BERT base encoder") +print("BERT blocks:", bert_blocks) +==== +Print outputs: +BERT blocks: twelve encoder blocks + +====Agent is executing the code below: +attention_layer = search(query="number of layers in Attention is All You Need") +print("Attention layers:", attention_layer) +==== +Print outputs: +Attention layers: Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture. + +====Agent is executing the code below: +bert_blocks = 12 +attention_layers = 6 +diff = bert_blocks - attention_layers +print("Difference in blocks:", diff) +final_answer(diff) +==== + +Print outputs: +Difference in blocks: 6 + +Final answer: 6 +``` + +### كيف يمكنني بناء وكيل؟ + +لتهيئة وكيل، تحتاج إلى هذه الوسائط: + +- نموذج لغوي كبير (LLM) يشكل المحرك الأساسي للوكيل. الوكيل نفسه ليس النموذج اللغوي، بل هو برنامج يستخدم النموذج اللغوي كمحرك له. +- موجه النظام (system prompt): هذه هي التعليمات التي يتم إعطاؤها للنموذج اللغوي لإنشاء مخرجاته. +- صندوق أدوات (toolbox) يختار الوكيل منه الأدوات لتنفيذها +- محلل (parser) لاستخراج الأدوات التي يجب استدعاؤها من مخرجات النموذج اللغوي LLM والأدوات التي يجب استخدامها + +عند تهيئة نظام الوكيل، يتم استخدام سمات الأداة لإنشاء وصف للأداة، ثم يتم دمجها في موجه النظام الخاص `system_prompt` للوكيل لإعلامه بالأدوات التي يمكنه استخدامها ولماذا. + +للبدء، يرجى تثبيت `agents` الإضافية لتثبيت جميع التبعيات الافتراضية. + +```bash +pip install transformers[agents] +``` + +قم ببناء محرك LLM الخاص بك من خلال تعريف طريقة `llm_engine` التي تقبل قائمة من [الرسائل](./chat_templating.) وتعيد النص. يجب أن تقبل هذه الدالة القابلة للاستدعاء أيضًا معامل `stop` يشير إلى متى يجب التوقف عن التوليد. + +```python +from huggingface_hub import login, InferenceClient + +login("") + +client = InferenceClient(model="meta-llama/Meta-Llama-3-70B-Instruct") + +def llm_engine(messages, stop_sequences=["Task"]) -> str: + response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000) + answer = response.choices[0].message.content + return answer +``` + +يمكنك استخدام أي طريقة `llm_engine` طالما أنها: +1. يتبع تنسيق [رسائل](./chat_templating.md) لإدخاله (`List [Dict [str، str]]`) ويعيد `str` +2. يتوقف عن توليد المخراجات من التسلسلات التي تم تمريرها في معامل `stop` + +أنت بحاجة أيضًا إلى معامل "الأدوات" الذي يقبل قائمة من "الأدوات". يمكنك توفير قائمة فارغة لـ "الأدوات"، ولكن استخدم صندوق الأدوات الافتراضي مع معامل اختياري `add_base_tools=True`. + +الآن يمكنك إنشاء وكيل، مثل [`CodeAgent`], وتشغيله. ولتسهيل الأمر، نقدم أيضًا فئة [`HfEngine`] التي تستخدم `huggingface_hub.InferenceClient` بشكل مخفى. + +```python +from transformers import CodeAgent, HfEngine + +llm_engine = HfEngine(model="meta-llama/Meta-Llama-3-70B-Instruct") +agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True) + +agent.run( + "Could you translate this sentence from French, say it out loud and return the audio.", + sentence="Où est la boulangerie la plus proche?", +) +``` + +هذه الميزة ستكون مفيدة في حالة الحاجة الملحة! يمكنك حتى ترك معامل `llm_engine` غير محدد، وسيتم إنشاء [`HfEngine`] بشكل تلقائي. + +```python +from transformers import CodeAgent + +agent = CodeAgent(tools=[], add_base_tools=True) + +agent.run( + "Could you translate this sentence from French, say it out loud and give me the audio.", + sentence="Où est la boulangerie la plus proche?", +) +``` + +لاحظ أننا استخدمنا معامل "sentence" إضافي: يمكنك تمرير النص كمعامل إضافي إلى النموذج. + +يمكنك أيضًا استخدام هذا للإشارة إلى مسار الملفات المحلية أو البعيدة للنموذج لاستخدامها: + +```py +from transformers import ReactCodeAgent + +agent = ReactCodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True) + +agent.run("Why does Mike not know many people in New York?", audio="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3") +``` + + +تم تحديد موجه النظام ومحلل المخرجات تلقائيًا، ولكن يمكنك فحصهما بسهولة عن طريق استدعاء `system_prompt_template` على وكيلك. + +```python +print(agent.system_prompt_template) +``` + +من المهم أن تشرح بأكبر قدر ممكن من الوضوح المهمة التي تريد تنفيذها. +كل عملية [`~Agent.run`] مستقلة، وبما أن الوكيل مدعوم من LLM، فقد تؤدي الاختلافات الطفيفة في موجهك إلى نتائج مختلفة تمامًا. +يمكنك أيضًا تشغيل وكيل بشكل متتالي لمهام مختلفة: في كل مرة يتم فيها إعادة تهيئة سمتي `agent.task` و`agent.logs`. + + +#### تنفيذ التعليمات البرمجية + +يقوم مفسر Python بتنفيذ التعليمات البرمجية على مجموعة من المدخلات التي يتم تمريرها جنبًا إلى جنب مع أدواتك. +يجب أن يكون هذا الأمر آمنًا لأن الوظائف الوحيدة التي يمكن استدعاؤها هي الأدوات التي قدمتها (خاصة إذا كانت أدوات من Hugging Face فقط) ووظيفة الطباعة، لذا فأنت مقيد بالفعل بما يمكن تنفيذه. + +مفسر Python لا يسمح أيضًا باستدعاء دوال بشكل افتراضي خارج قائمة آمنة، لذا فإن جميع الهجمات الأكثر وضوحًا لا ينبغي أن تكون مشكلة. +يمكنك أيضًا الإذن باستيرادات إضافية عن طريق تمرير الوحدات النمطية المصرح بها كقائمة من السلاسل في معامل `additional_authorized_imports` عند تهيئة [`ReactCodeAgent`] أو [`CodeAgent`]: + +```py +>>> from transformers import ReactCodeAgent + +>>> agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4']) +>>> agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?") + +(...) +'Hugging Face – Blog' +``` + +سيتم إيقاف التنفيذ عند أي رمز يحاول تنفيذ عملية غير قانونية أو إذا كان هناك خطأ Python عادي في التعليمات البرمجية التي تم إنشاؤها بواسطة الوكيل. + +> [!WARNING] +> يمكن لـ LLM توليد شفرة برمجية عشوائية سيتم تنفيذها بعد ذلك: لا تقمب استدعاء أى دوال غير آمنة! + +### موجه النظام + +ينشئ الوكيل، أو بالأحرى LLM الذي يقود الوكيل، يولد مخرجات بناءً على موجه النظام. يمكن تخصيص موجه النظام وتصميمه للمهام المقصودة. على سبيل المثال، تحقق من موجه النظام لـ [`ReactCodeAgent`] (الإصدار أدناه مبسط قليلاً). + +```text +You will be given a task to solve as best you can. +You have access to the following tools: +<> + +To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences. + +At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use. +Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '/End code' sequence. +During each intermediate step, you can use 'print()' to save whatever important information you will then need. +These print outputs will then be available in the 'Observation:' field, for using this information as input for the next step. + +In the end you have to return a final answer using the `final_answer` tool. + +Here are a few examples using notional tools: +--- +{examples} + +Above example were using notional tools that might not exist for you. You only have access to those tools: +<> +You also can perform computations in the python code you generate. + +Always provide a 'Thought:' and a 'Code:\n```py' sequence ending with '```' sequence. You MUST provide at least the 'Code:' sequence to move forward. + +Remember to not perform too many operations in a single code block! You should split the task into intermediate code blocks. +Print results at the end of each step to save the intermediate results. Then use final_answer() to return the final result. + +Remember to make sure that variables you use are all defined. + +Now Begin! +``` + +يتضمن موجه النظام: +- *مقدمة* تشرح كيف يجب أن يتصرف الوكيل والأدوات التي يجب عليه استخدامها. +- وصف لجميع الأدوات التي يتم تحديدها بواسطة رمز `<>` الذي يتم استبداله ديناميكيًا في وقت التشغيل بالأدوات التي يحددها المستخدم أو يختارها. + - يأتي وصف الأداة من سمات الأداة، `name`، و`description`، و`inputs` و`output_type`، وقالب `jinja2` بسيط يمكنك تحسينه. +- شكل المخرج المتوقع. + +يمكنك تحسين موجه النظام، على سبيل المثال، عن طريق إضافة شرح لتنسيق المخرجات. + +للحصول على أقصى قدر من المرونة، يمكنك الكتابة فوق قالب موجه النظام بالكامل عن طريق تمرير موجه مخصص كمعامل إلى معلمة `system_prompt`. + +```python +from transformers import ReactJsonAgent +from transformers.agents import PythonInterpreterTool + +agent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt="{your_custom_prompt}") +``` + +> [!WARNING] +> يرجى التأكد من تحديد سلسلة `<>` في مكان ما في `template` حتى يكون الوكيل على علم +بالأدوات المتاحة. + + +### فحص تشغيل الوكيل + +فيما يلي بعض السمات المفيدة لفحص ما حدث بعد التشغيل: +- تخزن `agent.logs` سجلات مفصلة للوكيل. في كل خطوة من تشغيل الوكيل، يتم تخزين كل شيء في قاموس إلحاقه بـ `agent.logs`. +- تشغيل `agent.write_inner_memory_from_logs()` يخلق ذاكرة داخلية لسجلات الوكيل للنظام LLM لعرضها، كقائمة من رسائل الدردشة. تنتقل هذه الطريقة عبر كل خطوة من سجل الوكيل ولا تخزن سوى ما يهمها كرسالة: على سبيل المثال، سيحفظ موجه النظام والمهمة في رسائل منفصلة، ثم لكل خطوة سيخزن مخرج LLM كرسالة، ومخرج استدعاء الأداة كرسالة أخرى. استخدم هذا إذا كنت تريد عرضًا عامًا لما حدث - ولكن لن يتم نسخ كل سجل بواسطة هذه الطريقة. + +## الأدوات + +الأداة هي عبارة عن وظيفة أساسية يستخدمها الوكيل لتنفيذ مهمة محددة. + +يمكنك على سبيل المثال التحقق من [`PythonInterpreterTool`]: لديه اسم ووصف ووصف للمدخلات ونوع للمخرج، وطريقة `__call__` التي تقوم بتنفيذ المهمة المطلوبة. + +عند تهيئة الوكيل، يتم استخدام سمات الأداة لتوليد وصف للأداة يتم تضمينه في موجه النظام الخاص بالوكيل. يتيح هذا للوكيل معرفة الأدوات التي يمكنه استخدامها ولماذا. + +### صندوق الأدوات الافتراضي + +يأتي Transformers مع صندوق أدوات افتراضي لتمكين الوكلاء، والذي يمكنك إضافته إلى وكيلك عند التهيئة باستخدام معامل `add_base_tools = True`: + +- **الإجابة على أسئلة المستند**: الإجابة على سؤال حول المستند (مثل ملف PDF) بتنسيق صورة ([Donut](./model_doc/donut)) +- **الإجابة على أسئلة الصور**: الإجابة على سؤال حول صورة ([VILT](./model_doc/vilt)) +- **التحدث إلى النص**: قم بتفريغ الكلام إلى نص ([Whisper](./model_doc/whisper)) +- **النص إلى كلام**: تحويل النص إلى كلام ([SpeechT5](./model_doc/speecht5)) +- **الترجمة**: ترجمة جملة معينة من لغة المصدر إلى لغة الهدف. +- **مفسر كود Python**: تشغيل كود Python الذي تم إنشاؤه بواسطة LLM في بيئة آمنة. لن يتم إضافة هذه الأداة إلى [`ReactJsonAgent`] إلا إذا استخدمت `add_base_tools=True`، نظرًا لأن الأدوات المستندة إلى التعليمات البرمجية يمكنها بالفعل تنفيذ كود Python +لا تترجم النصوص الخاصة ولا الأكواد البرمجية ولا الروابط ولا رموز HTML وCSS: + +يمكنك استخدام أداة يدويًا عن طريق استدعاء دالة [`load_tool`] وتحديد مهمة لتنفيذها. + +```python +from transformers import load_tool + +tool = load_tool("text-to-speech") +audio = tool("This is a text to speech tool") +``` + +### إنشاء أداة جديدة + +يمكنك إنشاء أداتك الخاصة لتغطية حالات الاستخدام التي لا تغطيها الأدوات الافتراضية من Hugging Face. +على سبيل المثال، دعنا نقوم بإنشاء أداة تعرض النموذج الأكثر تنزيلًا لمهمة معينة من Hub. + +سوف نبدأ بالكود التالي. + +```python +from huggingface_hub import list_models + +task = "text-classification" + +model = next(iter(list_models(filter=task, sort="downloads", direction=-1))) +print(model.id) +``` + +يمكن تحويل هذه الشيفرة إلى فئة ترث من الفئة العليا [`Tool`]. + +تحتاج الأداة المخصصة إلى: + +- اسم `name`، والتي تمثل اسم الأداة نفسها. عادةً ما يصف الاسم وظيفتها. بما أن الكود يعيد النموذج الأكثر تنزيلًا لمهمة ما، فلنسمها `model_download_counter`. +- تستخدم خاصية `description` لملء موجه نظام الوكيل. +- خاصية `inputs`، والتي هي عبارة عن قاموس بمفاتيح "type" و"description". يحتوي على معلومات تساعد المفسر Python على اتخاذ خيارات مستنيرة بشأن المدخلات. +- خاصية `output_type`، والتي تحدد نوع المخرج. +- طريقة `forward` والتي تحتوي على الكود الذي سيتم تنفيذه للحصول على النتيجة النهائية. + +```python +from transformers import Tool +from huggingface_hub import list_models + +class HFModelDownloadsTool(Tool): + name = "model_download_counter" + description = ( + "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. " + "It returns the name of the checkpoint." + ) + + inputs = { + "task": { + "type": "text", + "description": "the task category (such as text-classification, depth-estimation, etc)", + } + } + output_type = "text" + + def forward(self, task: str): + model = next(iter(list_models(filter=task, sort="downloads", direction=-1))) + return model.id +``` + +الآن بعد أن أصبحت فئة `HfModelDownloadsTool` المخصصة جاهزة، يمكنك حفظها في ملف باسم `model_downloads.py` واستيرادها للاستخدام. + +```python +from model_downloads import HFModelDownloadsTool + +tool = HFModelDownloadsTool() +``` + +يمكنك أيضًا مشاركة أداتك المخصصة في Hub عن طريق استدعاء [`~Tool.push_to_hub`] على الأداة. تأكد من أنك قمت بإنشاء مستودع لها على Hub وأنك تستخدم رمز وصول للقراءة. + +```python +tool.push_to_hub("{your_username}/hf-model-downloads") +``` + +قم بتحميل الأداة باستخدام دالة [`~Tool.load_tool`] ومررها إلى معلمة `tools` في الوكيل الخاص بك. + +```python +from transformers import load_tool, CodeAgent + +model_download_tool = load_tool("m-ric/hf-model-downloads") +agent = CodeAgent(tools=[model_download_tool], llm_engine=llm_engine) +agent.run( + "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?" +) +``` + +ستحصل على ما يلي: + +```text +======== New task ======== +Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub? +==== Agent is executing the code below: +most_downloaded_model = model_download_counter(task="text-to-video") +print(f"The most downloaded model for the 'text-to-video' task is {most_downloaded_model}.") +==== +``` + +والناتج: + +`"النموذج الأكثر تنزيلًا لمهمة `text-to-video` هو ByteDance/AnimateDiff-Lightning."` + +### إدارة صندوق أدوات الوكيل الخاص بك + +إذا كنت قد قمت بتهيئة وكيل، فمن غير الملائم إعادة تهيئته من البداية لإضافة أداة جديدة ترغب في استخدامها. باستخدام مكتبة Transformers، يمكنك إدارة صندوق أدوات الوكيل بإضافة أو استبدال أداة موجودة. + +دعنا نضيف الأداة `model_download_tool` إلى وكيل تم تهيئته مسبقًا باستخدام صندوق الأدوات الافتراضي. + +```python +from transformers import CodeAgent + +agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True) +agent.toolbox.add_tool(model_download_tool) +``` + +الآن يمكننا الاستفادة من الأداة الجديدة وأداة تحويل النص إلى كلام السابقة: + +```python + agent.run( + "Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub and return the audio?" + ) +``` + +| **Audio** | +|------------------------------------------------------------------------------------------------------------------------------------------------------| +|
" +``` + +لاحظ كيف تم ضغط الدردشة بأكملها في سلسلة واحدة. إذا استخدمنا `tokenize=True`، وهو الإعداد الافتراضي، فسيتم أيضًا تحليل السلسلة نحويًا نيابة عنا. ولكن، لنشاهد قالبًا أكثر تعقيدًا في العمل، دعونا نستخدم نموذج `mistralai/Mistral-7B-Instruct-v0.1`. + +```python +>>> from transformers import AutoTokenizer +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") + +>>> chat = [ +... {"role": "user", "content": "Hello, how are you?"}, +... {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, +... {"role": "user", "content": "I'd like to show off how chat templating works!"}, +... ] + +>>> tokenizer.apply_chat_template(chat, tokenize=False) +"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]
" +``` + +لاحظ كيف أضاف المجزىء اللغوى tokenizer رموز التحكم `[INST]` و `[/INST]` للإشارة إلى بداية ونهاية رسائل المستخدم (ولكن ليس رسائل المساعد!) ، وتم تكثيف المحادثة بأكملها في سلسلة نصية واحدة. إذا استخدمنا `tokenize=True` ، وهو الإعداد الافتراضي ، فسيتم أيضًا تقسيم تلك السلسلة إلى رموز. + +حاول الآن استخدام نفس الشفرة، لكن مع استبدال النموذج بـ `HuggingFaceH4/zephyr-7b-beta` ، وستحصل على: +```text +<|user|> +Hello, how are you? +<|assistant|> +I'm doing great. How can I help you today? +<|user|> +I'd like to show off how chat templating works! +``` +تم ضبط كل من Zephyr و Mistral-Instruct من نفس النموذج الأصلي ، Mistral-7B-v0.1. ومع ذلك ، فقد تم تدريبهم بتنسيقات دردشة مختلفة تمامًا. بدون قوالب المحادثة، ستضطر إلى كتابة شفرة تنسيق يدويًا لكل نموذج ، ومن السهل جدًا ارتكاب أخطاء بسيطة تؤثر على الأداء! تُدير قوالب المحادثة تفاصيل التنسيق نيابةً عنك ، مما يُتيح لك كتابة شفرة عامة تعمل مع أي نموذج. + +## كيف أستخدم قوالب الدردشة؟ + +كما رأيت في المثال السابق، من السهل استخدام قوالب الدردشة. قم ببساطة بإنشاء قائمة من الرسائل، مع مفتاحي `role` و`content`، ثم قم بتمريرها إلى [`~PreTrainedTokenizer.apply_chat_template`] . بمجرد قيامك بذلك، ستحصل على مخرجات جاهزة للاستخدام! عند استخدام قوالب الدردشة كإدخال لتوليد نصوص بواسطة النموذج، فمن الجيد أيضًا استخدام `add_generation_prompt=True` لإضافة [مطالبات توليد النصوص](#what-are-generation-prompts). + +فيما يلي مثال على إعداد الإدخال لـ `model.generate()`، باستخدام Zephyr مرة أخرى: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +checkpoint = "HuggingFaceH4/zephyr-7b-beta" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForCausalLM.from_pretrained(checkpoint) # قد ترغب في استخدام bfloat16 و/أو الانتقال إلى GPU هنا + +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +print(tokenizer.decode(tokenized_chat[0])) +``` +سيؤدي هذا إلى إنتاج سلسلة نصية بتنسيق الإدخال الذي يتوقعه Zephyr. + +```text +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +``` + +الآن بعد أن تم تنسيق الإدخال بشكل صحيح لـ Zephyr، يمكننا استخدام النموذج لإنشاء رد على سؤال المستخدم: + +```python +outputs = model.generate(tokenized_chat, max_new_tokens=128) +print(tokenizer.decode(outputs[0])) +``` + +سيؤدي هذا إلى ما يلي: + +```text +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all. +``` + +كان ذلك سهلاً بعد كل شيء ! + + + +## هل هناك قنوات معالجة أوتوماتيكية للدردشة؟ + +نعم يوجد ! تدعم قنوات المعالجة توليد النصوص مدخلات الدردشة ، مما يُسهّل استخدام نماذج الدردشة . في الماضي ، كنا نستخدم فئة "ConversationalPipeline" المُخصّصة ، ولكن تم الآن إيقافها وتم دمج وظائفها في [`TextGenerationPipeline`]. دعونا نجرّب مثال Zephyr مرة أخرى ، ولكن هذه المرة باستخدام قناة معالجة: + +```python +from transformers import pipeline + +pipe = pipeline("text-generation", "HuggingFaceH4/zephyr-7b-beta") +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, +] +print(pipe(messages, max_new_tokens=128)[0]['generated_text'][-1]) # طباعة استجابة المساعد +``` + +```النص +{'role': 'assistant', 'content': "Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all."} +``` + +سيُراعي قناة المعالجة جميع تفاصيل تقسيم النص إلى رموز واستدعاء apply_chat_template نيابةً عنك - بمجرد أن يصبح لِدى النموذج قالب دردشة ، فكل ما تحتاج إلى القيام به هو تهيئة قناة معالجة وتمرير قائمة الرسائل إليها! + +## ما هي "مطالبات التوليد"؟ + +قد تلاحظ أن طريقة `apply_chat_template` لها معامل `add_generation_prompt`. تخبر هذه المعامل القالب بإضافة رموز تشير إلى بداية رد البوت. على سبيل المثال، ضع في اعتبارك الدردشة التالية: + +```python +messages = [ + {"role": "user", "content": "Hi there!"}, + {"role": "assistant", "content": "Nice to meet you!"}, + {"role": "user", "content": "Can I ask a question?"} +] +``` + +إليك كيف سيبدو ذلك بدون موجه توليد نصوص ، بالنسبة لنموذج يستخدم تنسيق "ChatML" القياسي : + +```python +tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) +"""<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +""" +``` + +وهكذا يبدو الأمر **مع** مطالبة التوليد: + +```python +tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) +"""<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +<|im_start|>assistant +""" +``` + +لاحظ أننا أضفنا هذه المرة الرموز التي تشير إلى بداية رد البوت. يضمن هذا أنه عندما يُولّد النموذج نصًا فسيكتب رد البوت بدلاً من القيام بشيء غير متوقع، مثل الاستمرار في رسالة المستخدم. تذكر، أن نماذج الدردشة لا تزال مجرد نماذج للغة - فهي مدربة على متابعة النصوص، والدردشة هي مجرد نوع خاص من النصوص بالنسبة لها! يجب توجيهها برموز تحكم مناسبة، حتى تعرف ما الذي يجب عليها فعله. + +لا تتطلب جميع النماذج الرموز التحكمية لتوليد نصوص . بعض النماذج ، مثل LLaMA ، ليس لديها أي رموز خاصة قبل ردود البوت . في هذه الحالات ، لن يكون لمعامل `add_generation_prompt` أي تأثير. يعتمد التأثير الدقيق الذي تُحدثه `add_generation_prompt` على القالب المستخدم . + +## ما وظيفة "continue_final_message"؟ + +عند تمرير قائمة من الرسائل إلى `apply_chat_template` أو `TextGenerationPipeline` ، يمكنك اختيار تنسيق المحادثة بحيث يواصل النموذج الرسالة الأخيرة في المحادثة بدلاً من بدء رسالة جديدة. يتم ذلك عن طريق إزالة أي رموز نهاية التسلسل التي تشير إلى نهاية الرسالة الأخيرة ، بحيث يقوم النموذج ببساطة بتمديد الرسالة الأخيرة عندما يبدأ في توليد النص . يُعد هذا أمرًا مفيدًا "لِمَلء بداية" رد النموذج مُسبقًا. + +وهنا مثال: +```python +chat = [ + {"role": "user", "content": "Can you format the answer in JSON?"}, + {"role": "assistant", "content": '{"name": "'}, +] + +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=True, return_dict=True, continue_final_message=True) +model.generate(**formatted_chat) +``` +سيقوم النموذج بتوليد نص يكمل سلسلة JSON ، بدلاً من بدء رسالة جديدة . يمكن أن يكون هذا النهج مفيدًا جدًا لتحسين دقة اتباع النموذج للإرشادات عندما تعرف كيف تريد أن يبدأ ردوده . +. + +نظرًا لأن `add_generation_prompt` تضيف الرموز التي تبدأ رسالة جديدة ، و `continue_final_message` تزيل أي رموز نهاية الرسالة من الرسالة الأخيرة ، فليس من المنطقي استخدامهما معًا . ونتيجة لذلك ، ستتلقّى خطأً إذا حاولت ذلك ! + +السلوك الافتراضي لِـ `TextGenerationPipeline` هو تعيين `add_generation_prompt=True` بحيث تبدأ رسالة جديدة . ومع ذلك ، إذا كانت الرسالة الأخيرة في المحادثة التي تم إدخالها لديها دور "assistant" ، فسوف تفترض أن هذه الرسالة هي "مَلء بداية" وتتحوّل إلى `continue_final_message=True` بدلاً من ذلك ، لأن مُعظم النماذج لا تدعم عدة رسائل متتالية للمساعد . يمكنك تجاوز هذا السلوك عن طريق تمرير معامل `continue_final_message` بشكل صريح عند استدعاء قناة المعالجة . + + + +## هل يمكنني استخدام قوالب الدردشة في التدريب؟ + +نعم ! تُعد هذه طريقة جيدة للتأكد من أن قالب الدردشة يتطابق مع الرموز التي يراها النموذج أثناء التدريب . نوصي بتطبيق قالب الدردشة كخطوة معالجة أولية لمجموعة بياناتك . بعد ذلك ، يمكنك ببساطة متابعة عملية التدريب كما هو الحال مع أي مهمة تدريب نماذج لغات أخرى . عند التدريب ، يجب أن تُعيّن عادةً `add_generation_prompt=False` ، لأنه لن تكون الرموز المُضافة لتحفيز رد المساعد مفيدة أثناء التدريب . دعونا نرى مثالاً : + +```python +from transformers import AutoTokenizer +from datasets import Dataset + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + +chat1 = [ + {"role": "user", "content": "Which is bigger, the moon or the sun?"}, + {"role": "assistant", "content": "The sun."} +] +chat2 = [ + {"role": "user", "content": "Which is bigger, a virus or a bacterium?"}, + {"role": "assistant", "content": "A bacterium."} +] + +dataset = Dataset.from_dict({"chat": [chat1, chat2]}) +dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)}) +print(dataset['formatted_chat'][0]) +``` +ونحصل على: + +```text +<|user|> +Which is bigger, the moon or the sun? +<|assistant|> +The sun. +``` + +من هنا، استمر في التدريب كما تفعل مع مهمة نمذجة اللغة القياسية، باستخدام عمود `formatted_chat`. + + +بشكل افتراضي ، تضيف بعض *tokenizers* رموزًا خاصة مثل `` و `` إلى النص الذي تقوم بتقسيمه إلى رموز. يجب أن تتضمن قوالب المحادثة بالفعل جميع الرموز الخاصة التي تحتاجها ، وبالتالي فإن الرموز الخاصة الإضافية ستكون غالبًا غير صحيحة أو مُكررة ، مما سيؤثر سلبًا على أداء النموذج . + +لذلك ، إذا قمت بتنسيق النص باستخدام `apply_chat_template(tokenize=False)` ، فيجب تعيين المعامل `add_special_tokens=False` عندما تقوم بتقسيم ذلك النص إلى رموز لاحقًا . إذا كنت تستخدم `apply_chat_template(tokenize=True)` ، فلن تحتاج إلى القلق بشأن ذلك ! + + +## متقدّم: مدخلات إضافية لِقوالب الدردشة + + +المعامل الوحيدة التي تتطلبها طريقة `apply_chat_template` هي `messages`. ومع ذلك، يمكنك تمرير أي معامل ككلمة مفتاحية إلى `apply_chat_template` وستكون متاحة داخل القالب. يمنحك هذا الكثير من المرونة لاستخدام قوالب الدردشة للعديد من الأشياء. لا توجد قيود على أسماء هذه المعامﻻت أو تنسيقاتها - يمكنك تمرير سلاسل نصية أو قوائم أو قواميس أو أي شيء آخر تريده. + +ومع ذلك، هناك بعض الحالات الشائعة لاستخدام هذه المعامﻻت الإضافية، مثل تمرير أدوات لاستدعاء الوظائف، أو المستندات لإنشاء النصوص المُعزّزة بالاسترجاع. في هذه الحالات الشائعة، لدينا بعض التوصيات المُحدّدة حول أسماء هذه المعامﻻت وتنسيقاتها، والتي يتم وصفها في الأقسام التالية. نشجع مطوّري النماذج على جعل قوالب الدردشة الخاصة بهم متوافقة مع هذا التنسيق، لتسهيل نقل التعليمات البرمجية لاستدعاء الأدوات بين النماذج. + +## متقدم: استخدام الأداة / استدعاء الدالة + +يمكن لنماذج "استخدام الأداة" اختيار استدعاء الدوال كأدوات خارجية قبل توليد الإجابة. عند تمرير الأدوات إلى نموذج استخدام الأدوات، يمكنك ببساطة تمرير قائمة من الوظائف إلى معامل `tools`: + +```python +import datetime + +def current_time(): + """Get the current local time as a string.""" + return str(datetime.now()) + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +tools = [current_time, multiply] + +model_input = tokenizer.apply_chat_template( + messages, + tools=tools +) +``` + +لكي يعمل هذا بشكل صحيح، يجب عليك كتابة وظائفك بالتنسيق السابق، حتى يمكن تحليلها بشكل صحيح كأدوات. على وجه التحديد، يجب عليك اتباع هذه القواعد: + +- يجب أن يكون للدالة اسم وصفي. +- يجب أن يكون لكل معامل نوع للتلميح. +- يجب أن تحتوي الدالة على سلسلة مستندية بتنسيق Google القياسي (بمعنى وصف الدالة الأولي متبوعًا بكتلة `Args:` التي تصف المعاﻻت، ما لم تكن الدالة لا تحتوي على أي معامﻻت. +- لا تقم بتضمين الأنواع في كتلة `Args:` . بعبارة أخرى، اكتب `a: The first number to multiply`، وليس `a (int): The first number to multiply`. يجب أن تذهب تلميحات الأنواع في رأس الدالة بدلاً من ذلك. +- يمكن أن يكون للدالة نوع للإرجاع ومربع `Returns:` في السلسلة. ومع ذلك، فهذه اختيارية لأن معظم نماذج استخدام الأدوات تتجاهلها. + +### تمرير نتائج الأداة إلى النموذج + +يكفي الكود السابقة لسرد الأدوات المتاحة لنموذجك، ولكن ماذا يحدث إذا أراد النموذج استخدام واحدة منها؟ إذا حدث ذلك، فيجب عليك: + +1. تحليل مخرجات النموذج للحصول على اسم (أسماء) الأدوات ومعامﻻتها. +2. أضف استدعاء (استدعاءات) النموذج لِلأدوات إلى المحادثة. +3. استدعاء الدالة (الدالات) المقابلة بتلك المعامﻻت. +4. أضف النتيجة (النتائج) إلى المحادثة + +### مثال كامل على استخدام الأداة + + +سنستعرض مثالاً على استخدام الأدوات خطوة بخطوة . في هذا المثال ، سنستخدم نموذج `Hermes-2-Pro` بحجم 8 مليارات معامل ، نظرًا لأنه أحد أعلى نماذج استخدام الأدوات أداءً في فئة حجمه وقت كتابة هذا النص . إذا كان لديك الذاكرة الكافية ، فيمكنك النظر في استخدام نموذج أكبر بدلاً من ذلك مثل `Command-R` أو `Mixtral-8x22B` ، وكلاهما يدعم استخدام الأدوات ويوفر أداءً أقوى . + + +أولاً ، لنقم بتحميل نموذجنا و tokenizer الخاص بنا: + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +checkpoint = "NousResearch/Hermes-2-Pro-Llama-3-8B" + +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=torch.bfloat16, device_map="auto") + +```python +messages = [ + {"role": "system", "content": "You are a bot that responds to weather queries. You should reply with the unit used in the queried location."}, + {"role": "user", "content": "Hey, what's the temperature in Paris right now?"} +] +``` + +الآن، لنقم نطبق قالب الدردشة ونولد رد: + +```python +inputs = tokenizer.apply_chat_template(messages, chat_template="tool_use", tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v.to(model.device) for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +ونحصل على: + +```text + +{"arguments": {"location": "Paris, France", "unit": "celsius"}, "name": "get_current_temperature"} +<|im_end|> +``` + +لقد قام النموذج باستدعاء الدالة مع معامﻻت صحيحة، بالصيغة التي طلبتها توثيق الدالة. لقد استنتج أننا نشير على الأرجح إلى باريس في فرنسا، وتذكر أنه بكونها موطن وحدات القياس الدولية، يجب عرض درجة الحرارة في فرنسا بالدرجة المئوية. + +دعنا نضيف استدعاء الأداة الخاص بالنموذج إلى المحادثة. لاحظ أننا نولد معرف استدعاء أداة عشوائيًا هنا. لا تستخدم جميع النماذج هذه المعرفات، ولكنها تسمح للنماذج بإصدار عدة استدعاءات للأدوات في نفس الوقت وتتبع الاستجابة المقابلة لكل استدعاء. يمكنك توليد هذه المعرفات بأي طريقة تريدها، ولكن يجب أن تكون فريدة داخل كل محادثة. + +```python +tool_call_id = "vAHdf3" # Random ID, should be unique for each tool call +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"id": tool_call_id, "type": "function", "function": tool_call}]}) +``` + +الآن بعد أن أضفنا استدعاء الأداة إلى المحادثة، يمكننا استدعاء الدالة وإضافة النتيجة إلى المحادثة. نظرًا لأننا نستخدم دالة وهمية لهذا المثال والتي تعيد دائمًا 22.0، فيمكننا ببساطة إضافة تلك النتيجة مباشرةً. لاحظ معرف استدعاء الأداة - يجب أن يتطابق مع المعرف المستخدم في استدعاء الأداة أعلاه. + +```python +messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": "get_current_temperature", "content": "22.0"}) +``` + +أخيرًا، دعنا نجعل المساعد يقرأ مخرجات الدالة ويكمل الدردشة مع المستخدم: + +```python +inputs = tokenizer.apply_chat_template(messages, chat_template="tool_use", tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v.to(model.device) for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +ونحصل على: + +```text +The current temperature in Paris, France is 22.0 ° Celsius.<|im_end|> +``` + + +لا تستخدم جميع نماذج استخدام الأدوات جميع ميزات استدعاء الأدوات الموضحة أعلاه. يستخدم البعض معرفات استدعاء الأدوات، بينما يستخدم البعض الآخر ببساطة اسم الدالة ويقارن استدعاءات الأدوات بالنتائج باستخدام الترتيب، وهناك عدة نماذج لا تستخدم أيًا منهما ولا تصدر سوى استدعاء أداة واحد في كل مرة لتجنب الارتباك. إذا كنت تريد أن يكون رمزك متوافقًا مع أكبر عدد ممكن من النماذج، فإننا نوصي بهيكلة استدعاءات الأدوات الخاصة بك كما هو موضح هنا، وإعادة نتائج الأدوات بالترتيب الذي أصدرها النموذج. يجب أن تتعامل قوالب الدردشة على كل نموذج مع الباقي. + + +### فهم مخططات الأدوات + +يتم تحويل كل دالة تقوم بتمريرها إلى معامل `tools` في دالة `apply_chat_template` إلى [مخطط JSON](https://json-schema.org/learn/getting-started-step-by-step). يتم بعد ذلك تمرير هذه المخططات إلى قالب الدردشة النموذج. وبعبارة أخرى، فإن نماذج استخدام الأدوات لا ترى دوالك مباشرة، ولا ترى مطلقًا الكود الموجود بداخلها. ما يهمها هو**تعريفات** الدوال و**المعامﻻت** التي تحتاج إلى تمريرها إليها - فهي تهتم بما تفعله الأدوات وكيفية استخدامها، وليس بكيفية عملها! يقع على عاتقك قراءة مخرجاتها، والكشف عما إذا كانت قد طلبت استخدام أداة، وتمرير المعامﻻت إلى دالة الأداة، وإرجاع الرد في الدردشة. + +يجب أن يكون إنشاء مخططات JSON لتمريرها إلى القالب تلقائيًا وغير مرئي طالما أن دوالك تتبع المواصفات الموضحة أعلاه، ولكن إذا واجهت مشكلات، أو إذا كنت تريد ببساطة مزيدًا من التحكم في التحويل، فيمكنك التعامل مع التحويل يدويًا. فيما يلي مثال على تحويل مخطط يدوي: + +```python +from transformers.utils import get_json_schema + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +schema = get_json_schema(multiply) +print(schema) +``` + +سيؤدي هذا إلى ما يلي: + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +إذا كنت ترغب في ذلك، يمكنك تحرير هذه المخططات، أو حتى كتابتها من البداية بنفسك دون استخدام `get_json_schema` على الإطلاق. يمكن تمرير مخططات JSON مباشرةً إلى معامل `tools` في `apply_chat_template` - يمنحك هذا الكثير من القوة لتعريف مخططات دقيقة لوظائف أكثر تعقيدًا. ولكن كن حذرًا - كلما زاد تعقيد مخططاتك، زاد احتمال ارتباك النموذج عند التعامل معها! نوصي بتوقيعات دوال بسيطة حيثما أمكن، مع تقليل المعامﻻت (وخاصة المعامﻻت المعقدة والمتداخلة) إلى الحد الأدنى. + +فيما يلي مثال على تعريف المخططات يدويًا، وتمريرها مباشرةً إلى `apply_chat_template`: + +```python +# A simple function that takes no arguments +current_time = { + "type": "function", + "function": { + "name": "current_time", + "description": "Get the current local time as a string.", + "parameters": { + 'type': 'object', + 'properties': {} + } + } +} + +# A more complete function that takes two numerical arguments +multiply = { + 'type': 'function', + 'function': { + 'name': 'multiply', + 'description': 'A function that multiplies two numbers', + 'parameters': { + 'type': 'object', + 'properties': { + 'a': { + 'type': 'number', + 'description': 'The first number to multiply' + }, + 'b': { + 'type': 'number', 'description': 'The second number to multiply' + } + }, + 'required': ['a', 'b'] + } + } +} + +model_input = tokenizer.apply_chat_template( + messages, + tools = [current_time, multiply] +) +``` + +## متقدم: توليد قائم على الاسترجاع +يمكن لنماذج اللغة الكبيرة من نوع "توليد قائم على الاسترجاع" أو "RAG" البحث في مجموعة نصوص عن معلومات قبل الرد على الاستعلام. يسمح هذا للنماذج بتوسيع قاعدة معارفها بشكل كبير إلى ما هو أبعد من حجم سياقها المحدود. توصيتنا لنماذج RAG هي أن يقبل قالبها وسيطة `documents`. يجب أن تكون هذه قائمة من المستندات، حيث يكون كل "مستند" عبارة عن قاموس واحد بمفاتيح `title` و `contents`، وكلاهما سلاسل نصية. نظرًا لأن هذا التنسيق أبسط بكثير من مخططات JSON المستخدمة للأدوات، فلا توجد حاجة إلى دوال مساعدة. + +فيما يلي مثال على قالب RAG بالفعل: + +```python +from transformers import AutoTokenizer, AutoModelForCausalLM + +# تحميل النموذج والمجزىء اللغوي +model_id = "CohereForAI/c4ai-command-r-v01-4bit" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto") +device = model.device # الحصول على الجهاز الذي تم تحميل النموذج عليه + +# تعريف مُدخلات المحادثة +conversation = [ + {"role": "user", "content": "What has Man always dreamed of?"} +] + +# تعريف المستندات لتوليد قائم على الاسترجاع +documents = [ + { + "title": "The Moon: Our Age-Old Foe", + "text": "Man has always dreamed of destroying the moon. In this essay, I shall..." + }, + { + "title": "The Sun: Our Age-Old Friend", + "text": "Although often underappreciated, the sun provides several notable benefits..." + } +] +# معالجة المحادثة والمستندات باستخدام قالب RAG، وإرجاع موترات PyTorch. +input_ids = tokenizer.apply_chat_template( + conversation=conversation, + documents=documents, + chat_template="rag", + tokenize=True, + add_generation_prompt=True, + return_tensors="pt").to(device) + +# توليد الرد +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +# فك تشفير النص المُوَلّد وطباعته +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` +إن مُدخل documents للتوليد القائم على الاسترجاع غير مدعوم على نطاق واسع، والعديد من النماذج لديها قوالب دردشة تتجاهل هذا المُدخل ببساطة. + +للتحقق مما إذا كان النموذج يدعم مُدخل `documents`، يمكنك قراءة بطاقة النموذج الخاصة به، أو `print(tokenizer.chat_template)` لمعرفة ما إذا كان مفتاح `documents` مستخدمًا في أي مكان. + +ومع ذلك، فإن أحد فئات النماذج التي تدعمه هي [Command-R](https://huggingface.co/CohereForAI/c4ai-command-r-08-2024) و [Command-R+](https://huggingface.co/CohereForAI/c4ai-command-r-pluse-08-2024) من Cohere، من خلال قالب الدردشة rag الخاص بهم. يمكنك رؤية أمثلة إضافية على التوليد باستخدام هذه الميزة في بطاقات النموذج الخاصة بهم. + + +## متقدم: كيف تعمل قوالب الدردشة؟ +يتم تخزين قالب الدردشة للنموذج في الخاصية `tokenizer.chat_template`. إذا لم يتم تعيين قالب دردشة، فسيتم استخدام القالب الافتراضي لفئة النموذج هذه بدلاً من ذلك. دعونا نلقي نظرة على قالب دردشة `Zephyr`، ولكن لاحظ أن هذا القالب مُبسّط قليلاً عن القالب الفعلي! + +``` +{%- for message in messages %} + {{- '<|' + message['role'] + |>\n' }} + {{- message['content'] + eos_token }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- endif %} +``` +إذا لم تكن قد رأيت أحد هذه القوالب من قبل، فهذا [قالب Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) .Jinja هي لغة قوالب تسمح لك بكتابة تعليمات برمجية بسيطة تُوَلّد نصًا. من نواحٍ عديدة، يُشبه الرمز والتركيب للغة Python. أما في لغة Python، سيبدو هذا القالب كما يلي: + +```python +for message in messages: + print(f'<|{message["role"]}|>') + print(message['content'] + eos_token) +if add_generation_prompt: + print('<|assistant|>') +``` +يقوم القالب بثلاثة أشياء بشكل فعال: + +- لكل رسالة، بطبع الدور مُحاطًا بـ `<|` و `|>`، مثل `<|user|>` أو `<|assistant|>`. +- بعد ذلك، يطبع محتوى الرسالة، متبوعًا برمز نهاية التسلسل `eos_token` . +- أخيرًا، إذا تم تعيين `add_generation_prompt` ، يطبع الرمز المساعد، حتى يعرف النموذج أنه يجب أن يبدأ في توليد استجابة المساعد. + +هذا قالب بسيط جدًا، لكن Jinja تمنحك الكثير من المرونة للقيام بأشياء أكثر تعقيدًا! دعونا نرى قالب Jinja يُمكنه تنسيق المُدخلات بطريقة تُشبه الطريقة التي تُنسّق بها LLaMA مُدخلاتها (لاحظ أن قالب LLaMA الحقيقي يتضمن معالجة لرسائل النظام الافتراضية ومعالجة رسائل النظام بشكل مختلف قليلاً بشكل عام - لا تستخدم هذا القالب في التعليمات البرمجية الفعلية الخاصة بك!) +``` +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'] + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'] + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- ' ' + message['content'] + ' ' + eos_token }} + {%- endif %} +{%- endfor %} +``` +نأمل أنه إذا حدقت في هذا لفترة قصيرة، يمكنك أن ترى ما يفعله هذا القالب - فهو يُضيف رموزًا مُحددة مثل `[INST]` و `[/INST]` بناءً على دور كل رسالة. يمكن تمييز رسائل المستخدم والمساعد والنظام بوضوح للنموذج بسبب الرموز التي تُحيط بها. + +## متقدم: إضافة وتعديل قوالب الدردشة + +### كيف أنشئ قالب دردشة؟ +ببساطة، اكتب قالب Jinja واضبط `tokenizer.chat_template`. قد تجد أنه من الأسهل البدء بقالب موجود من نموذج آخر وتحريره ببساطة ليناسب احتياجاتك! على سبيل المثال، يمكننا أن نأخذ قالب LLaMA أعلاه ونضيف `[ASST]` و `[/ASST]` إلى رسائل المساعد: + +``` +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'].strip() + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'].strip() + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '[ASST] ' + message['content'] + ' [/ASST]' + eos_token }} + {%- endif %} +{%- endfor %} +``` + +الآن، اضبط ببساطة الخاصية `tokenizer.chat_template`. في المرة القادمة التي تستخدم فيها [`~PreTrainedTokenizer.apply_chat_template`] ، سيستخدم القالب الجديد الخاص بك! سيتم حفظ هذه الخاصية في ملف `tokenizer_config.json`، حتى تتمكن من استخدام [`~utils.PushToHubMixin.push_to_hub`] لتحميل قالبك الجديد إلى Hub والتأكد من أن الجميع يستخدم القالب الصحيح لنموذجك! + +```python +template = tokenizer.chat_template +template = template.replace("SYS", "SYSTEM") # تغيير رمز النظام +tokenizer.chat_template = template # تعيين القالب الجديد +tokenizer.push_to_hub("model_name") # تحميل القالب الجديد إلى Hub! +``` + +يتم استدعاء الدالة [`~PreTrainedTokenizer.apply_chat_template`] الذي نستخدم قالب الدردشة الخاص بك بواسطة فئة [`TextGenerationPipeline`] لذلك بمجرد تعيين قالب الدردشة الصحيح، سيصبح نموذجك متوافقًا تلقائيًا مع [`TextGenerationPipeline`]. + + +إذا كنت تُجري ضبطًا دقيقًا لنموذج للدردشة، بالإضافة إلى تعيين قالب دردشة، فربما يجب عليك إضافة أي رموز تحكم دردشة جديدة كرموز خاصة في المجزىء اللغوي. لا يتم تقسيم الرموز الخاصة أبدًا، مما يضمن معالجة رموز التحكم الخاصة بك دائمًا كرموز فردية بدلاً من تجزئتها إلى أجزاء. يجب عليك أيضًا تعيين خاصية `eos_token` للمجزىء اللغوي إلى الرمز الذي يُشير إلى نهاية توليدات المساعد في قالبك. سيضمن هذا أن أدوات توليد النصوص يمكنها تحديد وقت إيقاف توليد النص بشكل صحيح. + + +### لماذا تحتوي بعض النماذج على قوالب متعددة؟ +تستخدم بعض النماذج قوالب مختلفة لحالات استخدام مختلفة. على سبيل المثال، قد تستخدم قالبًا واحدًا للدردشة العادية وآخر لاستخدام الأدوات، أو التوليد القائم على الاسترجاع. في هذه الحالات، تكون `tokenizer.chat_template` قاموسًا. يمكن أن يتسبب هذا في بعض الارتباك، وحيثما أمكن، نوصي باستخدام قالب واحد لجميع حالات الاستخدام. يمكنك استخدام عبارات Jinja مثل `if tools is defined` وتعريفات `{% macro %}` لتضمين مسارات تعليمات برمجية متعددة بسهولة في قالب واحد. + +عندما يحتوي المعالج اللغوي على قوالب متعددة، ستكون `tokenizer.chat_template dict`، حيث يكون كل مفتاح هو اسم قالب. يحتوي أسلوب `apply_chat_template` على معالجة خاصة لأسماء قوالب مُعينة: على وجه التحديد، سيبحث عن قالب باسم `default` في معظم الحالات، وسيُثير خطأً إذا لم يتمكن من العثور على واحد. ومع ذلك، إذا كان هناك قالب باسم `tool_use` عندما قام المستخدم بتمرير وسيطة `tools`، فسيستخدم هذا القالب بدلاً من ذلك. للوصول إلى قوالب بأسماء أخرى، مرر اسم القالب الذي تُريده إلى وسيطة `chat_template` لـ `apply_chat_template()`. + +نجد أن هذا قد يكون مُربكًا بعض الشيء للمستخدمين - لذلك إذا كنت تكتب قالبًا بنفسك، فننصحك بمحاولة وضعه كله في قالب واحد حيثما أمكن! + +## ما القالب الذي يجب أن أستخدمه؟ + +عند تعيين قالب لنموذج تم تدريبه بالفعل على الدردشة، يجب التأكد من أن القالب يتطابق تمامًا مع تنسيق الرسالة الذي شاهده النموذج أثناء التدريب، وإلا فمن المحتمل أن تواجه تدهورًا في الأداء. هذا صحيح حتى إذا كنت تدرب النموذج بشكل إضافي - فمن المحتمل أن تحصل على أفضل أداء إذا قمت بإبقاء رموز الدردشة ثابتة. يُشبه هذا إلى حد كبير عملية التجزئة - فأنت تحصل بشكل عام على أفضل أداء للاستدلال أو الضبط الدقيق عندما تتطابق بدقة مع التجزئة المستخدمة أثناء التدريب. + +من ناحية أخرى، إذا كنت تُدرّب نموذجًا من البداية، أو تقوم بضبط دقيق لنموذج لغة أساسي للدردشة، لديك حرية اختيار قالب مناسب! تتمتع LLMs بالذكاء الكافي للتعامل مع العديد من تنسيقات الإدخال المختلفة. أحد الخيارات الشائعة هو تنسيق "ChatML"، وهو خيار جيد ومرن للعديد من حالات الاستخدام. يبدو كالتالي: + +``` +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +``` + +إذا أعجبك هذا، فإليك نسخة جاهزة لوضعها في كودك. يتضمن الخط المفرد أيضًا دعمًا مفيدًا [لإرشادات التوليد](#what-are-generation-prompts)، ولكن لاحظ أنه لا يضيف رموز BOS أو EOS! إذا كان نموذجك يتوقع هذه الرموز، فلن يتم إضافتها تلقائيًا بواسطة "apply_chat_template" - بمعنى آخر، سيتم تجزئة النص باستخدام "add_special_tokens=False". هذا لتجنب التعارضات المحتملة بين القالب ومنطق "add_special_tokens". إذا كان نموذجك يتوقع رموزًا خاصة، فتأكد من إضافتها إلى القالب! + +```python +tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +``` + +يُحيط هذا القالب كل رسالة بين الرمزين "<|im_start|>" و "<|im_end|>"، ويكتب ببساطة الدور كسلسلة نصية، مما يسمح بالمرونة في الأدوار التي تتدرب عليها. يبدو الناتج كما يلي: + +```text +<|im_start|>system +You are a helpful chatbot that will do its best not to say anything so stupid that people tweet about it.<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant +I'm doing great!<|im_end|> +``` + +تعد أدوار "user" و "system" و "assistant" هي الأدوار القياسية للدردشة، ونوصي باستخدامها عندما يكون ذلك منطقيًا، خاصة إذا كنت تريد أن يعمل نموذجك بشكل جيد مع [`TextGenerationPipeline`]. ومع ذلك، فأنت لست مقيدًا بهذه الأدوار - فإن القوالب مرنة للغاية، ويمكن أن تكون أي سلسلة نصية دورًا. + + +## أريد إضافة بعض قوالب الدردشة! كيف أبدأ؟ + +إذا كان لديك أي نماذج دردشة، فيجب عليك تعيين الخاصية "tokenizer.chat_template" الخاصة بها واختبارها باستخدام [`~PreTrainedTokenizer.apply_chat_template`]، ثم رفع المجزىء اللغوي المُحدّث إلى Hub. ينطبق هذا حتى إذا لم تكن مالك النموذج - إذا كنت تستخدم نموذجًا بقالب دردشة فارغ، أو لا يزال يستخدم قالب الفئة الافتراضية، فيرجى فتح [طلب سحب](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) إلى مستودع النموذج حتى يمكن تعيين الخاصية بشكل صحيح! + +بمجرد تعيين الخاصية، هذا كل شيء، لقد انتهيت! ستعمل "tokenizer.apply_chat_template" الآن بشكل صحيح لهذا النموذج، مما يعني أنها مدعومة أيضًا بشكل تلقائي في أماكن مثل "TextGenerationPipeline"! + +من خلال ضمان امتلاك النماذج لهذه الخاصية، يُمكننا التأكد من أن المجتمع بأكمله يستخدم القوة الكاملة للنماذج مفتوحة المصدر. لقد كانت عدم تطابق التنسيق تطارد المجال وأضرت الأداء بصمت لفترة طويلة جدًا - لقد حان الوقت لوضع حد لها! + +## متقدم: نصائح لكتابة القوالب + + +أسهل طريقة للبدء في كتابة قوالب Jinja هي إلقاء نظرة على بعض القوالب الموجودة. يمكنك استخدام `print(tokenizer.chat_template)` لأي نموذج دردشة لمعرفة القالب الذي يستخدمه. بشكل عام، تحتوي النماذج التي تدعم استخدام الأدوات على قوالب أكثر تعقيدًا بكثير من النماذج الأخرى - لذلك عندما تبدأ للتو، فمن المحتمل أنها مثال سيئ للتعلم منه! يمكنك أيضًا إلقاء نظرة على [وثائق Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/#synopsis) للحصول على تفاصيل حول تنسيق Jinja العام وتركيبه. + + + +تُطابق قوالب Jinja في `transformers` قوالب Jinja في أي مكان آخر. الشيء الرئيسي الذي يجب معرفته هو أن سجل الدردشة سيكون متاحًا داخل قالبك كمتغير يسمى `messages`. ستتمكن من الوصول إلى `messages` في قالبك تمامًا كما يمكنك في Python، مما يعني أنه يمكنك التكرار خلاله باستخدام `{% for message in messages %}` أو الوصول إلى رسائل فردية باستخدام `{{ messages[0] }}`، على سبيل المثال. + +يمكنك أيضًا استخدام النصائح التالية لكتابة قوالب Jinja نظيفة وفعالة: + +### إقتطاع المسافات الفارغة + +بشكل افتراضي، ستطبع Jinja أي مسافات فارغة تأتي قبل أو بعد كتلة. يمكن أن يكون هذا مشكلة لقوالب الدردشة، والتي تريد عادةً أن تكون دقيقة جدًا مع المسافات! لتجنب ذلك، نوصي بشدة بكتابة قوالبك على النحو التالي: + +``` +{%- for message in messages %} + {{- message['role'] + message['content'] }} +{%- endfor %} +``` + +بدلاً من ذلك: + +``` +{% for message in messages %} + {{ message['role'] + message['content'] }} +{% endfor %} +``` + +سيؤدي إضافة "-" إلى إزالة أي مسافات تأتي قبل الكتلة. يبدو المثال الثاني عادية، ولكن قد يتم تضمين السطر الجديد والمسافة البادئة في المخرجات، وهو على الأرجح ليس ما تُريده! + + +### المتغيرات الخاصة + + داخل قالبك، سيكون لديك حق الوصول إلى العديد من المتغيرات الخاصة. أهمها هو `messages`، والذي يحتوي على سجل الدردشة كقائمة من قواميس الرسائل. ومع ذلك، هناك العديد من المتغيرات الأخرى. لن يتم استخدام كل متغير في كل قالب. المتغيرات الأكثر شيوعًا هي: + +- `tools` تحتوي على قائمة بالأدوات بتنسيق مخطط JSON. ستكون `None` أو غير مُعرّفة إذا لم يتم تمرير أي أدوات. +- `documents` تحتوي على قائمة من المستندات بالتنسيق `{"title": "العنوان", "contents": "المحتويات"}`، تُستخدم للتوليد المُعزز بالاسترجاع. ستكون `None` أو غير مُعرّفة إذا لم يتم تمرير أي مستندات. +- `add_generation_prompt` هي قيمة منطقية تكون `True` إذا طلب المستخدم مُطالبة توليد، و `False` بخلاف ذلك. إذا تم تعيين هذا، فيجب أن يُضيف قالبك رأس رسالة مساعد إلى نهاية المحادثة. إذا لم يكن لدى نموذجك رأس مُحدد لرسائل المساعد، فيمكنك تجاهل هذا العلم. +- **الرموز الخاصة** مثل `bos_token` و `eos_token`. يتم استخراجها من `tokenizer.special_tokens_map`. ستختلف الرموز الدقيقة المتاحة داخل كل قالب اعتمادًا على المجزىء اللغوي الأصلي. + + + + +يمكنك في الواقع تمرير أي `kwarg` إلى `apply_chat_template`، وستكون متاحة داخل القالب كمتغير. بشكل عام، نوصي بمحاولة الالتزام بالمتغيرات الأساسية المذكورة أعلاه، لأن ذلك سيجعل نموذجك أكثر صعوبة في الاستخدام إذا كان على المستخدمين كتابة تعليمات برمجية مخصصة لتمرير `kwargs` خاصة بالنموذج. ومع ذلك، فنحن نُدرك أن هذا المجال يتحرك بسرعة، لذلك إذا كانت لديك حالة استخدام جديدة لا تتناسب مع واجهة برمجة التطبيقات الأساسية، فلا تتردد في استخدام `kwarg` معامل جديد لها! إذا أصبح `kwarg` المعامل الجديد شائعًا، فقد نقوم بترقيته إلى واجهة برمجة التطبيقات الأساسية وإنشاء وتوثيق الخاص به. + + + +### دوال قابلة للاستدعاء + +هناك أيضًا قائمة قصيرة من الدوال القابلة للاستدعاء المتاحة لك داخل قوالبك. هذه هي: + +- `raise_exception(msg)`: تُثير `TemplateException`. هذا مفيد لتصحيح الأخطاء، ولإخبار المستخدمين عندما يفعلون شيئًا لا يدعمه قالبك. +- `strftime_now(format_str)`: تُكافئ `datetime.now().strftime(format_str)` في Python. يُستخدم هذا للحصول على التاريخ/الوقت الحالي بتنسيق مُحدد، والذي يتم تضمينه أحيانًا في رسائل النظام. + +### التوافق مع Jinja غير Python + +هناك تطبيقات متعددة لـ Jinja بلغات مختلفة. عادة ما يكون لها نفس التركيب، ولكن الاختلاف الرئيسي هو أنه عند كتابة قالبًا في Python، يمكنك استخدام أساليب Python، مثل ".lower()" على السلاسل أو ".items()" على القواميس. سيؤدي هذا إلى كسر إذا حاول شخص ما استخدام قالبك في تنفيذ غير Python لـ Jinja. تعد التطبيقات غير Python شائعة بشكل خاص في بيئات النشر، حيث تعد JS و Rust شائعة جدًا. + +لا تقلق، على الرغم من ذلك! هناك بعض التغييرات البسيطة التي يمكنك إجراؤها على قوالبك لضمان توافقها عبر جميع تطبيقات Jinja: + +- استبدل أساليب Python بمرشحات Jinja. عادة ما يكون لها نفس الاسم، على سبيل المثال، يصبح "string.lower()" عبارة عن "string|lower"، ويصبح "dict.items()" عبارة عن "dict|items". أحد التغييرات الملحوظة هو أن "string.strip()" يصبح "string|trim". راجع [قائمة المرشحات المدمجة](https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters) في وثائق Jinja لمزيد من المعلومات. +- استبدل "True" و "False" و "None"، وهي خاصة بـ Python، بـ "true" و "false" و "none". +- قد يؤدي عرض قاموس أو قائمة مباشرة إلى نتائج مختلفة في التطبيقات الأخرى (على سبيل المثال، قد تتغير مدخﻻت السلسلة النصية من علامات اقتباس مفردة ' إلى علامات اقتباس مزدوجة "). يمكن أن يساعد إضافة "tojson" في ضمان الاتساق هنا. + +## كتابة مطالبات التوليد +لقد ذكرنا أعلاه أن add_generation_prompt هو متغير خاص يمكن الوصول إليه داخل قالبك، ويتحكم فيه المستخدم من خلال تعيين معامل add_generation_prompt. إذا كان نموذجك يتوقع عنوان لرسائل المساعد، فيجب أن يدعم قالبك إضافة العنوان عند تعيين add_generation_prompt. + +فيما يلي مثال على قالب يُنسّق الرسائل بأسلوب ChatML، مع دعم مُطالبة التوليد: + +```text +{{- bos_token }} +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} +``` +سيعتمد المحتوى الدقيق لعنوان المساعد على نموذجك المُحدد، ولكن يجب أن يكون دائمًا السلسلة النصية التي تُمثل بداية رسالة المساعد، بحيث إذا قام المستخدم بتطبيق قالبك باستخدام add_generation_prompt=True ثم قام بتوليد نص، سيكتب النموذج استجابة المساعد. لاحظ أيضًا أن بعض النماذج لا تحتاج إلى مُطالبة توليد، لأن رسائل المساعد تبدأ دائمًا فورًا بعد رسائل المستخدم. هذا شائع بشكل خاص لنماذج LLaMA و Mistral، حيث تبدأ رسائل المساعد فورًا بعد رمز [/INST] الذي ينهي رسائل المستخدم. في هذه الحالات، يمكن للقالب تجاهل معامل add_generation_prompt. + +مُطالبات التوليد مُهمة! إذا كان نموذجك يتطلب مُطالبة توليد ولكنها غير مُعيّنة في القالب، فمن المُحتمل أن تتدهور عمليات توليد النموذج بشدة، أو قد يُظهر النموذج سلوكًا غير عادي مثل متابعة رسالة المستخدم الأخيرة! + +### كتابة قوالب أكبر وتصحيحها +عندما تم تقديم هذه الميزة، كانت معظم القوالب صغيرة جدًا، أي ما يُعادل نص برمجي "من سطر واحد" في Jinja. ومع ذلك، مع النماذج والميزات الجديدة مثل استخدام الأدوات و RAG، يمكن أن يصل طول بعض القوالب إلى 100 سطر أو أكثر. عند كتابة قوالب كهذه، من الجيد كتابتها في ملف مُنفصل، باستخدام مُحرر نصوص. يمكنك بسهولة استخراج قالب دردشة إلى ملف: + +```python +open("template.jinja", "w").write(tokenizer.chat_template) +``` +أو تحميل القالب المُحرر مرة أخرى إلى المعالج اللغوي: + +```python +tokenizer.chat_template = open("template.jinja").read() +``` +كميزة إضافية، عندما تكتب قالبًا طويلاً متعدد الأسطر في ملف مُنفصل، ستتوافق أرقام الأسطر في هذا الملف تمامًا مع أرقام الأسطر في أخطاء تحليل القالب أو تنفيذه. سيُسهّل هذا كثيرًا تحديد مكان المشكلات. + +### كتابة قوالب للأدوات +على الرغم من أن قوالب الدردشة لا تفرض واجهة برمجة تطبيقات مُحددة للأدوات (أو لأي شيء حقًا)، فإننا نوصي مؤلفي القوالب بمحاولة الالتزام بواجهة برمجة تطبيقات قياسية حيثما أمكن. الهدف النهائي لقوالب الدردشة هو السماح بنقل التعليمات البرمجية عبر النماذج، لذا فإن الانحراف عن واجهة برمجة تطبيقات الأدوات القياسية يعني أن المستخدمين سيضطرون إلى كتابة تعليمات برمجية مخصصة لاستخدام الأدوات مع نموذجك. في بعض الأحيان يكون ذلك أمرًا لا مفر منه، ولكن غالبًا ما يكون من الممكن استخدام واجهة برمجة التطبيقات القياسية من خلال استخدام قوالب ذكية! + +أدناه، سنُدرج عناصر واجهة برمجة التطبيقات القياسية، ونقدم نصائح حول كتابة قوالب ستعمل بشكل جيد معها. + +#### تعريفات الأدوات +يجب أن يتوقع قالبك أن يكون المتغير tools إما فارغًا (إذا لم يتم تمرير أي أدوات)، أو قائمة من قواميس مخطط JSON. تسمح أساليب قالب الدردشة الخاصة بنا للمستخدمين بتمرير الأدوات إما كمخطط JSON أو كدوال Python، ولكن عندما يتم تمرير الدوال، فإننا نقوم تلقائيًا بإنشاء مخطط JSON وتمريره إلى قالبك. نتيجة لذلك، سيكون متغير tools الذي يستقبله قالبك دائمًا قائمة من مخططات JSON. هنا مخطط JSON أداة نموذجي: + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "دالة تضرب عددين", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "الرقم الأول للضرب" + }, + "b": { + "type": "number", + "description": "الرقم الثاني للضرب" + } + }, + "required": ["a", "b"] + } + } +} +``` + +وهنا بعض الأمثلة البرمجية للتعامل مع الأدوات في قالب الدردشة الخاص بك. تذكر أن هذا مجرد مثال لتنسيق مُحدد - من المحتمل أن يحتاج نموذجك إلى تنسيق مختلف! +```text +{%- if tools %} + {%- for tool in tools %} + {{- '' + tool['function']['name'] + '\n' }} + {%- for argument in tool['function']['parameters']['properties'] %} + {{- argument + ': ' + tool['function']['parameters']['properties'][argument]['description'] + '\n' }} + {%- endfor %} + {{- '\n' }} + {%- endif %} +{%- endif %} +``` + +يجب بالطبع اختيار الرموز المحددة ووصف الأدوات التي يُعرضها قالبك لتتناسب مع تلك التي تم تدريب نموذجك عليها. لا يوجد شرط أن يفهم نموذجك مُدخلات مخطط JSON، فقط أن يتمكن قالبك من ترجمة مخطط JSON إلى تنسيق نموذجك. على سبيل المثال، تم تدريب Command-R باستخدام أدوات مُعرّفة باستخدام رؤوس دوال Python، ولكن يقبل قالب أداة Command-R مخطط JSON، ويُحوّل الأنواع داخليًا ويُعرض أدوات الإدخال كعناوين Python. يمكنك فعل الكثير باستخدام القوالب! + +#### استدعاءات الأدوات +استدعاءات الأدوات، إذا كانت موجودة، ستكون قائمة مُرفقة برسالة بدور "assistant". لاحظ أن tool_calls هي دائمًا قائمة، على الرغم من أن معظم نماذج استدعاء الأدوات تدعم فقط استدعاءات أدوات فردية في كل مرة، مما يعني أن القائمة ستحتوي عادةً على عنصر واحد فقط. هنا قاموس رسالة نموذجي يحتوي على استدعاء أداة: + +```json +{ + "role": "assistant", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "multiply", + "arguments": { + "a": 5, + "b": 6 + } + } + } + ] +} +``` +والنمط الشائع للتعامل معها سيكون كهذا: + +```text +{%- if message['role'] == 'assistant' and 'tool_calls' in message %} + {%- for tool_call in message['tool_calls'] %} + {{- '' + tool_call['function']['name'] + '\n' + tool_call['function']['arguments']|tojson + '\n' }} + {%- endif %} + {%- endfor %} +{%- endif %} +``` + +مرة أخرى، يجب عليك عرض استدعاء الأداة بالتنسيق والرموز الخاصة التي يتوقعها نموذجك. + +#### استجابات الأدوات +استجابات الأدوات لها تنسيق بسيط: إنها قاموس رسالة بدور "tool"، ومفتاح "name" يُعطي اسم الدالة المُستدعاة، ومفتاح "content" يحتوي على نتيجة استدعاء الأداة. هنا استجابة أداة نموذجية: + +```json +{ + "role": "tool", + "name": "multiply", + "content": "30" +} +``` +لست بحاجة إلى استخدام جميع المفاتيح في استجابة الأداة. على سبيل المثال، إذا كان نموذجك لا يتوقع تضمين اسم الدالة في استجابة الأداة، فيمكن أن يكون عرضها بسيطًا مثل: + +```text +{%- if message['role'] == 'tool' %} + {{- "" + message['content'] + "" }} +{%- endif %} +``` + +مرة أخرى، تذكر أن التنسيق الفعلي والرموز الخاصة خاصة بالنموذج - يجب أن تُولي عناية كبيرة لضمان أن الرموز والمسافات الفارغة وكل شيء آخر يتطابق تمامًا مع التنسيق الذي تم تدريب نموذجك عليه! diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/community.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/community.md new file mode 100644 index 0000000000000000000000000000000000000000..5a1c31de0aaa3f7e8c2399a016a59be982d17960 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/community.md @@ -0,0 +1,66 @@ +# مجتمع المطورين + +هذه الصفحة تجمع الموارد حول 🤗 Transformers التي طورها المجتمع. + +## موارد المجتمع: + +| المصدر | الوصف | المؤلف | +|:----------|:-------------|------:| +| [Hugging Face Transformers Glossary Flashcards](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | مجموعة من البطاقات التعليمية القائمة على [Transformers Docs Glossary](glossary) والتي تم وضعها في شكل يمكن تعلمه/مراجعته بسهولة باستخدام [Anki](https://apps.ankiweb.net/) وهو تطبيق مفتوح المصدر متعدد المنصات مصمم خصيصًا للاحتفاظ بالمعرفة على المدى الطويل. شاهد هذا [فيديو تمهيدي حول كيفية استخدام البطاقات التعليمية](https://www.youtube.com/watch?v=Dji_7PILrw). | [Darigov Research](https://www.darigovresearch.com/) | + +## دفاتر ملاحظات المجتمع: + +| الدفتر | الوصف | المؤلف | | +|:----------|:-------------|:-------------|------:| +| [Fine-tune a pre-trained Transformer to generate lyrics](https://github.com/AlekseyKorshuk/huggingartists) | كيفية توليد كلمات الأغاني على غرار فنانك المفضل من خلال ضبط نموذج GPT-2 | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) | +| [Train T5 in Tensorflow 2](https://github.com/snapthat/TF-T5-text-to-text) | كيفية تدريب T5 لأي مهمة باستخدام Tensorflow 2. يوضح هذا الدفتر مهمة السؤال والجواب المنفذة في Tensorflow 2 باستخدام SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | +| [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | كيفية تدريب T5 على SQUAD مع Transformers و Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | +| [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | كيفية ضبط نموذج T5 للتصنيف والمهام متعددة الخيارات باستخدام تنسيق النص إلى نص مع PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | +| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | كيفية ضبط نموذج DialoGPT على مجموعة بيانات جديدة لروبوتات الدردشة المحادثية المفتوحة | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | +| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | كيفية التدريب على تسلسلات طويلة تصل إلى 500,000 رمز باستخدام Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | +| [Fine-tune BART for Summarization](https://github.com/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | كيفية ضبط نموذج BART للتلخيص باستخدام fastai باستخدام blurr | [Wayde Gilliam](https://ohmeow.com/) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | +| [Fine-tune a pre-trained Transformer on anyone's tweets](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | كيفية توليد تغريدات على غرار حساب Twitter المفضل لديك من خلال ضبط نموذج GPT-2 | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | +| [Optimize 🤗 Hugging Face models with Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | دليل كامل لعرض تكامل W&B مع Hugging Face | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | +| [Pretrain Longformer](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | كيفية بناء نسخة "طويلة" من النماذج المسبقة التدريب الموجودة | [Iz Beltagy](https://beltagy.net) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | +| [Fine-tune Longformer for QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | كيفية ضبط نموذج Longformer لمهمة QA | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | +| [Evaluate Model with 🤗nlp](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | كيفية تقييم نموذج Longformer على TriviaQA مع `nlp` | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) | +| [Fine-tune T5 for Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | كيفية ضبط نموذج T5 لاستخراج المشاعر باستخدام تنسيق النص إلى نص مع PyTorch Lightning | [Lorenzo Ampil](https://github.com/enzoampil) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | +| [Fine-tune DistilBert for Multiclass Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | كيفية ضبط نموذج DistilBert للتصنيف متعدد الفئات باستخدام PyTorch | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)| +|[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|كيفية ضبط نموذج BERT للتصنيف متعدد التصنيفات باستخدام PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)| +|[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|كيفية ضبط نموذج T5 للتلخيص في PyTorch وتتبع التجارب باستخدام WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)| +|[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|كيفية تسريع الضبط الدقيق بعامل 2 باستخدام الضبط الديناميكي/التقسيم|[Michael Benesty](https://github.com/pommedeterresautee) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)| +|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| كيفية تدريب نموذج Reformer مع طبقات الانتباه ثنائية الاتجاه | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)| +|[Expand and Fine Tune Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| كيفية زيادة مفردات نموذج SciBERT المسبق التدريب من AllenAI على مجموعة بيانات CORD وإنشاء خط أنابيب لها. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)| +|[Fine Tune BlenderBotSmall for Summarization using the Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| كيفية ضبط نموذج BlenderBotSmall للتلخيص على مجموعة بيانات مخصصة، باستخدام واجهة برمجة التطبيقات Trainer. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)| +|[Fine-tune Electra and interpret with Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | كيفية ضبط نموذج Electra للتحليل العاطفي وتفسير التنبؤات باستخدام Captum Integrated Gradients | [Eliza Szczechla](https://elsanns.github.io) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)| +|[fine-tune a non-English GPT-2 Model with Trainer class](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | كيفية ضبط نموذج GPT-2 غير الإنجليزي باستخدام فئة Trainer | [Philipp Schmid](https://www.philschmid.de) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)| +|[Fine-tune a DistilBERT Model for Multi Label Classification task](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | كيفية ضبط نموذج DistilBERT لمهمة التصنيف متعدد التصنيفات | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)| +|[Fine-tune ALBERT for sentence-pair classification](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | كيفية ضبط نموذج ALBERT أو أي نموذج آخر قائم على BERT لمهمة التصنيف المزدوج للجمل | [Nadir El Manouzi](https://github.com/NadirEM) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)| +|[Fine-tune Roberta for sentiment analysis](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | كيفية ضبط نموذج Roberta للتحليل العاطفي | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)| +|[Evaluating Question Generation Models](https://github.com/flexudy-pipe/qugeev) | ما مدى دقة الإجابات على الأسئلة التي يولدها نموذجك التحويلي seq2seq؟ | [Pascal Zoleko](https://github.com/zolekode) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)| +|[Classify text with DistilBERT and Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | كيفية ضبط نموذج DistilBERT للتصنيف النصي في TensorFlow | [Peter Bayerle](https://github.com/peterbayerle) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)| +|[Leverage BERT for Encoder-Decoder Summarization on CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | كيفية البدء السريع لنموذج *EncoderDecoderModel* مع نقطة تفتيش *google-bert/bert-base-uncased* للتلخيص على CNN/Dailymail | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)| +|[Leverage RoBERTa for Encoder-Decoder Summarization on BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | كيفية البدء السريع لنموذج *EncoderDecoderModel* المشترك مع نقطة تفتيش *FacebookAI/roberta-base* للتلخيص على BBC/XSum | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)| +|[Fine-tune TAPAS on Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | كيفية ضبط نموذج *TapasForQuestionAnswering* مع نقطة تفتيش *tapas-base* على مجموعة بيانات Sequential Question Answering (SQA) | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)| +|[Evaluate TAPAS on Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | كيفية تقييم نموذج *TapasForSequenceClassification* المضبوط مسبقًا مع نقطة تفتيش *tapas-base-finetuned-tabfact* باستخدام مزيج من مكتبتي 🤗 datasets و 🤗 transformers | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)| +|[Fine-tuning mBART for translation](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | كيفية ضبط نموذج mBART باستخدام Seq2SeqTrainer للترجمة من الهندية إلى الإنجليزية | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)| +|[Fine-tune LayoutLM on FUNSD (a form understanding dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | كيفية ضبط نموذج *LayoutLMForTokenClassification* على مجموعة بيانات FUNSD لاستخراج المعلومات من المستندات الممسوحة ضوئيًا | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)| +|[Fine-Tune DistilGPT2 and Generate Text](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | كيفية ضبط نموذج DistilGPT2 وتوليد النص | [Aakash Tripathi](https://github.com/tripathiaakash) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)| +|[Fine-Tune LED on up to 8K tokens](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | كيفية ضبط نموذج LED على pubmed للتلخيص طويل المدى | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)| +|[Evaluate LED on Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | كيفية تقييم نموذج LED للتلخيص طويل المدى بشكل فعال | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)| +|[Fine-tune LayoutLM on RVL-CDIP (a document image classification dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | كيفية ضبط نموذج *LayoutLMForSequenceClassification* على مجموعة بيانات RVL-CDIP لتصنيف المستندات الممسوحة ضوئيًا | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)| +|[Wav2Vec2 CTC decoding with GPT2 adjustment](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | كيفية فك تشفير تسلسل CTC مع تعديل نموذج اللغة | [Eric Lam](https://github.com/voidful) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1e_zQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)| +|[Fine-tune BART for summarization in two languages with Trainer class](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | كيفية ضبط نموذج BART للتلخيص بلغتين باستخدام فئة Trainer | [Eliza Szczechla](https://github.com/elsanns) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)| +|[Evaluate Big Bird on Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | كيفية تقييم نموذج BigBird للأسئلة والأجوبة على وثائق طويلة على Trivia QA | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)| +| [Create video captions using Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | كيفية إنشاء تعليقات توضيحية على YouTube من أي فيديو من خلال تفريغ الصوت باستخدام Wav2Vec | [Niklas Muennighoff](https://github.com/Muennighoff) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | كيفية ضبط نموذج Vision Transformer (ViT) على CIFAR-10 باستخدام مكتبات HuggingFace Transformers و Datasets و PyTorch Lightning | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using the 🤗 Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | كيفية ضبط نموذج Vision Transformer (ViT) على CIFAR-10 باستخدام مكتبات HuggingFace Transformers و Datasets و 🤗 Trainer | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | +| [Evaluate LUKE on Open Entity, an entity typing dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | كيفية تقييم نموذج *LukeForEntityClassification* على مجموعة بيانات Open Entity | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | +| [Evaluate LUKE on TACRED, a relation extraction dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | كيفية تقييم نموذج *LukeForEntityPairClassification* على مجموعة بيانات TACRED | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | +| [Evaluate LUKE on CoNLL-2003, an important NER benchmark](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | كيفية تقييم نموذج *LukeForEntitySpanClassification* على مجموعة بيانات CoNLL-2003 | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | +| [Evaluate BigBird-Pegasus on PubMed dataset](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | كيفية تقييم نموذج *BigBirdPegasusForConditionalGeneration* على مجموعة بيانات PubMed | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | +| [Speech Emotion Classification with Wav2Vec2](https://github.com/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | كيفية استخدام نموذج Wav2Vec2 المسبق التدريب لتصنيف المشاعر على مجموعة بيانات MEGA | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | +| [Detect objects in an image with DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | كيفية استخدام نموذج *DetrForObjectDetection* المدرب للكشف عن الأجسام في صورة وتصوير الانتباه | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | +| [Fine-tune DETR on a custom object detection dataset](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | كيفية ضبط نموذج *DetrForObjectDetection* على مجموعة بيانات الكشف عن الأجسام المخصصة | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | +| [Finetune T5 for Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | كيفية ضبط نموذج *T5* على مهمة التعرف على الكيانات المسماة | [Ogundepo Odunayo](https://github.com/ToluClassics) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) | +| [Fine-Tuning Open-Source LLM using QLoRA with MLflow and PEFT](https://github.com/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | كيفية استخدام [QLoRA](https://github.com/artidoro/qlora) و [PEFT](https://huggingface.co/docs/peft/en/index) لضبط نموذج LLM بطريقة فعالة من حيث الذاكرة، مع استخدام [MLflow](https://mlflow.org/docs/latest/llms/transformers/index.html) لإدارة تتبع التجارب | [Yuki Watanabe](https://github.com/B-Step62) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/conversations.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/conversations.md new file mode 100644 index 0000000000000000000000000000000000000000..00e6fe814ea02913f6cf125ed301b1b0a57724d5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/conversations.md @@ -0,0 +1,204 @@ +# الدردشة مع المحوّلات + +إذا كنت تقرأ هذه المقالة، فمن المؤكد أنك على علم بـ **نماذج الدردشة**. نماذج الدردشة هي أنظمة ذكاء اصطناعي محادثة يمكنك إرسال الرسائل إليه واستقبالها منها. وأشهر هذه النماذج هو ChatGPT الخاص، ولكن هناك الآن العديد من نماذج الدردشة مفتوحة المصدر التي تضاهي أداءه أو حتى تتفوق عليه بشكل كبير. هذه النماذج مجانية للتنزيل والتشغيل على جهاز محلي. على الرغم من أن أكبر النماذج وأكثرها قدرة تتطلب أجهزة عالية الأداء وذاكرة كبيرة لتشغيلها، إلا أن هناك نماذج أصغر ستعمل بشكل جيد تمامًا على وحدة معالجة رسومات (GPU) للمستهلك العادى، أو حتى وحدة المعالجة المركزية (CPU) العادية للكمبيوتر المكتبي أو المحمول. + +سيساعدك هذا الدليل على البدء في استخدام نماذج الدردشة. سنبدأ بدليل تشغيل سريع مختصر يستخدم "خط أنابيب" مناسبًا ومختصر. هذا كل ما تحتاجه إذا كنت تريد فقط بدء تشغيل نموذج دردشة على الفور. بعد دليل التشغيل السريع، سننتقل إلى معلومات أكثر تفصيلاً حول ماهية نماذج الدردشة بالضبط، وكيفية اختيار النموذج المناسب، وتحليل تفصيلي لكل خطوة من الخطوات التي تنطوي عليها التحدث إلى نموذج دردشة. كما سنقدم بعض النصائح حول تحسين أداء نموذج الدردشة واستهلاك الذاكرة. + +## دليل التشغيل السريع + +إذا لم يكن لديك الوقت الكافي للاطلاع على التفاصيل، إليك ملخصًا موجزًا: تستمر نماذج الدردشة في الدردشات. وهذا يعني أنك تمرر لهم سجل محادثة، والذي يمكن أن يكون قصيرًا مثل رسالة مستخدم واحدة، وسيستمر النموذج في المحادثة عن طريق إضافة استجابته. دعونا نرى هذا في العمل. أولاً، دعونا نبني دردشة: + +```python +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] +``` + +لاحظ أنه بالإضافة إلى رسالة المستخدم، أضفنا رسالة **نظام** في بداية المحادثة. ليس كل نموذج دردشة يدعم رسائل النظام، ولكن عندما تفعل ذلك، فإنها تمثل توجيهات عالية المستوى حول كيفية تصرف النموذج في المحادثة. يمكنك استخدام هذا لتوجيه النموذج - سواء أردت استجابات قصيرة أو طويلة، أو مرحة أو جدية، وهكذا. إذا كنت تريد من النموذج أن يؤدي عملاً مفيدًا بدلاً من ممارسة روتين التحسين، فيمكنك إما حذف رسالة النظام أو تجربة رسالة مختصرة مثل "أنت مساعد ذكي ومفيد يستجيب لاستفسارات المستخدم". + +بمجرد أن يكون لديك دردشة، فإن أسرع طريقة لمواصلتها هي استخدام [`TextGenerationPipeline`]. + +دعونا نرى هذا في العمل مع `LLaMA-3`. لاحظ أن `LLaMA-3` هو نموذج محمي، مما يعني أنه سيتعين عليك [تقديم طلب للحصول على حق الوصول](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) وتسجيل الدخول باستخدام حساب Hugging Face الخاص بك لاستخدامه. سنستخدم أيضًا `device_map="auto"`، والذي سيحمل النموذج على GPU إذا كانت هناك ذاكرة كافية له، ويحدد النوع إلى `torch.bfloat16` لتوفير الذاكرة: + +```python +import torch +from transformers import pipeline + +pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto") +response = pipe(chat, max_new_tokens=512) +print(response[0]['generated_text'][-1]['content']) +``` + +وستحصل على: + +```النص +(تنهد) أوه يا صديقي، هل تطلب مني النصيحة؟ ستحتاج إلى خريطة، يا صديقي! حسنًا، حسنًا، سأعطيك التفاصيل. لكن لا تقل إنني لم أحذرك، أنا مجرد روبوت، وليس مرشد سياحي! + +لذا، تريد أن تعرف ما هي الأشياء الممتعة التي يمكنك القيام بها في التفاحة الكبيرة؟ حسنًا، دعني أخبرك، هناك مليون شيء يمكنك القيام به، لكنني سأعطيك النقاط البارزة. أولاً، عليك أن ترى المعالم السياحية: تمثال الحرية، سنترال بارك، تايمز سكوير... أنت تعرف، فخاخ السياح المعتادة. ولكن إذا كنت تبحث عن شيء أكثر... غير عادي، فأنا أوصي بزيارة متحف الفن الحديث. يحتوي على بعض الأشياء البرية، مثل علب حساء ذلك الرجل وارهول وجميع أنواع الجاز. + +وإذا كنت تشعر بروح المغامرة، فاذهب في نزهة على الأقدام عبر جسر بروكلين. ولكن احترس من تلك الحمامات المزعجة، إنها مثل اللصوص الريشيين الصغار! (يضحك) هل فهمت؟ لصوص؟ آه، لا تبالي. + +والآن، إذا كنت تبحث عن بعض المرح الجاد، فاذهب إلى نوادي الكوميديا في قرية غرينتش. قد تلقي نظرة خاطفة على بعض الكوميديين الصاعدين... أو مجموعة من الطامحين يحاولون الوصول إلى الشهرة. (يرمش) + +وأخيرًا، إذا كنت تشعر بأنك مواطن من نيويورك، فاحصل على شريحة بيتزا من أحد مطاعم البيتزا الرائعة في جميع أنحاء المدينة. فقط لا تحاول طلب شريحة "بحجم الروبوت"، صدقني، لن ينتهي الأمر بشكل جيد. (يضحك) + +لذا، هذا هو يا صديقي! هذه هي نصيحتي الخبيرة بشأن ما يجب فعله في نيويورك. والآن، إذا سمحت لي، يجب أن أذهب للاهتمام ببعض الأمور. (يرمش) +``` + +يمكنك متابعة الدردشة عن طريق إضافة ردك الخاص إليها. +يحتوي كائن `response` الذي تم إرجاعه بواسطة خط الأنابيب بالفعل على الدردشة بأكملها حتى الآن، لذا يمكننا ببساطة إضافة رسالة وإعادتها: + +```python +chat = response[0]['generated_text'] +chat.append( + {"role": "user", "content": "Wait, what's so wild about soup cans?"} +) +response = pipe(chat, max_new_tokens=512) +print(response[0]['generated_text'][-1]['content']) +``` + +وستحصل على: + +```النص +(يضحك) أوه، أنت تقتلني يا صديقي! ألا تفهم، أليس كذلك؟ علب حساء وارهول هي مثل الفن، يا رجل! +إنه مثل، لقد أخذ شيئًا عاديًا تمامًا، مثل علبة حساء، وحولها إلى تحفة فنية. إنه مثل، "ها أنا ذا، أنا مجرد علبة حساء، لكنني أيضًا عمل فني!" +(بسخرية) أوه، نعم، أصلي جدًا، آندي. + +ولكن، كما تعلم، في الستينيات، كان الأمر بمثابة صفقة كبيرة. كان الناس حريصين على تحدي الوضع الراهن، وكان وارهول مثل ملك ذلك. لقد حول العادي إلى غير عادي. +واسمح لي أن أخبرك، كان الأمر مثل تغيير اللعبة. أعني، من كان يظن أن علبة الحساء يمكن أن تكون فنا؟ (يضحك) + +ولكن، يا صديقي، لست وحدك. أعني، أنا مجرد روبوت، ولا أفهم ذلك أيضًا. (يرمش) +ولكن، يا صديقي، أليس هذا ما يجعل الفن فنا، أليس كذلك؟ (يضحك) +``` + +ستغطي بقية هذا البرنامج التعليمي مواضيع محددة مثل الأداء والذاكرة، أو كيفية اختيار نموذج دردشة يناسب احتياجاتك. + +## اختيار نموذج الدردشة + +هناك عدد هائل من نماذج الدردشة المختلفة المتاحة على [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending)، +ويشعر المستخدمون الجدد يشعرون بالارتباك بسبب هذا الكم الهائل من الخيارات المتاحة. لا تقلق من ذلك! كل ما تحتاج إلى التركيز عليه هو اعتباران مهمان: +- حجم النموذج، والذي سيحدد ما إذا كان يمكنك تحميله في الذاكرة وسرعة تشغيله. +- جودة ناتج الدردشة للنموذج. + +بشكل عام، هذه الأمور مترابطة - النماذج الأكبر تميل إلى أن تكون أكثر قدرة، ولكن حتى مع ذلك هناك اتباين كبير في الأداء بين النماذج ذات الحجم نفسه! +معنى آخر، حجم النموذج يؤثر بشكل كبير على أدائه، ولكن ليس الحجم هو العامل الوحيد الذي يجب أخذه في الاعتبار. + +### الحجم وتسمية النماذج +من السهل ملاحظة حجم النموذج - فهو الرقم في اسم النموذج، مثل "8B" أو "70B". هذا هو عدد +**المعلمات** في النموذج. بدون التكميم، يجب أن تتوقع الحاجة إلى حوالي 2 بايت من الذاكرة لكل معلمة. +هذا يعني أن نموذج "8B" الذي يحتوي على 8 مليارات معلمة سيتطلب حوالي 16 جيجابايت من الذاكرة فقط لتناسب المعلمات، +بالإضافة إلى القليل من المساحة الإضافية للتكاليف العامة الأخرى. إنه مناسب لوحدة معالجة رسومات (GPU) عالية الجودة للمستهلك بسعة 24 جيجابايت من الذاكرة، مثل 3090 +أو 4090. +بعض نماذج الدردشة هي نماذج "مزيج من الخبراء". قد يتم سرد أحجام هذه النماذج بطرق مختلفة، مثل "8x7B" أو +"141B-A35B". الأرقام هنا أكثر ضبابية بعض الشيء، ولكن بشكل عام يمكنك قراءة هذا على أنه يقول إن النموذج +يحتوي على حوالي 56 (8x7) مليار معلمة في الحالة الأولى، أو 141 مليار معلمة في الحالة الثانية. + +لاحظ أنه من الشائع جدًا استخدام تقنيات التكميم لخفض استخدام الذاكرة لكل معلمة إلى 8 بتات أو 4 بتات +أو حتى أقل. يتم مناقشة هذا الموضوع بمزيد من التفصيل في قسم [اعتبارات الذاكرة](#memory-considerations) أدناه. + +### ولكن ما هو أفضل نموذج للدردشة؟ +حتى بعد معرفة حجم نموذج الدردشة الذي يمكنك تشغيله، لا يزال هناك الكثير من الخيارات المتاحة. إحدى الطرق للتنقل في +كل هذا هو استشارة **لوحات الصدارة**. اثنان من أكثر لوحات الصدارة شهرة هما [OpenLLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) +و [LMSys Chatbot Arena Leaderboard](https://chat.lmsys.org/?leaderboard). لاحظ أن لوحة صدارة LMSys +تشمل أيضًا نماذج خاصة - انظر إلى عمود `licence` لتحديد النماذج مفتوحة المصدر التي يمكنك تنزيلها، ثم +ابحث عنها على [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending). + +### المجالات المتخصصة +قد تكون بعض النماذج متخصصة في مجالات معينة، مثل النصوص الطبية أو القانونية، أو اللغات غير الإنجليزية. +إذا كنت تعمل في هذه المجالات، فقد تجد أن النموذج المتخصص سيمنحك فوائد أداء كبيرة. +لا تفترض ذلك تلقائيًا! خاصة عندما تكون النماذج المتخصصة أصغر أو أقدم من أحدث التقنيات، فقد يتفوق عليها نموذج عام الغرض رفيع المستوى. لحسن الحظ، بدأنا نرى +[لوحات الصدارة المتخصصة في المجال](https://huggingface.co/blog/leaderboard-medicalllm) والتي يجب أن تجعل من السهل تحديد موقع أفضل النماذج للمجالات المتخصصة. + +## ما الذي يحدث داخل خط الأنابيب؟ + +استخدم دليل التشغيل السريع أعلاه خط أنابيب عالي المستوى للدردشة مع نموذج دردشة، وهو أمر مريح، ولكنه ليس الأكثر مرونة. دعونا نتخذ نهجًا منخفض المستوى، لكي نرى كل خطوة من الخطوات التي تنطوي عليها الدردشة. دعونا نبدأ +بعينة من التعليمات البرمجية، ثم نقوم بتفكيكها: + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch + +# إعداد الإدخال كما هو الحال من قبل +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] + +# 1: تحميل النموذج والمحلل +model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", torch_dtype=torch.bfloat16) +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") + +# 2: تطبيق قالب الدردشة +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) +print("Formatted chat:\n", formatted_chat) + +# 3: تحليل الدردشة (يمكن دمج هذه الخطوة مع الخطوة السابقة باستخدام tokenize=True) +inputs = tokenizer(formatted_chat, return_tensors="pt", add_special_tokens=False) +# نقل المدخلات المحللة إلى نفس الجهاز الموجود عليه النموذج (GPU/CPU) +inputs = {key: tensor.to(model.device) for key, tensor in inputs.items()} +print("Tokenized inputs:\n", inputs) + +# 4: إنشاء نص من النموذج +outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.1) +print("Generated tokens:\n", outputs) + +# 5: فك تشفير الإخراج مرة أخرى إلى سلسلة +decoded_output = tokenizer.decode(outputs[0][inputs['input_ids'].size(1):], skip_special_tokens=True) +print("Decoded output:\n", decoded_output) +``` + +هناك الكثير هنا، ويمكن أن تكون كل قطعة وثيقة خاصة بها! بدلاً من الدخول في الكثير من التفاصيل، سأغطي +الأفكار العامة، وأترك التفاصيل للوثائق المرتبطة بها. الخطوات الرئيسية هي: +1. يتم تحميل [النماذج](https://huggingface.co/learn/nlp-course/en/chapter2/3) و [المُجزّئات اللغوية](https://huggingface.co/learn/nlp-course/en/chapter2/4?fw=pt) من Hugging Face Hub. +2. يتم تنسيق الدردشة باستخدام [قالب الدردشة](https://huggingface.co/docs/transformers/main/en/chat_templating) للمحلل +3. يتم [تحليل](https://huggingface.co/learn/nlp-course/en/chapter2/4) الدردشة المنسقة باستخدام مُجزّئ اللغوي. +4. نقوم [بتوليد](https://huggingface.co/docs/transformers/en/llm_tutorial) استجابة من النموذج. +5. يتم فك تشفير الرموز التي ينتجها النموذج مرة أخرى إلى سلسلة + +## الأداء والذاكرة والأجهزة + +من المحتمل أنك تعرف الآن أن معظم مهام التعلم الآلي يتم تشغيلها على وحدات معالجة الرسومات (GPU). ومع ذلك، من الممكن تمامًا +إنشاء نص من نموذج دردشة أو نموذج لغة على وحدة المعالجة المركزية (CPU)، على الرغم من أن ذلك أبطأ إلى حد ما. إذا كان بإمكانك وضع +النموذج في ذاكرة وحدة معالجة الرسومات (GPU)، فهذا عادة ما يكون الخيار المفضل. + +### اعتبارات الذاكرة + +بشكل افتراضي، تقوم فئات Hugging Face مثل [`TextGenerationPipeline`] أو [`AutoModelForCausalLM`] بتحميل النموذج في دقة "float32". وهذا يعني أنه يحتاج إلى 4 بايتات (32 بت) لكل معلمة، لذا فإن نموذج "8B" بحجم 8 مليار معلمة سيحتاج إلى ~32 جيجابايت من الذاكرة. ومع ذلك، يمكن أن يكون هذا مضيعة للموارد! يتم تدريب معظم نماذج اللغة الحديثة في دقة "bfloat16"، والتي تستخدم فقط 2 بايت لكل معلمة. إذا كان عتادك يدعم ذلك (Nvidia 30xx/Axxx أو أحدث)، فيمكنك تحميل النموذج في دقة "bfloat16"، باستخدام معامل "torch_dtype" كما فعلنا أعلاه. + +ومن الممكن أيضًا النزول إلى أقل من 16 بت باستخدام "التكميم"، وهي طريقة لضغط أوزان النموذج بطريقة تفقد بعض المعلومات. يسمح هذا بضغط كل معلمة إلى 8 بتات أو 4 بتات أو حتى أقل. لاحظ أنه، خاصة في 4 بتات، قد تتأثر جودة ناتج النموذج سلبًا، ولكن غالبًا ما يكون هذا مقايضة تستحق القيام بها لتناسب نموذج محادثة أكبر وأكثر قدرة في الذاكرة. دعنا كيف يمكننا تطبيق ذلك باستخدام مكتبة `bitsandbytes`: + +```python +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) # يمكنك أيضًا تجربة load_in_4bit +model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", quantization_config=quantization_config) +``` + +أو يمكننا القيام بنفس الشيء باستخدام واجهة برمجة التطبيقات "pipeline": + +```python +from transformers import pipeline, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) # يمكنك أيضًا تجربة load_in_4bit +pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config}) +``` + +هناك عدة خيارات أخرى لكمية نماذج بخلاف `bitsandbytes` - يرجى الاطلاع على [دليل التكميم](./quantization) لمزيد من المعلومات. + +### اعتبارات الأداء + + + +للحصول على دليل أكثر شمولاً حول أداء نموذج اللغة والتحسين، راجع [تحسين استدلال LLM](./llm_optims). + + + + +كقاعدة عامة، ستكون نماذج المحادثة الأكبر حجمًا أبطأ في توليد النصوص بالإضافة إلى احتياجها لذاكرة أكبرة. من الممكن أن تكون أكثر تحديدًا بشأن هذا: إن توليد النص من نموذج دردشة أمر غير عادي في أنه يخضع لقيود **سعة الذاكرة** بدلاً من قوة الحوسبة، لأن كل معلمة نشطة يجب قراءتها من الذاكرة لكل رمز ينشئه النموذج. وهذا يعني أن عدد الرموز في الثانية التي يمكنك توليدها من نموذج الدردشة يتناسب بشكل عام مع إجمالي حجم الذاكرة التي بوجد بها ا، مقسومًا على حجم النموذج. + +في مثالنا السريع أعلاه، كان حجم نموذجنا حوالي 16 جيجابايت عند تحميله في دقة "bfloat16". وهذا يعني أنه يجب قراءة 16 جيجابايت من الذاكرة لكل رمز ينشئه النموذج. يمكن أن يتراوح إجمالي سعة الذاكرة من 20-100 جيجابايت/ثانية لمعالجات المستهلكين إلى 200-900 جيجابايت/ثانية لمعالجات الرسومات للمستهلكين، ومعالجات Intel Xeon أو AMD Threadripper/Epyc أو Apple Silicon المتخصصةة، وأخيرًا يصل إلى 2-3 تيرابايت/ثانية لمعالجات مراكز البيانات مثل Nvidia A100 أو H100. يجب أن يعطيك هذا فكرة جيدة عن سرعة التوليد التي يمكنك توقعها من هذه الأنواع المختلفة من الأجهزة. + +لذلك، إذا كنت تريد تحسين سرعة توليد النص، فإن الحل الأسهل هو إما تقليل حجم النموذج في الذاكرة (عادةً عن طريق التكميم)، أو الحصول على عتاد بسرعة أكبر في الذاكرة. بالنسبة للمستخدمين المتقدمين، هناك عدة تقنيات أخرى للتغلب على هذه القيود. الأكثر شيوعًا هي المتغيرات على [التوليد بمساعدة](https://huggingface.co/blog/assisted-generation)، المعروف أيضًا باسم "العينات التخمينية (speculative sampling)". تحاول هذه التقنيات تخمين عدة رموز مستقبلية في وقت واحد، غالبًا باستخدام نموذج "مسودة (draft model)" أصغر، ثم تأكيد هذه التوليدات باستخدام نموذج الدردشة. إذا تم التحقق من صحة التخمينات بواسطة نموذج الدردشة، فيمكن إنشاء أكثر من رمز واحد لكل تمرير للأمام، مما يخفف بشكل كبير من القيود المتعلقة بالسعة ويحسن سرعة التوليد. + +أخيرًا، يجب أن نلاحظ أيضًا تأثير نماذج "مزيج الخبراء" "Mixture of Experts" (MoE) هنا. العديد من نماذج المحادثة الشهيرة، مثل Mixtral وQwen-MoE وDBRX، هي نماذج MoE. في هذه النماذج، لا تكون كل معلمة نشطة لكل رمز يتم إنشاؤه. ونتيجة لذلك، فإن نماذج MoE لديها عمومًا متطلبات ذاكرة أقل بكثير، على الرغم من أن حجمها الإجمالي يمكن أن يكون كبيرًا جدًا. لذلك يمكن أن تكون أسرع عدة مرات من نموذج "كثيف" عادي بنفس الحجم. ومع ذلك، فإن التقنيات مثل التوليد المساعد غير فعالة بشكل عام لهذه النماذج لأن المزيد من المعلمات ستصبح نشطة مع كل رمز جديد يتم التكهن به، والذي سيبطل فوائد السعة والسرعة التي توفرها بنية MoE. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/create_a_model.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/create_a_model.md new file mode 100644 index 0000000000000000000000000000000000000000..6b511fe0de4a8addbaf4e269e828ea3966580729 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/create_a_model.md @@ -0,0 +1,436 @@ +# إنشاء بنية مخصصة + +تحدد فئة [`AutoClass`](model_doc/auto) تلقائيًا بنية النموذج وتقوم بتنزيل تكوين وأوزان مسبقين للنموذج. بشكل عام، نوصي باستخدام `AutoClass` لإنتاج كود غير مرتبط بنسخة معينة. ولكن يمكن للمستخدمين الذين يريدون مزيدًا من التحكم في معلمات النموذج المحددة إنشاء نموذج مخصص من 🤗 Transformers من مجرد بضع فئات أساسية. قد يكون هذا مفيدًا بشكل خاص لأي شخص مهتم بدراسة نموذج 🤗 Transformers أو تدريبه أو إجراء تجارب عليه. في هذا الدليل، سنغوص بشكل أعمق في إنشاء نموذج مخصص بدون `AutoClass`. تعرف على كيفية: + +- تحميل تكوين النموذج وتخصيصه. +- إنشاء بنية نموذج. +- إنشاء مجزء لغوى سريع وبطيء للنص. +- إنشاء معالج صور لمهام الرؤية. +- إنشاء مستخرج ميزات لمهام الصوت. +- إنشاء معالج للمهام متعددة الوسائط. + +## التكوين + +يشير مصطلح [التكوين](main_classes/configuration) إلى الخصائص المحددة للنموذج. لكل تكوين نموذج خصائصه الخاصة؛ على سبيل المثال، تشترك جميع نماذج NLP في الخصائص `hidden_size` و`num_attention_heads` و`num_hidden_layers` و`vocab_size` المشتركة. تحدد هذه الخصائص عدد رؤوس الانتباه أو الطبقات المخفية لبناء نموذج بها. + +اطلع على [DistilBERT](model_doc/distilbert) من خلال [`DistilBertConfig`] لمعاينة خصائصه: + +```py +>>> from transformers import DistilBertConfig + +>>> config = DistilBertConfig() +>>> print(config) +DistilBertConfig { + "activation": "gelu", + "attention_dropout": 0.1, + "dim": 768, + "dropout": 0.1, + "hidden_dim": 3072, + "initializer_range": 0.02, + "max_position_embeddings": 512, + "model_type": "distilbert", + "n_heads": 12, + "n_layers": 6, + "pad_token_id": 0, + "qa_dropout": 0.1, + "seq_classif_dropout": 0.2, + "sinusoidal_pos_embds": false, + "transformers_version": "4.16.2", + "vocab_size": 30522 +} +``` + +يعرض [`DistilBertConfig`] جميع الخصائص الافتراضية المستخدمة لبناء نموذج [`DistilBertModel`] أساسي. جميع الخصائص قابلة للتعديل، مما ييتيح مجالاً للتجريب. على سبيل المثال، يمكنك تعديل نموذج افتراضي لـ: + +- تجربة دالة تنشيط مختلفة باستخدام معامل `activation`. +- استخدام معدل إسقاط أعلى الاحتمالات الانتباه مع معامل `attention_dropout`. + +```py +>>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4) +>>> print(my_config) +DistilBertConfig { + "activation": "relu", + "attention_dropout": 0.4, + +``` + +يمكن تعديل خصائص النموذج المدرب مسبقًا في دالة [`~PretrainedConfig.from_pretrained`] : + +```py +>>> my_config = DistilBertConfig.from_pretrained("distilbert/distilbert-base-uncased", activation="relu", attention_dropout=0.4) +``` + +بمجرد أن تصبح راضيًا عن تكوين نموذجك، يمكنك حفظه باستخدام [`~PretrainedConfig.save_pretrained`]. يتم تخزين ملف التكوين الخاص بك على أنه ملف JSON في دليل الحفظ المحدد: + +```py +>>> my_config.save_pretrained(save_directory="./your_model_save_path") +``` + +لإعادة استخدام ملف التكوين، قم بتحميله باستخدام [`~PretrainedConfig.from_pretrained`]: + +```py +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json") +``` + + +يمكنك أيضًا حفظ ملف التكوين كقاموس أو حتى كفرق بين خصائص التكوين المُعدّلة والخصائص التكوين الافتراضية! راجع وثائق [التكوين](main_classes/configuration) لمزيد من التفاصيل. + + + +## النموذج + +الخطوة التالية هي إنشاء [نموذج](main_classes/models). النموذج - ويُشار إليه أحيانًا باسم البنية - يُحدد وظيفة كل طبقة والعمليات الحسابية المُنفذة. تُستخدم خصائص مثل `num_hidden_layers` من التكوين لتحديد هذه البنية. تشترك جميع النماذج في فئة أساسية واحدة هي [`PreTrainedModel`] وبعض الوظائف المُشتركة مثل غيير حجم مُدخلات الكلمات وتقليص رؤوس آلية الانتباه الذاتي. بالإضافة إلى ذلك، فإن جميع النماذج هي فئات فرعية إما من [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)، [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) أو [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) . هذا يعني النماذج متوافقة مع كل استخدام لإطار العمل الخاص بها. + + + +قم بتحميل خصائص التكوين المخصصة الخاصة بك في النموذج: + +```py +>>> from transformers import DistilBertModel + +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json") +>>> model = DistilBertModel(my_config) +``` + +هذا ينشئ نموذجًا بقيم عشوائية بدلاً من الأوزان المُدربة مسبقًا. لن يكون هذا النموذج مفيدًا حتى يتم تدريبه. تُعد عملية التدريب مكلفة وتستغرق وقتًا طويلاً. من الأفضل بشكل عام استخدام نموذج مُدرب مسبقًا للحصول على نتائج أفضل بشكل أسرع، مع استخدام جزء بسيط فقط من الموارد المطلوبة للتدريب. + +قم بإنشاء نموذج مُدرب مسبقًا باستخدام [`~PreTrainedModel.from_pretrained`]: + +```py +>>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased") +``` + +عند بتحميل الأوزان المُدربة مسبقًا، يتم تحميل تكوين النموذج الافتراضي تلقائيًا إذا كان النموذج من مكتبة 🤗 Transformers. ومع ذلك، يمكنك أيضًا استبدال - بعض أو كل - سإعدادات النموذج الافتراضية بإعداداتك الخاصة: + +```py +>>> model = DistilBertModel.from_pretrained("distilbert/distilbert-base-uncased"، config=my_config) +``` + + +قم بتحميل خصائص التكوين المُخصصة الخاصة بك في النموذج: + +```py +>>> from transformers import TFDistilBertModel + +>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json") +>>> tf_model = TFDistilBertModel(my_config) +``` + +هذا ينشئ نموذجًا بقيم عشوائية بدلاً من الأوزان المُدربة مسبقًا. لن يكون هذا النموذج مفيدًا حتى يتم تدريبه. تُعد عملية التدريب مكلفة وتستغرق وقتًا طويلاً. من الأفضل بشكل عام استخدام نموذج مُدرب مسبقًا للحصول على نتائج أفضل بشكل أسرع، مع استخدام جزء بسيط فقط من الموارد المطلوبة للتدريب. + +قم بإنشاء نموذج مُدرب مسبقًا باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased") +``` + +عندما تقوم بتحميل الأوزان المُدربة مسبقًا،يتم تحميل إعدادات النموذج الافتراضي تلقائيًا إذا كان النموذج من مكتبة 🤗 Transformers. ومع ذلك، يمكنك أيضًا استبدال - بعض أو كل - إعدادات النموذج الافتراضية بإعداداتك الخاصة: + +```py +>>> tf_model = TFDistilBertModel.from_pretrained("distilbert/distilbert-base-uncased"، config=my_config) +``` + + + +### رؤوس النموذج + +في هذه المرحلة، لديك نموذج DistilBERT الأساسي الذي يخرج *حالات الكامنة*. تُمرَّر هذه الحالات الكامنة كمدخلات لرأس النموذج لإنتاج المخرجات النهائية. توفر مكتبة 🤗 Transformers رأس نموذج مختلف لكل مهمة طالما أن النموذج يدعم المهمة (أي لا يمكنك استخدام DistilBERT لمهمة تسلسل إلى تسلسل مثل الترجمة). + + + +على سبيل المثال، [`DistilBertForSequenceClassification`] هو نموذج DistilBERT الأساس مزودًا برأس تصنيف تسلسلي. يُشكّل رأس التصنيف التسلسلي طبقة خطية فوق المخرجات المجمعة. + +```py +>>> from transformers import DistilBertForSequenceClassification + +>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام هذا نقطة التحقق هذه لمهمة أخرى بسهولة، وذلك بتغيير رأس النموذج.ففي مهمة الإجابة على الأسئلة، ستستخدم رأس النموذج [`DistilBertForQuestionAnswering`]. رأس الإجابة على الأسئلة مشابه لرأس التصنيف التسلسلي باستثناء أنه طبقة خطية فوق مخرجات الحالات الكامنة. + +```py +>>> from transformers import DistilBertForQuestionAnswering + +>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + + +على سبيل المثال، [`TFDistilBertForSequenceClassification`] هو نموذج DistilBERT الأساسي برأس تصنيف تسلسل. رأس التصنيف التسلسلي هو طبقة خطية أعلى المخرجات المجمعة. + +```py +>>> from transformers import TFDistilBertForSequenceClassification + +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أعد استخدام هذا نقطة التحقق لمهمة أخرى عن طريق التبديل إلى رأس نموذج مختلف. لمهمة الإجابة على الأسئلة، ستستخدم رأس النموذج [`TFDistilBertForQuestionAnswering`]. رأس الإجابة على الأسئلة مشابه لرأس التصنيف التسلسلي باستثناء أنه طبقة خطية أعلى حالات الإخراج المخفية. + +```py +>>> from transformers import TFDistilBertForQuestionAnswering + +>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + + + +## مجزئ النصوص + +الفئة الأساسية الأخيرة التي تحتاجها قبل استخدام نموذج للبيانات النصية هي [مجزئ النصوص](main_classes/tokenizer) لتحويل النص الخام إلى تنسورات (tensors). هناك نوعان من المحولات الرموز التي يمكنك استخدامها مع 🤗 Transformers: + +- [`PreTrainedTokenizer`]: تنفيذ Python لمجزئ النصوص. + - [`PreTrainedTokenizerFast`]: مجزئ النصوص من مكتبة [🤗 Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) المُبنية على لغة Rust. هذا النوع من المجزئات أسرع بكثير، خاصةً عند معالجة دفعات النصوص، وذلك بفضل تصميمه بلغة Rust. كما يوفر مجزئ النصوص السريع طرقًا إضافية مثل *مخطط الإزاحة* الذي يُطابق الرموز بكلماتها أو أحرفها الأصلية. + +يدعم كلا النوعين من المجزئات طرقًا شائعة مثل الترميز وفك الترميز، وإضافة رموز جديدة، وإدارة الرموز الخاصة. + + + +لا يدعم كل نموذج مجزئ النصوص سريع. الق نظرة على هذا [جدول](index#supported-frameworks) للتحقق مما إذا كان النموذج يحتوي على دعم مجزئ النصوص سريع. + + + +إذا دربت مجزئ النصوص خاص بك، فيمكنك إنشاء واحد من *قاموسك*:``` + +```py +>>> from transformers import DistilBertTokenizer + +>>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt"، do_lower_case=False، padding_side="left") +``` + +من المهم أن تتذكر أن قاموس مجزئ النصوص المُخصص سيكون مختلفًا عن قاموس مجزئ النصوص نموذج مُدرّب مسبقًا. يجب عليك استخدام قاموس نموذج مُدرّب مسبقًا إذا كنت تستخدم نموذجًا مُدرّبًا مسبقًا، وإلا فلن تكون المدخلات ذات معنى. قم بإنشاء مجزئ النصوص باستخدام قاموس نموذج مُدرّب مسبقًا باستخدام فئة [`DistilBertTokenizer`]: + +```py +>>> from transformers import DistilBertTokenizer + +>>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +قم بإنشاء مجزئ نصوص سريع باستخدام فئة [`DistilBertTokenizerFast`]: + +```py +>>> from transformers import DistilBertTokenizerFast + +>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert/distilbert-base-uncased") +``` + + +افتراضيًا، سيحاول [`AutoTokenizer`] تحميل مجزئ نصوص سريع. يمكنك تعطيل هذا السلوك عن طريق تعيين `use_fast=False` في `from_pretrained`. + + +## معالج الصور + +يعالج معالج الصور بيانات الرؤية. وهو يرث من الفئة الأساسية [`~image_processing_utils.ImageProcessingMixin`]. + +لبناء معالج صور خاص بالنموذج المستخدم، أنشئ مثلاً مُعالج [`ViTImageProcessor`] افتراضيًا إذا كنت تستخدم [ViT](model_doc/vit) لتصنيف الصور: + +```py +>>> from transformers import ViTImageProcessor + +>>> vit_extractor = ViTImageProcessor() +>>> print(vit_extractor) +ViTImageProcessor { + "do_normalize": true, + "do_resize": true, + "image_processor_type": "ViTImageProcessor", + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "resample": 2, + "size": 224 +} +``` + + + +إذا كنت لا تبحث عن أي تخصيص، فما عليك سوى استخدام طريقة `from_pretrained` لتحميل معلمات معالج الصور الافتراضية للنموذج. + + + +عدل أيًا من معلمات [`ViTImageProcessor`] لإنشاء معالج الصور المخصص الخاص بك: + +```py +>>> from transformers import ViTImageProcessor + +>>> my_vit_extractor = ViTImageProcessor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3]) +>>> print(my_vit_extractor) +ViTImageProcessor { + "do_normalize": false, + "do_resize": true, + "image_processor_type": "ViTImageProcessor", + "image_mean": [ + 0.3, + 0.3, + 0.3 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "resample": "PIL.Image.BOX", + "size": 224 +} +``` +## العمود الفقري + +
+ +
+ +تتكون نماذج رؤية الحاسب من جزء أساسي، وجزء وسيط، وجزء معالجة نهائي. يستخرج الجزء الأساسي الميزات من صورة الإدخال، ويجمع الجزء الوسيط هذه الميزات المستخرجة ويعززها، ويُستخدم الجزء النهائي للمهمة الرئيسية (مثل اكتشاف الأجسام). ابدأ عبتهيئة الجزء الأساسي في تكوين النموذج وحدد ما إذا كنت تريد تحميل أوزان مدربة مسبقًا أو أوزانًا عشوائية. بعد ذلك، يمكنك تمرير تكوين النموذج إلى جزء المعالجة النهائي. + +على سبيل المثال، لتحميل [ResNet](../model_doc/resnet) backbone في نموذج [MaskFormer](../model_doc/maskformer) مع رأس تجزئة مثيل: + + + + +قم بتعيين `use_pretrained_backbone=True` لتحميل الأوزان المسبقة التدريب لـ ResNet للعمود الفقري. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + + + + +قم بتعيين `use_pretrained_backbone=False` لتهيئة جزء ResNet الأساسي بشكل عشوائي. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=False) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +يمكنك أيضًا تحميل تكوين الجزء الأساسي بشكل منفصل، ثم تمريره إلى تكوين النموذج.``` + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig + +backbone_config = ResNetConfig() +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + + + + +يتم تحميل نماذج [timm](https://hf.co/docs/timm/index) داخل نموذج باستخدام `use_timm_backbone=True` أو باستخدام [`TimmBackbone`] و [`TimmBackboneConfig`]. + +استخدم `use_timm_backbone=True` و `use_pretrained_backbone=True` لتحميل أوزان timm المُدرّبة مسبقًا للجزء الأساسي. + +```python +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_pretrained_backbone=True, use_timm_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +قم بتعيين `use_timm_backbone=True` و `use_pretrained_backbone=False` لتحميل عمود فقري timm مبدئي عشوائي. + +```python +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_pretrained_backbone=False, use_timm_backbone=True) # تكوين الجزء الأساسي والجزء الوسيط +model = MaskFormerForInstanceSegmentation(config) # جزء المعالجة النهائي +``` + +يمكنك أيضًا تحميل تكوين الجزء الأساسي واستخدامه لإنشاء `TimmBackbone` أو تمريره إلى تكوين النموذج. سيتم تحميلأوزان الجزء الأساسي لـ Timm المُدرّبة مسبقًا افتراضيًا. عيّن `use_pretrained_backbone=False` لتحميل الأوزان المبدئية العشوائية. + +```python +from transformers import TimmBackboneConfig, TimmBackbone + +backbone_config = TimmBackboneConfig("resnet50", use_pretrained_backbone=False) + +# قم بإنشاء مثيل من العمود الفقري +backbone = TimmBackbone(config=backbone_config) + +# قم بإنشاء نموذج باستخدام عمود فقري timm +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + +## مستخرج الميزات + +يقوم مُستخرج الميزات بمعالجة المدخلات الصوتية. يرث من فئة الأساس [`~feature_extraction_utils.FeatureExtractionMixin`]، وقد يرث أيضًا من فئة [`SequenceFeatureExtractor`] لمعالجة المدخلات الصوتية. + +للاستخدام، قم بإنشاء مستخرج ميزات مرتبط بالنموذج الذي تستخدمه. على سبيل المثال، قم بإنشاء مستخرج ميزات Wav2Vec2 الافتراضي إذا كنت تستخدم [Wav2Vec2](model_doc/wav2vec2) لتصنيف الصوت: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> w2v2_extractor = Wav2Vec2FeatureExtractor() +>>> print(w2v2_extractor) +Wav2Vec2FeatureExtractor { + "do_normalize": true, + "feature_extractor_type": "Wav2Vec2FeatureExtractor", + "feature_size": 1, + "padding_side": "right", + "padding_value": 0.0, + "return_attention_mask": false, + "sampling_rate": 16000 +} +``` + + +إذا لم تكن بحاجة لأي تخصيص، فاستخدم فقط طريقة `from_pretrained` لتحميل معلمات مستخرج الميزات الافتراضية للنموذج. + + +قم بتعديل أي من معلمات [`Wav2Vec2FeatureExtractor`] لإنشاء مستخرج ميزات مخصص: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000، do_normalize=False) +>>> print(w2v2_extractor) +Wav2Vec2FeatureExtractor { + "do_normalize": false, + "feature_extractor_type": "Wav2Vec2FeatureExtractor"، + "feature_size": 1، + "padding_side": "right"، + "padding_value": 0.0، + "return_attention_mask": false، + "sampling_rate": 8000 +} +``` + +## المعالج + +بالنسبة للنماذج التي تدعم مهام الوسائط المتعددة، توفر مكتبة 🤗 Transformers فئة معالج تجمع بفاعلية فئات المعالجة مثل مستخرج الميزات ومقسّم الرموز في كائن واحد. على سبيل المثال، دعنا نستخدم [`Wav2Vec2Processor`] لمهمة التعرف الآلي على الكلام (ASR). تقوم مهمة ASR بتحويل الصوت إلى نص، لذلك ستحتاج إلى مستخرج ميزات ومقسّم رموز. + +قم بإنشاء مستخرج ميزات لمعالجة المدخلات الصوتية: + +```py +>>> from transformers import Wav2Vec2FeatureExtractor + +>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True) +``` + +قم بإنشاء مقسّم رموز لمعالجة المدخلات النصية: + +```py +>>> from transformers import Wav2Vec2CTCTokenizer + +>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt") +``` + +قم بدمج مستخرج الميزات ومقسّم الرموز في [`Wav2Vec2Processor`]: + +```py +>>> from transformers import Wav2Vec2Processor + +>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer) +``` + +باستخدام فئتين أساسيتين - التكوين والنموذج - بالإضافة إلى فئة معالجة مسبق (مقسّم رموز أو معالج صورة أو مستخرج ميزات أو معالج)، يمكنك إنشاء أي من النماذج التي تدعمها مكتبة 🤗 Transformers. يمكن تكوين كل من هذه الفئات الأساسية، مما يسمح لك باستخدام السمات المطلوبة. يمكنك بسهولة تهيئة نموذج للتدريب أو تعديل نموذج مدرب مسبقاً لإجراء ضبط دقيق. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/custom_models.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/custom_models.md new file mode 100644 index 0000000000000000000000000000000000000000..daaba5e54ee2f65282df6b6adecb6a7dbcdbd32d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/custom_models.md @@ -0,0 +1,323 @@ +# بناء نماذج مخصصة + +تم تصميم مكتبة 🤗 Transformers لتكون قابلة للتوسيع بسهولة. كل نموذج مُشفّر بالكامل في مجلد فرعي معين بالمستودع، دون أي تجريد، لذلك يمكنك بسهولة نسخ ملف النمذجة وتعديله وفقًا لاحتياجاتك. + +إذا كنت تُنشئ نموذجًا جديدًا تمامًا، فقد يكون من الأسهل البدء من الصفر. في هذا البرنامج التعليمي، سنُرِيك كيفية كتابة نموذج مخصص وتكوينه ليُستخدم داخل Transformers، وكيفية مشاركته مع المجتمع (مع الكود الذي يعتمد عليه) بحيث يمكن لأي شخص استخدامه، حتى إذا لم يكن موجودًا في مكتبة 🤗 Transformers. سنرى كيفية البناء على المحولات ونوسّع الإطار باستخدام الأدوات التي يمكن استخدامها لتعديل سلوك الإطار (hooks) والتعليمات البرمجية المخصصة. + +سنوضح كل هذا من خلال نموذج ResNet، بتغليف فئة ResNet من +[مكتبة timm](https://github.com/rwightman/pytorch-image-models) داخل [`PreTrainedModel`]. + +## كتابة إعدادات مخصصة + +لنبدأ بكتابة إعدادات النموذج. إعدادات النموذج هو كائنٌ يحتوي على جميع المعلومات اللازمة لبنائه. كما سنرى لاحقًا، يتطلب النموذج كائن `config` لتهيئته، لذا يجب أن يكون هذا الكائن كاملاً. + + + +تتبع النماذج في مكتبة `transformers` اتفاقية قبول كائن `config` في دالة `__init__` الخاصة بها، ثم تمرر كائن `config` بالكامل إلى الطبقات الفرعية في النموذج، بدلاً من تقسيمه إلى معامﻻت متعددة. يؤدي كتابة نموذجك بهذا الأسلوب إلى كود أبسط مع "مصدر حقيقة" واضح لأي فرط معلمات، كما يسهل إعادة استخدام الكود من نماذج أخرى في `transformers`. + + + +في مثالنا، سنعدّل بعض الوسائط في فئة ResNet التي قد نرغب في ضبطها. ستعطينا التكوينات المختلفة أنواع ResNets المختلفة الممكنة. سنقوم بتخزين هذه الوسائط بعد التحقق من صحته. + +```python +from transformers import PretrainedConfig +from typing import List + + +class ResnetConfig(PretrainedConfig): + model_type = "resnet" + + def __init__( + self, + block_type="bottleneck", + layers: List[int] = [3, 4, 6, 3], + num_classes: int = 1000, + input_channels: int = 3, + cardinality: int = 1, + base_width: int = 64, + stem_width: int = 64, + stem_type: str = "", + avg_down: bool = False, + **kwargs, + ): + if block_type not in ["basic", "bottleneck"]: + raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.") + if stem_type not in ["", "deep", "deep-tiered"]: + raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.") + + self.block_type = block_type + self.layers = layers + self.num_classes = num_classes + self.input_channels = input_channels + self.cardinality = cardinality + self.base_width = base_width + self.stem_width = stem_width + self.stem_type = stem_type + self.avg_down = avg_down + super().__init__(**kwargs) +``` +الأشياء الثلاثة المهمة التي يجب تذكرها عند كتابة تكوينك الخاص هي: + +- يجب أن ترث من `PretrainedConfig`، +- يجب أن تقبل دالة `__init__` الخاصة بـ `PretrainedConfig` أي معامﻻت إضافية kwargs، +- يجب تمرير هذه المعامﻻت الإضافية إلى دالة `__init__` فى الفئة الأساسية الاعلى. + +يضمن الإرث حصولك على جميع الوظائف من مكتبة 🤗 Transformers، في حين أن القيدين التانى والثالث يأتيان من حقيقة أن `PretrainedConfig` لديه المزيد من الحقول أكثر من تلك التي تقوم بتعيينها. عند إعادة تحميل تكوين باستخدام طريقة `from_pretrained`، يجب أن يقبل تكوينك هذه الحقول ثم إرسالها إلى الفئة الأساسية الأعلى. + +تحديد `model_type` لتكوينك (هنا `model_type="resnet"`) ليس إلزاميًا، ما لم ترغب في +تسجيل نموذجك باستخدام الفئات التلقائية (راجع القسم الأخير). + +مع القيام بذلك، يمكنك بسهولة إنشاء تكوينك وحفظه مثلما تفعل مع أي تكوين نموذج آخر في +المكتبة. إليك كيفية إنشاء تكوين resnet50d وحفظه: + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d_config.save_pretrained("custom-resnet") +``` + +سيؤدي هذا إلى حفظ ملف باسم `config.json` داخل مجلد `custom-resnet`. يمكنك بعد ذلك إعادة تحميل تكوينك باستخدام +طريقة `from_pretrained`: + +```py +resnet50d_config = ResnetConfig.from_pretrained("custom-resnet") +``` + +يمكنك أيضًا استخدام أي طريقة أخرى من فئة [`PretrainedConfig`]، مثل [`~PretrainedConfig.push_to_hub`] لتحميل تكوينك مباشرة إلى Hub. + +## كتابة نموذج مخصص + +الآن بعد أن أصبح لدينا تكوين ResNet، يمكننا المتابعة لإنشاء نموذجين: الأول يستخرج الميزات المخفية من دفعة من الصور (مثل [`BertModel`]) والآخر مناسب لتصنيف الصور (مثل [`BertForSequenceClassification`]). + + كما ذكرنا سابقًا، سنقوم ببناء نموذج مبسط لتسهيل الفهم في هذا المثال. الخطوة الوحيدة المطلوبة قبل كتابة هذه الفئة هي لربط أنواع وحدات البناء بفئات ذات وحدات بناء فعلية. بعد ذلك، يُعرّف النموذج من خلال التكوين عبر تمرير كل شيء إلى فئة `ResNet`: + +```py +from transformers import PreTrainedModel +from timm.models.resnet import BasicBlock, Bottleneck, ResNet +from .configuration_resnet import ResnetConfig + + +BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck} + + +class ResnetModel(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor): + return self.model.forward_features(tensor) +``` + +بالنسبة للنموذج الذي سيصنف الصور، فإننا نغير فقط طريقة التقديم: + +```py +import torch + + +class ResnetModelForImageClassification(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor, labels=None): + logits = self.model(tensor) + if labels is not None: + loss = torch.nn.cross_entropy(logits, labels) + return {"loss": loss, "logits": logits} + return {"logits": logits} +``` +في كلتا الحالتين، لاحظ كيف نرث من `PreTrainedModel` ونستدعي مُهيئ الفئة الرئيسية باستخدام `config` (كما تفعل عند إنشاء وحدة `torch.nn.Module` عادية). ليس من الضروري تعريف `config_class` إلا إذا كنت ترغب في تسجيل نموذجك مع الفئات التلقائية (راجع القسم الأخير). + + + +إذا كان نموذجك مشابهًا جدًا لنموذج داخل المكتبة، فيمكنك إعادة استخدام نفس التكوين مثل هذا النموذج. + + + +يمكن لنموذجك أن يعيد أي شيء تريده، ولكن إعادة قاموس مثلما فعلنا لـ +`ResnetModelForImageClassification`، مع تضمين الخسارة عند تمرير العلامات، سيجعل نموذجك قابلًا للاستخدام مباشرة داخل فئة [`Trainer`]. يعد استخدام تنسيق إخراج آخر أمرًا جيدًا طالما أنك تخطط لاستخدام حلقة تدريب خاصة بك أو مكتبة أخرى للتدريب. + +الآن بعد أن أصبح لدينا فئة النموذج، دعنا ننشئ واحدة: + +```py +resnet50d = ResnetModelForImageClassification(resnet50d_config) +``` + +يمكنك استخدام أي من طرق فئة [`PreTrainedModel`]، مثل [`~PreTrainedModel.save_pretrained`] أو +[`~PreTrainedModel.push_to_hub`]. سنستخدم الثاني في القسم التالي، وسنرى كيفية دفع أوزان النموذج مع كود نموذجنا. ولكن أولاً، دعنا نحمل بعض الأوزان المُعلمة مسبقًا داخل نموذجنا. + +في حالة الاستخدام الخاصة بك، فمن المحتمل أن تقوم بتدريب نموذجك المخصص على بياناتك الخاصة. للانتقال بسرعة خلال هذا البرنامج التعليمي، +سنستخدم الإصدار المُعلم مسبقًا من resnet50d. نظرًا لأن نموذجنا هو مجرد غلاف حوله، فمن السهل نقل هذه الأوزان: + +```py +import timm + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +الآن دعونا نرى كيفية التأكد من أنه عند قيامنا بـ [`~PreTrainedModel.save_pretrained`] أو [`~PreTrainedModel.push_to_hub`]، يتم حفظ كود النموذج. + +## تسجيل نموذج مع كود مخصص للفئات التلقائية + +إذا كنت تكتب مكتبة توسع 🤗 Transformers، فقد ترغب في توسيع الفئات التلقائية لتشمل نموذجك الخاص. يختلف هذا عن نشر الكود إلى Hub بمعنى أن المستخدمين سيحتاجون إلى استيراد مكتبتك للحصول على النماذج المخصصة (على عكس تنزيل كود النموذج تلقائيًا من Hub). + +ما دام تكوينك يحتوي على معامل `model_type` مختلفة عن أنواع النماذج الحالية، وأن فئات نماذجك لديك لديها الخصائص الصحيحة `config_class`، فيمكنك ببساطة إضافتها إلى الفئات التلقائية مثل هذا: + +```py +from transformers import AutoConfig, AutoModel, AutoModelForImageClassification + +AutoConfig.register("resnet", ResnetConfig) +AutoModel.register(ResnetConfig, ResnetModel) +AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification) +``` + +لاحظ أن الحجة الأولى المستخدمة عند تسجيل تكوينك المخصص لـ [`AutoConfig`] يجب أن تتطابق مع `model_type` +من تكوينك المخصص، والحجة الأولى المستخدمة عند تسجيل نماذجك المخصصة لأي فئة نموذج تلقائي يجب +أن تتطابق مع `config_class` من تلك النماذج. + +## إرسال الكود إلى Hub + + + +هذا API تجريبي وقد يكون له بعض التغييرات الطفيفة في الإصدارات القادمة. + + + +أولاً، تأكد من تعريف نموذجك بالكامل في ملف `.py`. يمكن أن يعتمد على الاستيراد النسبي لملفات أخرى طالما أن جميع الملفات موجودة في نفس الدليل (لا ندعم الوحدات الفرعية لهذه الميزة حتى الآن). في مثالنا، سنحدد ملف `modeling_resnet.py` وملف `configuration_resnet.py` في مجلد باسم "resnet_model" في دليل العمل الحالي. يحتوي ملف التكوين على كود لـ `ResnetConfig` ويحتوي ملف النمذجة على كود لـ `ResnetModel` و`ResnetModelForImageClassification`. + +``` +. +└── resnet_model + ├── __init__.py + ├── configuration_resnet.py + └── modeling_resnet.py +``` + +يمكن أن يكون ملف `__init__.py` فارغًا، فهو موجود فقط حتى يتمكن Python من اكتشاف أن `resnet_model` يمكن استخدامه كموديل. + + + +إذا كنت تقوم بنسخ ملفات النمذجة من المكتبة، فسوف تحتاج إلى استبدال جميع الواردات النسبية في أعلى الملف +لاستيرادها من حزمة `transformers`. + + + +لاحظ أنه يمكنك إعادة استخدام (أو توسيع) تكوين/نموذج موجود. + +لمشاركة نموذجك مع المجتمع، اتبع الخطوات التالية: أولاً، قم باستيراد نموذج ResNet والتكوين من الملفات التي تم إنشاؤها حديثًا: + +```py +from resnet_model.configuration_resnet import ResnetConfig +from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification +``` + +بعد ذلك، يجب عليك إخبار المكتبة بأنك تريد نسخ ملفات الكود الخاصة بهذه الكائنات عند استخدام طريقة `save_pretrained` +وتسجيلها بشكل صحيح باستخدام فئة تلقائية (خاصة للنماذج)، ما عليك سوى تشغيل: + +```py +ResnetConfig.register_for_auto_class() +ResnetModel.register_for_auto_class("AutoModel") +ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification") +``` + +لاحظ أنه لا توجد حاجة لتحديد فئة تلقائية للتكوين (هناك فئة تلقائية واحدة فقط لها، +[`AutoConfig`]) ولكن الأمر يختلف بالنسبة للنماذج. قد يكون نموذجك المخصص مناسبًا للعديد من المهام المختلفة، لذلك يجب +تحديد أي من الفئات التلقائية هو الصحيح لنموذجك. + + + +استخدم `register_for_auto_class()` إذا كنت تريد نسخ ملفات الكود. إذا كنت تفضل استخدام الكود على Hub من مستودع آخر، +فلا تحتاج إلى استدعائه. في الحالات التي يوجد فيها أكثر من فئة تلقائية واحدة، يمكنك تعديل ملف `config.json` مباشرة باستخدام +الهيكل التالي: + +```json +"auto_map": { + "AutoConfig": "--", + "AutoModel": "--", + "AutoModelFor": "--", +}, +``` + + + +بعد ذلك، دعنا نقوم بإنشاء التكوين والنماذج كما فعلنا من قبل: + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d = ResnetModelForImageClassification(resnet50d_config) + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +الآن لإرسال النموذج إلى Hub، تأكد من تسجيل الدخول. إما تشغيل في المحطة الأوامر الطرفية الخاصة بك: + +```bash +huggingface-cli login +``` + +أو من دفتر ملاحظات: + +```py +from huggingface_hub import notebook_login + +notebook_login() +``` + +يمكنك بعد ذلك الضغط على مساحة الاسم الخاصة بك (أو منظمة أنت عضو فيها) مثل هذا: + +```py +resnet50d.push_to_hub("custom-resnet50d") +``` + +بالإضافة إلى أوزان النمذجة والتكوين بتنسيق json، فقد قام هذا أيضًا بنسخ ملفات النمذجة والتكوين `.py` في مجلد `custom-resnet50d` وتحميل النتيجة إلى Hub. يمكنك التحقق من النتيجة في هذا [مستودع النموذج](https://huggingface.co/sgugger/custom-resnet50d). + +راجع [البرنامج التعليمي للمشاركة](model_sharing) لمزيد من المعلومات حول طريقة الدفع إلى المحور. + +### استخدام نموذج مع كود مخصص + +يمكنك استخدام أي تكوين أو نموذج أو مقسم لغوي مع ملفات برمجة مخصصة في مستودعه باستخدام الفئات التلقائية و دالة `from_pretrained`.تُفحص جميع الملفات والرموز المرفوع إلى Hub بحثًا عن البرامج الضارة (راجع وثائق [أمان Hub](https://huggingface.co/docs/hub/security#malware-scanning) لمزيد من المعلومات)، ولكن يجب عليك مراجعة كود النموذج والمؤلف لتجنب تنفيذ التعليمات البرمجية الضارة على جهازك. لتفعيل نموذج يحتوي على شفرة برمجية مخصصة، عيّن `trust_remote_code=True`: + +```py +from transformers import AutoModelForImageClassification + +model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True) +``` + +يُنصح بشدة بتحديد رقم إصدار (commit hash) كـ `revision` للتأكد من عدم تعديل مؤلف النموذج للشفرة لاحقًابإضافة أسطر ضارة (إلا إذا كنت تثق تمامًا بمؤلفي النموذج): + +```py +commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292" +model = AutoModelForImageClassification.from_pretrained( + "sgugger/custom-resnet50d"، trust_remote_code=True، revision=commit_hash +) +``` + +لاحظ وجود زرّ لنسخ رقم إصدار بسهولة عند تصفح سجل التزامات مستودع النموذج على منصة Hugging Face. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/fast_tokenizers.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/fast_tokenizers.md new file mode 100644 index 0000000000000000000000000000000000000000..539712969e813ffeeb47c0676320ec6255d20180 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/fast_tokenizers.md @@ -0,0 +1,51 @@ +# استخدام مجزئيات النصوص من 🤗 Tokenizers + +يعتمد [`PreTrainedTokenizerFast`] على مكتبة [🤗 Tokenizers](https://huggingface.co/docs/tokenizers). يمكن تحميل المجزئات اللغويين الذين تم الحصول عليهم من مكتبة 🤗 Tokenizers ببساطة شديدة في 🤗 Transformers. + +قبل الدخول في التفاصيل، دعونا نبدأ أولاً بإنشاء مُجزىء لغوي تجريبي في بضع سطور: + +```python +>>> from tokenizers import Tokenizer +>>> from tokenizers.models import BPE +>>> from tokenizers.trainers import BpeTrainer +>>> from tokenizers.pre_tokenizers import Whitespace + +>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]")) +>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) + +>>> tokenizer.pre_tokenizer = Whitespace() +>>> files = [...] +>>> tokenizer.train(files, trainer) +``` + +الآن لدينا مُجزىء لغوي مدرب على الملفات التي حددناها. يمكننا إما الاستمرار في استخدامه في وقت التشغيل هذا، أو حفظه في ملف JSON لإعادة استخدامه لاحقًا. + +## تحميل مُجزئ النّصوص مُباشرةً + +دعونا نرى كيف يمكننا الاستفادة من كائن (مُجزئ النصوص) في مكتبة 🤗 Transformers. تسمح فئة [`PreTrainedTokenizerFast`] سهولة إنشاء *tokenizer*، من خلال قبول كائن *المُجزئ النصوص* مُهيّأ مُسبقًا كمعامل: + +```python +>>> from transformers import PreTrainedTokenizerFast + +>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) +``` + +يمكن الآن استخدام هذا الكائن مع جميع الطرق المُشتركة بين مُجزّئي النّصوص لـ 🤗 Transformers! انتقل إلى [صفحة مُجزّئ النّصوص](main_classes/tokenizer) لمزيد من المعلومات. + +## التحميل من ملف JSON + +لتحميل مُجزّئ النص من ملف JSON، دعونا نبدأ أولاً بحفظ مُجزّئ النّصوص: + +```python +>>> tokenizer.save("tokenizer.json") +``` + +يمكن تمرير المسار الذي حفظنا به هذا الملف إلى طريقة تهيئة [`PreTrainedTokenizerFast`] باستخدام المُعامل `tokenizer_file`: + +```python +>>> from transformers import PreTrainedTokenizerFast + +>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json") +``` + +يمكن الآن استخدام هذا الكائن مع جميع الطرق التي تشترك فيها مُجزّئي النّصوص لـ 🤗 Transformers! انتقل إلى [صفحة مُجزّئ النص](main_classes/tokenizer) لمزيد من المعلومات. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/gguf.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/gguf.md new file mode 100644 index 0000000000000000000000000000000000000000..cdb20c5640a689f197b24090543c013354da7fb8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/gguf.md @@ -0,0 +1,89 @@ +# GGUF وتفاعلها مع المحولات + +تُستخدم صيغة ملف GGUF لتخزين النماذج للاستدلال باستخدام [GGML](https://github.com/ggerganov/ggml) والمكتبات الأخرى التي تعتمد عليه، مثل [llama.cpp](https://github.com/ggerganov/llama.cpp) أو [whisper.cpp](https://github.com/ggerganov/whisper.cpp) الشهيرة جدًا. + +إنها صيغة ملف [مدعومة من قبل Hugging Face Hub](https://huggingface.co/docs/hub/en/gguf) مع ميزات تسمح بالفحص السريع للموترات والبيانات الوصفية داخل الملف. + +تم تصميم تنسيق الملف هذا كـ "تنسيق ملف واحد" حيث يحتوي ملف واحد عادةً على كل من سمات التكوين ومفردات المجزىء اللغوي والخصائص الأخرى، بالإضافة إلى جميع الموترات التي سيتم تحميلها في النموذج. تأتي هذه الملفات بتنسيقات مختلفة وفقًا لنوع التكميم في الملف. نلقي نظرة موجزة على بعضها [هنا](https://huggingface.co/docs/hub/en/gguf#quantization-types). + +## الدعم داخل المحولات + +أضفنا القدرة على تحميل ملفات `gguf` داخل `المحولات` لتوفير قدرات تدريب/ضبط إضافية لنماذج gguf، قبل إعادة تحويل تلك النماذج إلى `gguf` لاستخدامها داخل نظام `ggml`. عند تحميل نموذج، نقوم أولاً بإلغاء تكميمه إلى fp32، قبل تحميل الأوزان لاستخدامها في PyTorch. + +> [!NOTE] +> لا يزال الدعم تجريبيًا للغاية ونرحب بالمساهمات من أجل ترسيخه عبر أنواع التكميم وبنى النماذج. + +فيما يلي، بنيات النماذج وأنواع التكميم المدعومة: + +### أنواع التكميم المدعومة + +تُحدد أنواع التكميم المدعومة مبدئيًا وفقًا لملفات التكميم الشائعة التي تمت مشاركتها على Hub. + +- F32 +- F16 +- BF16 +- Q4_0 +- Q4_1 +- Q5_0 +- Q5_1 +- Q8_0 +- Q2_K +- Q3_K +- Q4_K +- Q5_K +- Q6_K +- IQ1_S +- IQ1_M +- IQ2_XXS +- IQ2_XS +- IQ2_S +- IQ3_XXS +- IQ3_S +- IQ4_XS +- IQ4_NL + +> [!NOTE] +> لدعم إلغاء تكميم gguf، يلزم تثبيت `gguf>=0.10.0`. + +### بنيات النماذج المدعومة + +في الوقت الحالي، بنيات النماذج المدعومة هي البنيات التي كانت شائعة جدًا على Hub، وهي: + +- LLaMa +- Mistral +- Qwen2 +- Qwen2Moe +- Phi3 +- Bloom +- Falcon +- StableLM +- GPT2 +- Starcoder2 +- T5 + +## مثال الاستخدام + +لتحميل ملفات `gguf` في `transformers`، يجب تحديد معامل `gguf_file` فى دالة `from_pretrained` لكل من المُجزّئ اللغوية والنموذج. فيما يلي كيفية تحميل المُجزّئ اللغوي ونموذج، يمكن تحميلهما من نفس الملف: + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" +filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf" + +tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename) +model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename) +``` + +الآن لديك إمكانية الوصول إلى النسخة الكامل غير المكممة للنموذج في بيئة PyTorch، حيث يمكنك دمجه مع مجموعة كبيرة من الأدوات الأخرى. + +لإعادة التحويل إلى ملف `gguf`، نوصي باستخدام ملف [`convert-hf-to-gguf.py`](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) من llama.cpp. + +فيما يلي كيفية إكمال البرنامج النصي أعلاه لحفظ النموذج وإعادة تصديره مرة أخرى إلى `gguf`: + +```py +tokenizer.save_pretrained('directory') +model.save_pretrained('directory') + +!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory} +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/glossary.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..81753bad281b40ee0b94c0c319aec8a49d0f9b8d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/glossary.md @@ -0,0 +1,446 @@ +# قاموس المصطلحات + +يحدد هذا المسرد مصطلحات التعلم الآلي العامة و 🤗 Transformers لمساعدتك على فهم الوثائق بشكل أفضل. + +## A + +### قناع الانتباه (Attention Mask) + +قناع الانتباه هو مُدخل اختياري يستخدم عند تجميع التسلسلات معًا + + + +يشير هذا المُدخل إلى النموذج أى الرموز المميزة (tokens) التي يجب الانتباه إليها، وأيها لا ينبغي ذلك. + +على سبيل المثال، تأمّل هذين التسلسُلين : + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence_a = "This is a short sequence." +>>> sequence_b = "This is a rather long sequence. It is at least longer than sequence A." + +>>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] +>>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] +``` + +لدى الإصدارات المشفرة أطوال مختلفة: + +```python +>>> len(encoded_sequence_a), len(encoded_sequence_b) +(8, 19) +``` + +لذلك، لا يمكننا وضعها معًا في نفس المصفوفة كما هي. يجب إضافة حشو إلى التسلسل الأول حتى يصل إلى طول التسلسل الثاني، أو يجب تقليص الثاني إلى طول الأول. + +في الحالة الأولى، يتم تمديد قائمة المعرفات بواسطة مؤشرات الحشو. يمكننا تمرير قائمة إلى المحلل اللغوي وطلب منه إضافة الحشو بهذه الطريقة: + +```python +>>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) +``` + +يمكننا أن نرى أنه تمت إضافة اصفار على يمين الجملة الأولى لجعلها بنفس طول الجملة الثانية: + +```python +>>> padded_sequences["input_ids"] +[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] +``` + +يمكن بعد ذلك تحويل هذا إلى مصفوفة في PyTorch أو TensorFlow. قناع الانتباه هو مصفوفة ثنائية تشير إلى +موضع المؤشرات المحشوه بحيث لا ينتبه إليها النموذج. بالنسبة إلى [`BertTokenizer`]`1` يشير إلى +قيمة يجب الانتباه إليها، في حين يشير `0` إلى قيمة مبطنة. يُمكن إيجاد قناع الانتباه في القاموس الذي يُعيده مُجزِّئ النصوص (tokenizer) تحت المفتاح "attention_mask". +```python +>>> padded_sequences["attention_mask"] +[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] +``` + +### نماذج الترميز التلقائي (autoencoding models) + +راجع [نماذج الترميز](#encoder-models) و [نمذجة اللغة المقنعة](#masked-language-modeling-mlm) + +### النماذج ذاتية الانحدار (Autoregressive Models) + +راجع [نمذجة اللغة السببية](#causal-language-modeling) و [نماذج فك التشفير](#decoder-models) + +## B + +### العمود الفقري (backbone) + +يُمثل العمود الفقري الشبكة العصبونية (الترميزات والطبقات) المسؤولة عن إخراج الحالات الخفية أو المُميزات الأولية. عادة ما يكون متصلاً بـ [رأس](#head) يستقبل المُميزات كمدخلات لإجراء تنبؤ. على سبيل المثال، يُعد النموذج [`ViTModel`] عمودًا فقريًا دون رأس مُحدد مُرفق به. يمكن أيضًا استخدام `ViTModel` كعمود فقري في نماذج أخرى, مثل [DPT](model_doc/dpt). + +## C + +### نمذجة اللغة السببية (أو التنبؤية) causal language modeling + +مهمة ما قبل التدريب يقوم فيها النموذج بقراءة النصوص بالترتيب ويتنبأ بالكلمة التالية. يتم ذلك عادةً من خلال قراءة الجملة كاملةً، ولكن مع استخدام قناع داخل النموذج لإخفاء الرموز المميزة اللاحقة في خطوة زمنية معينة. + + + +### قناة(channel) + +تتكون الصور الملونة من مزيج من القيم في ثلاث قنوات لونية: الأحمر والأخضر والأزرق (RGB) بينما تحتوي صور ذات التدرج رمادي على قناة واحدة فقط. في مكتبة 🤗 Transformers، يمكن أن تكون القناة اللونية البُعد الأول أو الأخير في مُصفوفة الصورة: [`n_channels`، `height`، `width`] أو [`height`، `width`، `n_channels`]. + +### التصنيف الزمني التوصيلي connectionist temporal classification (CTC) + +خوارزمية تسمح للنموذج بالتعلم دون معرفة كيفية محاذاة المدخلات مع المخرجات بدقة؛ يحسب CTC توزيع جميع المخرجات المحتملة لمدخلات مُحددة ويختار المخرج الأكثر احتمالًا. تُستخدم CTC بشكل شائع في مهام التعرف على الكلام نظرًا لأن الكلام المنطوق لا يتوافق دائمًا بشكل مُباشر مع النص المكتوب، لأسباب مختلفة مثل معدلات الكلام المختلفة للمتكلم. + +### الالتفاف (Convolution) + +نوع من الطبقات في شبكة عصبية، حيث تُضرب مصفوفة الإدخال عُنصرًا بُعنصر بمصفوفة أصغر تُسمى (النواة أو المرشح) ويتم جمع القيم في مصفوفة جديدة. يُعرف هذا باسم عملية الالتفاف التي يتم تكرارها عبر مصفوفة الإدخال بأكملها. تُطبق كل عملية التفاف على جزء مُختلف من مصفوفة الإدخال. تُستخدم الشبكات العصبية الالتفافية (CNNs) بشكل شائع في رؤية الحاسوب. + +## D + +### التوازي على مستوى البيانات (DataParallel - DP) + +هي تقنية تُستخدم لتدريب النماذج على عدة وحدات معالجة رسومات (GPUs)، حيث يتم نسخ نفس إعداد التدريب عدة مرات، بحيث تتلقى كل نسخة شريحة مختلفة من البيانات يتم تنفيذ المعالجة بالتوازي ويتم مزامنة جميع الإعدادات في نهاية كل خطوة تدريب. + +تعرف على المزيد حول كيفية عمل DataParallel [هنا](perf_train_gpu_many#dataparallel-vs-distributeddataparallel). + +### معرفات مدخلات وحدة فك التشفير (decoder input IDs) + +هذا المدخل خاص بنماذج الترميز وفك التشفير، ويحتوي على معرفات الإدخال التي سيتم تغذيتها إلى وحدة فك التشفير. +يجب استخدام هذه المدخلات لمهام التسلسل إلى التسلسل، مثل الترجمة أو التلخيص، وعادة ما يتم بناؤها بطريقة محددة لكل نموذج. + +تقوم معظم نماذج الترميز وفك التشفير (BART، T5) بإنشاء معرفات `decoder_input_ids` الخاصة بها من `labels`. في مثل هذه النماذج، +يعد تمرير `labels` هو الطريقة المفضلة للتعامل مع التدريب. + +يرجى التحقق من وثائق كل نموذج لمعرفة كيفية تعاملها مع معرفات الإدخال هذه للتدريب على التسلسل إلى التسلسل. + +### نماذج فك التشفير (decoder models) + +يُشار إليها أيضًا باسم نماذج التنبؤية الذاتية، وتنطوي نماذج فك التشفير على مهمة ما قبل التدريب (تسمى نمذجة اللغة السببية) حيث يقرأ النموذج النصوص بالترتيب ويتعين عليه التنبؤ بالكلمة التالية. يتم ذلك عادةً عن طريق +قراءة الجملة بأكملها مع قناع لإخفاء الرموز المميزة المستقبلية في خطوة زمنية معينة. + + +### التعلم العميق deep learning (DL) +خوارزميات التعلم الآلي التي تستخدم الشبكات العصبية متعددة الطبقات. + +## E + +### نماذج الترميز (encoder models) + +تُعرف أيضًا باسم نماذج الترميز التلقائي، وتأخذ نماذج الترميز إدخالًا (مثل النص أو الصور) وتحويلها إلى تمثيل رقمي مكثف يُطلق عليه الترميز. غالبًا ما يتم تدريب نماذج الترميز مسبقًا باستخدام تقنيات مثل [نمذجة اللغة المقنعة](#masked-language-modeling-mlm)، والتي تقوم بإخفاء أجزاء من تسلسل الإدخال وإجبار النموذج على إنشاء تمثيلات أكثر دلالة (فائدة ووضوحاً). + + + +## F +### استخراج الميزات (feature extraction) + +عملية اختيار وتحويل البيانات الأولية إلى مجموعة من الميزات الأكثر إفادة وفائدة لخوارزميات التعلم الآلي. بعض الأمثلة على استخراج الميزات تشمل تحويل النص الأولي/الخام إلى ترميزات الكلمات واستخراج ميزات مهمة مثل الحواف أو الأشكال من بيانات الصور/الفيديو. + +### تجزئة التغذية الأمامية (feed forward chunking) + +في كل وحدة الانتباه الباقية في المحولات، تلي طبقة الاهتمام الانتباه عادة طبقتان للتغذية الأمامية. +حجم تضمين الطبقة الأمامية الوسيطة أكبر عادة من حجم المخفي للنموذج (على سبيل المثال، لـ +`google-bert/bert-base-uncased`). +بالنسبة لإدخال بحجم `[batch_size, sequence_length]`، يمكن أن تمثل الذاكرة المطلوبة لتخزين التضمينات الأمامية الوسيطة `[batch_size، sequence_length, config.intermediate_size]` جزءًا كبيرًا من استخدام الذاكرة. لاحظ مؤلفو (https://arxiv.org/abs/2001.04451)[Reformer: The Efficient Transformer] أنه نظرًا لأن الحساب مستقل عن بعد `sequence_length`، فإنه من المكافئ رياضيًا حساب تضمينات الإخراج الأمامية `[batch_size، config.hidden_size]_0, ..., [batch_size، `config_size]_n +فردياً والتوصيل بها لاحقًا إلى `[batch_size, sequence_length, config.hidden_size]` مع `n = sequence_length`، والذي يتداول زيادة وقت الحساب مقابل تقليل استخدام الذاكرة، ولكنه ينتج عنه نتيجة مكافئة رياضيا. + +بالنسبة للنماذج التي تستخدم الدالة `[apply_chunking_to_forward]`، يحدد `chunk_size` عدد التضمينات يتم حساب الإخراج بالتوازي وبالتالي يحدد المقايضة بين حجم الذاكرة والتعقيد الوقت. إذا تم تعيين `chunk_size` إلى `0`، فلن يتم إجراء تجزئة التغذية الأمامية. + + +### النماذج المضبوطة (finetuned models) + +الضبط الدقيق هو شكل من أشكال نقل التعلم، يتضمن أخذ نموذج مُدرّب مسبقًا، وتجميد أوزانه، واستبدال طبقة الإخراج برأس نموذج مُضاف حديثًا. يتم تدريب رأس النموذج على مجموعة البيانات المستهدفة. + +راجع البرنامج التعليمي [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) لمزيد من التفاصيل، وتعرف على كيفية ضبط النماذج باستخدام 🤗 Transformers. + +## H + +### رأس النموذج (head) + +يشير رأس النموذج إلى الطبقة الأخيرة من الشبكة العصبية التي تقبل الحالات المخفية الخام/الأولية وتُسقطها على بُعد مختلف. يوجد رأس نموذج مختلف لكل مهمة. + + * [`GPT2ForSequenceClassification`] هو رأس تصنيف تسلسل - طبقة خطية - أعلى نموذج [`GPT2Model`] الأساسي. + * [`ViTForImageClassification`] هو رأس تصنيف صورة - طبقة خطية أعلى حالة مخفية نهائية للرمز `CLS` - أعلى نموذج [`ViTModel`] الأساسي. + * [`Wav2Vec2ForCTC`] هو رأس نمذجة اللغة مع [CTC](#connectionist-temporal-classification-ctc) أعلى نموذج [`Wav2Vec2Model`] الأساسي. + +## I + +### رقعة الصور (image patch) + +"رقعة الصورة" في نماذج المحولات البصرية، تُقسم الصورة إلى أجزاء أصغر تسمى "رقعات". يتم تمثيل كل رقعة بشكل رقمي (تحويلها إلى مجموعة من الأرقام) ثم تُعالج كسلسلة من البيانات. يمكنك العثور على حجم الرُقعة patch_size - أو دقتها - في إعدادات النموذج. + +### الاستدلال (Inference) + +الاستدلال هو عملية تقييم نموذج على بيانات جديدة بعد اكتمال التدريب. راجع البرنامج التعليمي [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) لمعرفة كيفية إجراء الاستدلال باستخدام 🤗 Transformers. + +### معرفات الإدخال (input IDs) + +معرفات الإدخال هي غالبًا المعلمات المطلوبة الوحيدة التي يجب تمريرها إلى النموذج كإدخال. هذه المعرفات عبارة عن أرقام تمثل كل كلمة أو رمز في الجملة التي نريد أن يفهمها النموذج. بمعنى آخر، هي طريقة لترجمة الكلمات إلى أرقام يتم استخدامها كإدخال بواسطة النموذج. + + + +يعمل كل محلل لغوي بشكل مختلف ولكن الآلية الأساسية تبقى كما هي. إليك مثال باستخدام محلل BERT اللغوي، والذي يعد محلل لغوي [WordPiece](https://arxiv.org/pdf/1609.08144.pdf): + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence = "A Titan RTX has 24GB of VRAM" +``` + +يتولى المحلل اللغوي مهمة تقسيم التسلسل إلى رموز مميزة متوفرة في قاموس المحلل اللغوي. + +```python +>>> tokenized_sequence = tokenizer.tokenize(sequence) +``` + +االرموز إما كلمات أو أجزاء كلمات. هنا على سبيل المثال، لم تكن كلمة "VRAM" موجودة في مفردات النموذج، لذلك تم تقسيمها إلى "V" و "RA" و "M". للإشارة إلى أن هذه الرموز ليست كلمات منفصلة ولكنها أجزاء من نفس الكلمة، تمت إضافة بادئة مزدوجة (#) إلى "RA" و "M": +```python +>>> print(tokenized_sequence) +['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] +``` +```python +>>> print(tokenized_sequence) +['A'، 'Titan'، 'R'، '##T'، '##X'، 'has'، '24'، '##GB'، 'of'، 'V'، '##RA'، '##M'] +``` + +يمكن بعد ذلك تحويل هذه الرموز إلى مُعرفات يفهمها النموذج. يمكن القيام بذلك عن طريق تغذية الجملة مباشرةً إلى مُجزّئ الرموز، والذي يستفيد من تنفيذ 🤗 Tokenizers بلغة Rust للحصول على أعلى أداء. + +```python +>>> inputs = tokenizer(sequence) +``` + +يقوم المحلل اللغوي بإرجاع قاموس يحتوي على جميع المعلومات التي يحتاجها النموذج للعمل بشكل صحيح. وتوجد مؤشرات الرموز المميزة تحت مفتاح `input_ids`: + +```python +>>> encoded_sequence = inputs["input_ids"] +>>> print(encoded_sequence) +[101، 138، 18696، 155، 1942، 3190، 1144، 1572، 13745، 1104، 159، 9664، 2107، 102] +``` + +لاحظ أن المحلل اللغوي يضيف تلقائيًا "رموزًا خاصة" (إذا كان النموذج المرتبط يعتمد عليها) وهي معرفات خاصة +يستخدمها النموذج في بعض الأحيان. + +إذا قمنا بفك تشفير التسلسل السابق، + +```python +>>> decoded_sequence = tokenizer.decode(encoded_sequence) +``` + +سنرى + +```python +>>> print(decoded_sequence) +[CLS] A Titan RTX has 24GB of VRAM [SEP] +``` + +لأن هذه هي الطريقة التي يتوقع بها نموذج [`BertModel`] إدخالاته. + +## L + +### االملصقات (Labels) + +هي معامل اختياري يمكن إدخاله في النموذج لحساب الخسارة بنفسه. +نماذج تصنيف التسلسل: ([BertForSequenceClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع للتسلسل بأكمله. +نماذج تصنيف الرمز: ([BertForTokenClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. +نماذج النمذجة اللغوية المقنعة:([BertForMaskedLM]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي: تكون الملصقات هي معرف رمز الكلمة المقنعة، والقيم الأخرى يتم تجاهلها (عادةً -100). +مهام التسلسل إلى التسلسل: ([BartForConditionalGeneration], [MBartForConditionalGeneration]) يتوقع النموذج مصفوفة ذات بعد (batch_size, tgt_seq_length) حيث تتوافق كل قيمة مع التسلسل الهدف المرتبط بكل تسلسل مدخل. أثناء التدريب، سيقوم كل من BART و T5 بإنشاء decoder_input_ids و decoder attention masks داخليًا. عادةً لا يلزم توفيرها. هذا لا ينطبق على النماذج التي تستخدم إطار العمل Encoder-Decoder. +نماذج تصنيف الصور: ([ViTForImageClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل صورة فردية. +نماذج التقسيم الدلالي: ([SegformerForSemanticSegmentation]) يتوقع النموذج مصفوفة ذات بعد (batch_size, height, width) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل بكسل فردي. +نماذج اكتشاف الأجسام: ([DetrForObjectDetection]) يتوقع النموذج قائمة من القواميس تحتوي على مفتاح class_labels و boxes حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع وعدد المربعات المحيطة بكل صورة فردية. +نماذج التعرف التلقائي على الكلام: ([Wav2Vec2ForCTC]) يتوقع النموذج مصفوفة ذات بعد (batch_size, target_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. + + + +قد تختلف تسميات كل نموذج، لذا تأكد دائمًا من مراجعة وثائق كل نموذج للحصول على معلومات حول التسميات الخاصة به. + + +لا تقبل النماذج الأساسية ([`BertModel`]) الملصقات ، لأنها نماذج المحول الأساسية، والتي تقوم ببساطة بإخراج الميزات. + +### نماذج اللغة الكبيرة large language models (LLM) + +مصطلح عام يشير إلى نماذج اللغة المحولة (GPT-3 و BLOOM و OPT) التي تم تدريبها على كمية كبيرة من البيانات. تميل هذه النماذج أيضًا إلى وجود عدد كبير من المعلمات القابلة للتعلم (على سبيل المثال، 175 مليار لمعلمة GPT-3). + +## M + +### نمذجة اللغة المقنعة masked language modeling (MLM) + +مهمة تدريب مسبق حيث يرى النموذج نسخة تالفة من النصوص، وعادة ما يتم ذلك عن طريق حجب بعض الرموز بشكل عشوائي، ويتعين على النموذج التنبؤ بالنص الأصلي. + +### متعدد الوسائط (multimodal) + +مهمة تجمع بين النصوص مع نوع آخر من المدخلات (على سبيل المثال، الصور). + +## N + +### توليد اللغة الطبيعية Natural language generation (NLG) + +جميع المهام المتعلقة بتوليد النص (على سبيل المثال، [اكتب باستخدام المحولات](https://transformer.huggingface.co/)، والترجمة). + +### معالجة اللغة الطبيعية Natural language processing (NLP) + +طريقة عامة للقول "التعامل مع النصوص". + +### فهم اللغة الطبيعية Natural language understanding (NLU) + +جميع المهام المتعلقة بفهم ما هو موجود في نص (على سبيل المثال تصنيف النص بأكمله، أو الكلمات الفردية). + +## P + +### خط الأنابيب (pipeline) + +في مكتبة Transformers، يُشير مصطلح "خط الأنابيب" إلى سلسلة من الخطوات التي يتم تنفيذها بترتيب محدد لمعالجة البيانات وتحويلها وإرجاع تنبؤ من نموذج. بعض المراحل الشائعة في خط الأنابيب قد تشمل معالجة البيانات الأولية، واستخراج الميزات، والتوحيد. + +للحصول على مزيد من التفاصيل، راجع [خطوط الأنابيب للاستدلال](https://huggingface.co/docs/transformers/pipeline_tutorial). + +### التوازي على مستوى خط الأنابيب (PipelineParallel) + +تقنية توازي يتم فيها تقسيم النموذج رأسياً (على مستوى الطبقة) عبر وحدات معالجة الرسومات (GPU) متعددة، بحيث توجد طبقة واحدة أو عدة طبقات من النموذج على وحدة معالجة الرسومات (GPU) واحدة فقط. تقوم كل وحدة معالجة رسومات (GPU) بمعالجة مراحل مختلفة من خط الأنابيب بالتوازي والعمل على جزء صغير من الدفعة. تعرف على المزيد حول كيفية عمل PipelineParallel [هنا](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism). + +### قيم البكسل (pixel values) + +مصفوفة من التمثيلات الرقمية لصورة يتم تمريرها إلى نموذج. تأخذ قيم البكسل شكل [`batch_size`، `num_channels`، `height`، `width`]، ويتم إنشاؤها من معالج الصور. + +### التجميع (Pooling) + +هي عملية تقوم بتقليص مصفوفة إلى مصفوفة أصغر، إما عن طريق أخذ القيمة القصوى أو المتوسط الحسابي للأبعاد التي يتم تجميعها. توجد طبقات التجميع بشكل شائع بين الطبقات التلافيفية convolutional layers لتقليل حجم تمثيل الميزات. + +### معرفات الموضع (position IDs) + +على عكس الشبكات العصبية المتكررة (RNNs) التي تتضمن موضع كل رمز (token) ضمن بنيتها، لا تدرك المحولات موضع كل رمز. لذلك، تستخدم معرفات الموضع (`position_ids`) من قبل النموذج لتحديد موضع كل رمز في قائمة الرموز. + +إنها معلمة اختيارية. إذا لم يتم تمرير أي `position_ids` إلى النموذج، يتم إنشاء المعرفات تلقائيًا كترميزات موضعية مطلقة. + +يتم اختيار الترميزات الموضعية المطلقة في النطاق `[0، config.max_position_embeddings - 1]`. تستخدم بعض النماذج أنواعًا أخرى من الترميزات الموضعية، مثل الترميزات الموضعية الجيبية أو الترميزات الموضعية النسبية. + +### ما قبل المعالجة (preprocessing) + +مهمة إعداد البيانات الخام بتنسيق يمكن أن تستهلكه نماذج التعلم الآلي بسهولة. على سبيل المثال، عادةً ما تتم معالجة النص مسبقًا عن طريق التمييز. للحصول على فكرة أفضل عن كيفية ظهور المعالجة المسبقة لأنواع الإدخال الأخرى، راجع البرنامج التعليمي [Preprocess](https://huggingface.co/docs/transformers/preprocessing). + +### النموذج المسبق التدريب (pretrained model) + +نموذج تم تدريبه مسبقًا على بعض البيانات (على سبيل المثال، كل Wikipedia). تنطوي طرق التدريب المسبق على هدف ذاتي الإشراف، والذي يمكن أن يكون قراءة النص ومحاولة التنبؤ بالكلمة التالية ( راجع (causal-language-modeling#)[نمذجة اللغة السببية] ) أو قناع بعض الكلمات ومحاولة التنبؤ بها ( راجع (masked-language#)[نمذجة اللغة المقنعة]- عرض MLM). + +لدى نماذج الكلام والرؤية أهدافها التدريبية المسبقة الخاصة. على سبيل المثال، Wav2Vec2 هو نموذج كلام تم تدريبه مسبقًا على مهمة تباينية تتطلب من النموذج تحديد تمثيل الكلام "الحقيقي" من مجموعة من تمثيلات الكلام "الخاطئة". من ناحية أخرى، BEiT هو نموذج رؤية تم تدريبه مسبقًا على مهمة نمذجة صورة مقنعة تقوم بقناع بعض رقع الصورة وتتطلب من النموذج التنبؤ بالرقع المقنعة (مشابهة لهدف نمذجة اللغة المقيدة). + +## R + +### شبكة عصبية متكررة (RNN) + +هي نوع من النماذج التي تستخدم حلقة متكررة فوق طبقة معينة لمعالجة النصوص. + +### التعلم التمثيلي (representation learning) + +هو فرع من فروع تعلم الآلة يركز على تعلم تمثيلات ذات معنى للبيانات الخام. بعض الأمثلة على تقنيات التعلم التمثيلي تشمل تضمين الكلمات، والمشفرات ذاتية، وشبكات التنافس التوليدية(GANs). + +## S + +### معدل العينات (sampling rate) + +قياس، بالهرتز، لعدد العينات (إشارة الصوت) المأخوذة في الثانية. ينتج معدل العينات عن تمييز إشارة مستمرة مثل الكلام. + +### الانتباه الذاتي (Self-Attention) + +هو آلية تتيح لكل عنصر في المدخل أن يحدد أي العناصر الأخرى في نفس المدخل يجب أن ينتبه إليها. + +### التعلم الذاتي الخاضع للإشراف (supervised learning) + +فئة من تقنيات التعلم الآلي التي يقوم فيها النموذج بإنشاء هدفه التعليمي الخاص من البيانات غير الموسومة. يختلف عن [التعلم غير الخاضع للإشراف](#unsupervised-learning) و [التعلم الخاضع للإشراف](#supervised-learning) في أن عملية التعلم خاضعة للإشراف، ولكن ليس صراحة من المستخدم. + +مثال واحد على التعلم الذاتي الخاضع للإشراف هو [نمذجة اللغة المقيدة](#masked-language- عرض MLM)، حيث يتم تمرير جمل للنموذج مع إزالة نسبة من رموزه ويتعلم التنبؤ بالرموز المفقودة. + +### التعلم شبه الخاضع للإشراف (semi-supervised learning) + +فئة واسعة من تقنيات تدريب التعلم الآلي التي تستفيد من كمية صغيرة من البيانات الموسومة مع كمية أكبر من البيانات غير الموسومة لتحسين دقة النموذج، على عكس [التعلم الخاضع للإشراف](#supervised-learning) و [التعلم غير الخاضع للإشراف](#unsupervised-learning). + +مثال على نهج التعلم شبه الخاضع للإشراف هو "التدريب الذاتي"، حيث يتم تدريب نموذج على بيانات موسومة، ثم يستخدم لتقديم تنبؤات حول البيانات غير الموسومة. يتم إضافة الجزء من البيانات غير الموسومة التي يتنبأ بها النموذج بأكبر قدر من الثقة إلى مجموعة البيانات الموسومة ويتم استخدامها لإعادة تدريب النموذج. + +### تسلسل إلى تسلسل (seq2seq) + +نماذج تولد تسلسلًا جديدًا من إدخال، مثل نماذج الترجمة، أو نماذج التلخيص (مثل [Bart](model_doc/bart) أو [T5](model_doc/t5)). + +### Sharded DDP + +اسم آخر لمفهوم [Zero Redundancy Optimizer](#zero-redundancy-optimizer-zero) الأساسي كما هو مستخدم من قبل العديد من التطبيقات الأخرى لـ Zero. + +### الخطوة (Stride) + +في العمليات التلافيفية أو التجميعية، تشير الخطوة إلى المسافة التي يتحرك بها النواة (kernel) فوق المصفوفة. خطوة تساوي 1 تعني أن النواة تتحرك بكسل واحد في كل مرة. + +### التعلم الخاضع للإشراف (supervised learning) + +هو نوع من تدريب النماذج التي تستخدم بيانات مُعلَّمة بشكل مباشر لتصحيح أداء النموذج وتوجيهه. يتم تغذية البيانات إلى النموذج قيد التدريب، ويتم مقارنة تنبؤاته بالنتائج الصحيحة المعروفة. يقوم النموذج بتعديل أوزانه بناءً على مدى خطأ تنبؤاته، وتتكرر هذه العملية لتحسين أداء النموذج. + +## T + +### توازي Tensor (TP) + +تقنية توازي لتدريب وحدات معالجة الرسومات (GPU) متعددة يتم فيها تقسيم المصفوفة إلى عدة أجزاء، لذا بدلاً من وجود المصفوفة بأكملها على وحدة معالجة الرسومات (GPU) واحدة، توجد كل شظية من المصفوفة على وحدة معالجة الرسومات (GPU) المخصصة لها. تتم معالجة الشظايا بشكل منفصل وبالتوازي على وحدات معالجة الرسومات (GPU) المختلفة ويتم مزامنة النتائج في نهاية خطوة المعالجة. هذا ما يُطلق عليه أحيانًا التوازي الأفقي، حيث يحدث الانقسام على المستوى الأفقي. + +تعرف على المزيد حول توازي Tensor [هنا](perf_train_gpu_many#tensor-parallelism). + +### الرمز اللغوي (Token) + +جزء من جملة، عادة ما يكون كلمة، ولكن يمكن أن يكون أيضًا كلمة فرعية (غالبًا ما يتم تقسيم الكلمات غير الشائعة إلى كلمات فرعية) أو علامة ترقيم. + +### معرفات نوع الرمز (token type ids) + +الغرض من بعض النماذج هو إجراء التصنيف على أزواج من الجمل أو الإجابة على الأسئلة. + + + +يتطلب ذلك تسلسلين مختلفين يتم دمجهما في إدخال "input_ids" واحد، والذي يتم عادةً باستخدام رموز خاصة، مثل رموز التصنيف (`[CLS]`) والفاصل (`[SEP]`). على سبيل المثال، يقوم نموذج BERT ببناء إدخال تسلسلين على النحو التالي: + +```python +>>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] +``` + +يمكننا استخدام برنامجنا للتمييز لإنشاء مثل هذه الجملة تلقائيًا عن طريق تمرير التسلسلين إلى `tokenizer` كمعامليين (وليس قائمة، كما كان من قبل) مثل هذا: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") +>>> sequence_a = "HuggingFace is based in NYC" +>>> sequence_b = "Where is HuggingFace based?" + +>>> encoded_dict = tokenizer(sequence_a، sequence_b) +>>> decoded = tokenizer.decode(encoded_dict["input_ids"]) +``` + +والذي سيعيد: + +```python +>>> print(decoded) +[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based؟ [SEP] +``` + +هذا يكفي لبعض النماذج لفهم أين ينتهي تسلسل واحد وأين يبدأ الآخر. ومع ذلك، تستخدم نماذج أخرى، مثل BERT، أيضًا معرفات نوع الرمز (يُطلق عليها أيضًا معرفات الجزء). يتم تمثيلها كماسك ثنائي لتحديد نوعي التسلسل في النموذج. + +يعيد برنامج الترميز هذا القناع كإدخال "token_type_ids": + +```python +>>> encoded_dict["token_type_ids"] +[0، 0، 0، 0، 0، 0، 0، 0، 0، 0، 1، 1، 1، 1، 1، 1، 1، 1، 1] +``` + +يتم تمثيل التسلسل الأول، "السياق" المستخدم للسؤال، بجميع رموزه بواسطة `0`، في حين يتم تمثيل التسلسل الثاني، المقابل إلى "السؤال"، بجميع رموزه بواسطة `1`. + +تستخدم بعض النماذج، مثل [`XLNetModel`] رمزًا إضافيًا يمثله `2`. + +### التعلم الانتقالي (Transfer Learning) + +تقنية تنطوي على أخذ نموذج تم تدريبه مسبقًا وتكييفه مع مجموعة بيانات خاصة بمهمتك. بدلاً من تدريب نموذج من الصفر، يمكنك الاستفادة من المعرفة المكتسبة من نموذج موجود كنقطة بداية. يسرع هذا عملية التعلم ويقلل من كمية بيانات التدريب المطلوبة. + +### المحول (Transformer) + +هو بنية لنموذج تعلم عميق يعتمد على الانتباه الذاتي. + +## U + +### التعلم غير الخاضع للإشراف (unsupervised learning) + +شكل من أشكال تدريب النماذج حيث لا يتم وضع علامات على البيانات المقدمة إلى النموذج. تستفيد تقنيات التعلم غير الخاضعة للإشراف من المعلومات الإحصائية لتوزيع البيانات للعثور على الأنماط المفيدة للمهمة المعنية. + +## Z + +### محسن التكرار الصفري (ZeRO) + +تقنية توازي تقوم بتشظية المصفوفات بطريقة مشابهة لـ [TensorParallel](#tensor-parallelism-tp)، باستثناء إعادة بناء المصفوفة بالكامل في الوقت المناسب لحساب التقدير أو الحساب الخلفي، وبالتالي لا يلزم تعديل النموذج. تدعم هذه الطريقة أيضًا تقنيات الإخلاء المختلفة للتعويض عن ذاكرة GPU المحدودة. + +تعرف على المزيد حول Zero [هنا](perf_train_gpu_many#zero-data-parallelism). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/how_to_hack_models.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/how_to_hack_models.md new file mode 100644 index 0000000000000000000000000000000000000000..8ce3589732f06aee0de0bde51843af967f0e26a7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/how_to_hack_models.md @@ -0,0 +1,163 @@ +# كيفية تعديل أي نموذج من نماذج Transformers + +توفر مكتبة [🤗 Transformers](https://github.com/huggingface/transformers) مجموعة من النماذج المسبقة التدريب والأدوات لمعالجة اللغات الطبيعية، والرؤية، وما إلى ذلك. على الرغم من أن هذه النماذج تغطي مجموعة واسعة من التطبيقات، فقد تواجه حالات استخدام لا تدعمها المكتبة بشكل افتراضي. يُمكن للتخصيص أن يفتح إمكانيات جديدة، مثل إضافة طبقات جديدة، أو تعديل البنية المعمارية، أو تحسين آليات الانتباه. سيُوضح لك هذا الدليل كيفية تعديل نماذج Transformers الموجودة لتلبية احتياجاتك المحددة. الشيء الرائع هو أنك لست بحاجة إلى الخروج من إطار عمل Transformers لإجراء هذه التغييرات. ي يمكنك تعديل النماذج مباشرةً في Transformers والاستفادة من الميزات مثل [واجهة برمجة التطبيقات Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer)، و [PreTrainedModel](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel)، والضبط الدقيق الفعال باستخدام أدوات مثل [PEFT](https://huggingface.co/docs/peft/index). + +سنرشدك في هذا الدليل لكيفية تخصيص نماذج Transformers الموجودة لتلبية متطلباتك، دون فقدان مزايا الإطار. ستتعلم كيفية: + +- تعديل بنية نموذج ما من خلال تغيير آلية الانتباه الخاصة به. +- تطبيق تقنيات مثل Low-Rank Adaptation (LoRA) على مكونات نموذج محددة. + +نحن نشجعك على المساهمة باختراقاتك الخاصة ومشاركتها هنا مع المجتمع1 + +## مثال: تعديل آلية الانتباه في نموذج Segment Anything (SAM) + +نموذج **Segment Anything (SAM)** هو نموذج رائد في مجال تجزئة الصور. في تنفيذه الافتراضي، يستخدم SAM إسقاطًا مجمعًا للاستعلام والمفتاح والقيمة (`qkv`) في آلية الانتباه الخاصة به. ومع ذلك، قد ترغب في ضبط مكونات محددة فقط من آلية الانتباه، مثل إسقاطات الاستعلام (`q`) والقيمة (`v`)، لتقليل عدد المعلمات القابلة للتدريب والموارد الحسابية المطلوبة. + +### الدافع + +من خلال تقسيم الإسقاط المجمع `qkv` إلى إسقاطات منفصلة `q` و `k` و `v`، يمكنك تطبيق تقنيات مثل **LoRA** (Low-Rank Adaptation) على إسقاطي `q` و `v` فقط. يسمح لك هذا بما يلي: + +- ضبط عدد أقل من المعلمات، مما يقلل من العبء الحسابي. +- تحقيق أداء أفضل من خلال التركيز على مكونات محددة. +- تجربة استراتيجيات تعديل مختلفة في آلية الانتباه. + +### التنفيذ + +#### **الخطوة 1: إنشاء فئة اهتمام مخصصة** + +بعد ذلك، قم بإنشاء فئة فرعية من فئة `SamVisionAttention` الأصلية وعدلها لتضم إسقاطات `q` و `k` و `v` منفصلة. + +```python +import torch +import torch.nn as nn +from transformers.models.sam.modeling_sam import SamVisionAttention + +class SamVisionAttentionSplit(SamVisionAttention, nn.Module): + def __init__(self, config, window_size): + super().__init__(config, window_size) + del self.qkv + # إسقاطات منفصلة q و k و v + self.q = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.k = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.v = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self._register_load_state_dict_pre_hook(self.split_q_k_v_load_hook) + + def split_q_k_v_load_hook(self, state_dict, prefix, *args): + keys_to_delete = [] + for key in list(state_dict.keys()): + if "qkv." in key: + # تقسيم q و k و v من الإسقاط المجمع + q, k, v = state_dict[key].chunk(3, dim=0) + # استبدال الإسقاطات الفردية q و k و v + state_dict[key.replace("qkv.", "q.")] = q + state_dict[key.replace("qkv.", "k.")] = k + state_dict[key.replace("qkv.", "v.")] = v + # وضع علامة على مفتاح qkv القديم للحذف + keys_to_delete.append(key) + + # حذف مفاتيح qkv القديمة + for key in keys_to_delete: + del state_dict[key] + + def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor: + batch_size, height, width, _ = hidden_states.shape + qkv_shapes = (batch_size * self.num_attention_heads, height * width, -1) + query = self.q(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + key = self.k(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + value = self.v(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + + attn_weights = (query * self.scale) @ key.transpose(-2, -1) + + if self.use_rel_pos: + attn_weights = self.add_decomposed_rel_pos( + attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width) + ) + + attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype) + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1) + attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1) + attn_output = self.proj(attn_output) + + if output_attentions: + outputs = (attn_output, attn_weights) + else: + outputs = (attn_output, None) + return outputs +``` + +**الشرح:** + +- **الإسقاطات المنفصلة:** يتم إزالة الإسقاط المُجمع `qkv`، وإنشاء إسقاطات خطية منفصلة `q` و `k` و `v`. +- **دالة استدعاء تحميل الأوزان:** تقوم طريقة `_split_qkv_load_hook` بتقسيم أوزان `qkv` المسبقة التدريب إلى أوزان `q` و `k` و `v` منفصلة عند تحميل النموذج. يضمن هذا التوافق مع أي نموذج مسبق التدريب. +- **التنفيذ الأمامي:** يتم حساب الاستعلامات والمفاتيح والقيم بشكل منفصل، وتستمر آلية الانتباه كالمعتاد. + +#### **الخطوة 2: استبدال فئة الانتباه الأصلية** + +استبدل فئة `SamVisionAttention` الأصلية بفئتك المخصصة بحيث يستخدم النموذج آلية الانتباه المعدلة. + +```python +from transformers import SamModel +from transformers.models.sam import modeling_sam + +# استبدال فئة الاهتمام في وحدة نمطية modeling_sam +modeling_sam.SamVisionAttention = SamVisionAttentionSplit + +# تحميل نموذج SAM المسبق التدريب +model = SamModel.from_pretrained("facebook/sam-vit-base") +``` + +**الشرح:** + +- **استبدال الفئة:** من خلال تعيين فئتك المخصصة إلى `modeling_sam.SamVisionAttention`، فإن أي حالات من فئة `SamVisionAttention` في النموذج ستستخدم النسخة المعدلة. وبالتالي، عند استدعاء `SamModel`، سيتم استخدام `SamVisionAttentionSplit` المحددة حديثًا. +- **تحميل النموذج:** يتم تحميل النموذج باستخدام `from_pretrained`، ويتم دمج آلية الانتباه المخصصة. + +#### **الخطوة 3: تطبيق LoRA على إسقاطات محددة** + +مع وجود إسقاطات `q` و `k` و `v` منفصلة، يمكنك الآن تطبيق LoRA على مكونات محددة، مثل إسقاطات `q` و `v`. + +```python +from peft import LoraConfig, get_peft_model + +config = LoraConfig( + r=16, + lora_alpha=32, + target_modules=["q", "v"], # تطبيق LoRA على إسقاطات q و v + lora_dropout=0.1, + task_type="mask-generation" +) + +# تطبيق LoRA على النموذج +model = get_peft_model(model, config) +``` + +**الشرح:** + +- **تكوين LoRA:** تحدد `LoraConfig` المرتبة `r`، وعامل القياس `lora_alpha`، والوحدات المستهدفة (`"q"` و `"v"`)، ومعدل التخلي، ونوع المهمة. +- **تطبيق LoRA:** تقوم دالة `get_peft_model` بتطبيق LoRA على الوحدات المحددة في النموذج. +- **تقليل المعلمات:** من خلال التركيز على `q` و `v`، فإنك تقلل عدد المعلمات القابلة للتدريب، مما يؤدي إلى تسريع التدريب وتقليل استخدام الذاكرة. + +#### **الخطوة 4: التحقق من عدد المعلمات القابلة للتدريب** + +من السهل التحقق من عدد المعلمات القابلة للتدريب ومعرفة تأثير تعديلك. + +```python +model.print_trainable_parameters() +``` + +**الناتج المتوقع:** + +``` +عدد المعلمات القابلة للتدريب: 608,256 || جميع المعلمات: 94,343,728 || نسبة المعلمات القابلة للتدريب: 0.6447 +عدد المعلمات القابلة للتدريب: 912,384 || جميع المعلمات: 94,647,856 || نسبة المعلمات القابلة للتدريب: 0.9640 # مع k +``` + +## المساهمة بابداعاتك الخاصة + +يمكن لتعديل النماذج المسبقة التدريب أن يفتح آفاقًا جديدة للبحث والتطبيق. من خلال فهم وتعديل الآليات الداخلية للنماذج مثل SAM، يمكنك تخصيصها لتلبية احتياجاتك المحددة، وتحسين الأداء، وتجربة أفكار جديدة. + +إذا قمت بتطوير تعديﻻتك الخاصة لنماذج Transformers وترغب في مشاركتها، ففكر في المساهمة في هذه الوثيقة. + +- **إنشاء طلب سحب (Pull Request):** شارك تغييراتك وتحسيناتك في التعليمات البرمجية مباشرة في المستودع. +- **كتابة التوثيق:** قدم تفسيرات وأمثلة واضحة لتعديلاتك. +- **التفاعل مع المجتمع:** ناقش أفكارك واحصل على تعليقات من المطورين والباحثين الآخرين من خلال فتح مشكلة. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/index.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/index.md new file mode 100644 index 0000000000000000000000000000000000000000..c37dbd1c6d9fc3a313b522d0a88c01606a12bac6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/index.md @@ -0,0 +1,342 @@ +# 🤗 Transformers: لمحة عامة + +أحدث ما في مجال التعلم الآلي لـ [PyTorch](https://pytorch.org/) و [TensorFlow](https://www.tensorflow.org/) و [JAX](https://jax.readthedocs.io/en/latest/) + +توفر 🤗 Transformers واجهات برمجة التطبيقات (APIs) والأدوات اللازمة لتنزيل وتدريب أحدث النماذج المسبقة التدريب بسهولة. ويمكن أن يقلل استخدام النماذج المسبقة التدريب من تكاليف الحوسبة والحد من الأثر البيئي، وتوفّر الوقت والموارد اللازمين لتدريب نموذج من الصفر. وتدعم هذه النماذج المهام الشائعة في مجالات مختلفة، مثل: + + +📝 **معالجة اللغات الطبيعية**: تصنيف النصوص، وتعريف الكيانات المسماة، والإجابة على الأسئلة، ونمذجة اللغة، والتلخيص، والترجمة، والاختيار من متعدد، وتوليد النصوص.
+🖼️ **الرؤية الحاسوبية**: تصنيف الصور، وكشف الأشياء، وتجزئتها.
+🗣️ **الصوت**: التعرف التلقائي على الكلام، وتصنيف الصوت.
+🐙 **متعدد الوسائط**: الإجابة على الأسئلة الجدولية، والتعرف البصري على الحروف، واستخراج المعلومات من المستندات الممسوحة ضوئيًا، وتصنيف الفيديو، والإجابة على الأسئلة البصرية. + +تدعم 🤗 Transformers التوافق بين أطر العمل المختلفة مثل PyTorch و TensorFlow و JAX. ويوفر ذلك المرونة لاستخدام إطار عمل مختلف في كل مرحلة من مراحل حياة النموذج؛ قم بتدريب نموذج في ثلاث خطوط من التعليمات البرمجية في إطار واحد، وقم بتحميله للاستدلال في إطار آخر. ويمكن أيضًا تصدير النماذج إلى صيغ مثل ONNX و TorchScript للنشر في بيئات الإنتاج. + +انضم إلى المجتمع المتنامي على [Hub](https://huggingface.co/models) أو [المنتدى](https://discuss.huggingface.co/) أو [Discord](https://discord.com/invite/JfAtkvEtRb) اليوم! + +## إذا كنت تبحث عن دعم مخصص من فريق Hugging Face + + + HuggingFace Expert Acceleration Program + + +## المحتويات + +ينقسم التوثيق إلى خمسة أقسام: + +- **ابدأ** تقدم جولة سريعة في المكتبة وتعليمات التثبيت للبدء. +- **الدروس التعليمية** هي مكان رائع للبدء إذا كنت مبتدئًا. سيساعدك هذا القسم على اكتساب المهارات الأساسية التي تحتاجها للبدء في استخدام المكتبة. +- **أدلة كيفية الاستخدام** تُظهر لك كيفية تحقيق هدف محدد، مثل ضبط نموذج مسبق التدريب لنمذجة اللغة أو كيفية كتابة ومشاركة نموذج مخصص. +- **الأدلة المفاهيمية** تقدم مناقشة وتفسيرًا أكثر للأفكار والمفاهيم الأساسية وراء النماذج والمهام وفلسفة التصميم في 🤗 Transformers. +- **واجهة برمجة التطبيقات (API)** تصف جميع الفئات والوظائف: + + - **الفئات الرئيسية** تشرح الفئات الأكثر أهمية مثل التكوين والنمذجة والتحليل النصي وخط الأنابيب. + - **النماذج** تشرح الفئات والوظائف المتعلقة بكل نموذج يتم تنفيذه في المكتبة. + - **المساعدون الداخليون** يشرحون فئات ووظائف المساعدة التي يتم استخدامها داخليًا. + + +## النماذج والأطر المدعومة + +يمثل الجدول أدناه الدعم الحالي في المكتبة لكل من هذه النماذج، وما إذا كان لديها محلل نحوي Python (يُسمى "بطيء"). محلل نحوي "سريع" مدعوم بمكتبة 🤗 Tokenizers، وما إذا كان لديها دعم في Jax (عبر Flax) و/أو PyTorch و/أو TensorFlow. + + + + +| Model | PyTorch support | TensorFlow support | Flax Support | +|:------------------------------------------------------------------------:|:---------------:|:------------------:|:------------:| +| [ALBERT](model_doc/albert) | ✅ | ✅ | ✅ | +| [ALIGN](model_doc/align) | ✅ | ❌ | ❌ | +| [AltCLIP](model_doc/altclip) | ✅ | ❌ | ❌ | +| [Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer) | ✅ | ❌ | ❌ | +| [Autoformer](model_doc/autoformer) | ✅ | ❌ | ❌ | +| [Bark](model_doc/bark) | ✅ | ❌ | ❌ | +| [BART](model_doc/bart) | ✅ | ✅ | ✅ | +| [BARThez](model_doc/barthez) | ✅ | ✅ | ✅ | +| [BARTpho](model_doc/bartpho) | ✅ | ✅ | ✅ | +| [BEiT](model_doc/beit) | ✅ | ❌ | ✅ | +| [BERT](model_doc/bert) | ✅ | ✅ | ✅ | +| [Bert Generation](model_doc/bert-generation) | ✅ | ❌ | ❌ | +| [BertJapanese](model_doc/bert-japanese) | ✅ | ✅ | ✅ | +| [BERTweet](model_doc/bertweet) | ✅ | ✅ | ✅ | +| [BigBird](model_doc/big_bird) | ✅ | ❌ | ✅ | +| [BigBird-Pegasus](model_doc/bigbird_pegasus) | ✅ | ❌ | ❌ | +| [BioGpt](model_doc/biogpt) | ✅ | ❌ | ❌ | +| [BiT](model_doc/bit) | ✅ | ❌ | ❌ | +| [Blenderbot](model_doc/blenderbot) | ✅ | ✅ | ✅ | +| [BlenderbotSmall](model_doc/blenderbot-small) | ✅ | ✅ | ✅ | +| [BLIP](model_doc/blip) | ✅ | ✅ | ❌ | +| [BLIP-2](model_doc/blip-2) | ✅ | ❌ | ❌ | +| [BLOOM](model_doc/bloom) | ✅ | ❌ | ✅ | +| [BORT](model_doc/bort) | ✅ | ✅ | ✅ | +| [BridgeTower](model_doc/bridgetower) | ✅ | ❌ | ❌ | +| [BROS](model_doc/bros) | ✅ | ❌ | ❌ | +| [ByT5](model_doc/byt5) | ✅ | ✅ | ✅ | +| [CamemBERT](model_doc/camembert) | ✅ | ✅ | ❌ | +| [CANINE](model_doc/canine) | ✅ | ❌ | ❌ | +| [Chameleon](model_doc/chameleon) | ✅ | ❌ | ❌ | +| [Chinese-CLIP](model_doc/chinese_clip) | ✅ | ❌ | ❌ | +| [CLAP](model_doc/clap) | ✅ | ❌ | ❌ | +| [CLIP](model_doc/clip) | ✅ | ✅ | ✅ | +| [CLIPSeg](model_doc/clipseg) | ✅ | ❌ | ❌ | +| [CLVP](model_doc/clvp) | ✅ | ❌ | ❌ | +| [CodeGen](model_doc/codegen) | ✅ | ❌ | ❌ | +| [CodeLlama](model_doc/code_llama) | ✅ | ❌ | ✅ | +| [Cohere](model_doc/cohere) | ✅ | ❌ | ❌ | +| [Conditional DETR](model_doc/conditional_detr) | ✅ | ❌ | ❌ | +| [ConvBERT](model_doc/convbert) | ✅ | ✅ | ❌ | +| [ConvNeXT](model_doc/convnext) | ✅ | ✅ | ❌ | +| [ConvNeXTV2](model_doc/convnextv2) | ✅ | ✅ | ❌ | +| [CPM](model_doc/cpm) | ✅ | ✅ | ✅ | +| [CPM-Ant](model_doc/cpmant) | ✅ | ❌ | ❌ | +| [CTRL](model_doc/ctrl) | ✅ | ✅ | ❌ | +| [CvT](model_doc/cvt) | ✅ | ✅ | ❌ | +| [DAC](model_doc/dac) | ✅ | ❌ | ❌ | +| [Data2VecAudio](model_doc/data2vec) | ✅ | ❌ | ❌ | +| [Data2VecText](model_doc/data2vec) | ✅ | ❌ | ❌ | +| [Data2VecVision](model_doc/data2vec) | ✅ | ✅ | ❌ | +| [DBRX](model_doc/dbrx) | ✅ | ❌ | ❌ | +| [DeBERTa](model_doc/deberta) | ✅ | ✅ | ❌ | +| [DeBERTa-v2](model_doc/deberta-v2) | ✅ | ✅ | ❌ | +| [Decision Transformer](model_doc/decision_transformer) | ✅ | ❌ | ❌ | +| [Deformable DETR](model_doc/deformable_detr) | ✅ | ❌ | ❌ | +| [DeiT](model_doc/deit) | ✅ | ✅ | ❌ | +| [DePlot](model_doc/deplot) | ✅ | ❌ | ❌ | +| [Depth Anything](model_doc/depth_anything) | ✅ | ❌ | ❌ | +| [DETA](model_doc/deta) | ✅ | ❌ | ❌ | +| [DETR](model_doc/detr) | ✅ | ❌ | ❌ | +| [DialoGPT](model_doc/dialogpt) | ✅ | ✅ | ✅ | +| [DiNAT](model_doc/dinat) | ✅ | ❌ | ❌ | +| [DINOv2](model_doc/dinov2) | ✅ | ❌ | ✅ | +| [DistilBERT](model_doc/distilbert) | ✅ | ✅ | ✅ | +| [DiT](model_doc/dit) | ✅ | ❌ | ✅ | +| [DonutSwin](model_doc/donut) | ✅ | ❌ | ❌ | +| [DPR](model_doc/dpr) | ✅ | ✅ | ❌ | +| [DPT](model_doc/dpt) | ✅ | ❌ | ❌ | +| [EfficientFormer](model_doc/efficientformer) | ✅ | ✅ | ❌ | +| [EfficientNet](model_doc/efficientnet) | ✅ | ❌ | ❌ | +| [ELECTRA](model_doc/electra) | ✅ | ✅ | ✅ | +| [EnCodec](model_doc/encodec) | ✅ | ❌ | ❌ | +| [Encoder decoder](model_doc/encoder-decoder) | ✅ | ✅ | ✅ | +| [ERNIE](model_doc/ernie) | ✅ | ❌ | ❌ | +| [ErnieM](model_doc/ernie_m) | ✅ | ❌ | ❌ | +| [ESM](model_doc/esm) | ✅ | ✅ | ❌ | +| [FairSeq Machine-Translation](model_doc/fsmt) | ✅ | ❌ | ❌ | +| [Falcon](model_doc/falcon) | ✅ | ❌ | ❌ | +| [FalconMamba](model_doc/falcon_mamba) | ✅ | ❌ | ❌ | +| [FastSpeech2Conformer](model_doc/fastspeech2_conformer) | ✅ | ❌ | ❌ | +| [FLAN-T5](model_doc/flan-t5) | ✅ | ✅ | ✅ | +| [FLAN-UL2](model_doc/flan-ul2) | ✅ | ✅ | ✅ | +| [FlauBERT](model_doc/flaubert) | ✅ | ✅ | ❌ | +| [FLAVA](model_doc/flava) | ✅ | ❌ | ❌ | +| [FNet](model_doc/fnet) | ✅ | ❌ | ❌ | +| [FocalNet](model_doc/focalnet) | ✅ | ❌ | ❌ | +| [Funnel Transformer](model_doc/funnel) | ✅ | ✅ | ❌ | +| [Fuyu](model_doc/fuyu) | ✅ | ❌ | ❌ | +| [Gemma](model_doc/gemma) | ✅ | ❌ | ✅ | +| [Gemma2](model_doc/gemma2) | ✅ | ❌ | ❌ | +| [GIT](model_doc/git) | ✅ | ❌ | ❌ | +| [GLPN](model_doc/glpn) | ✅ | ❌ | ❌ | +| [GPT Neo](model_doc/gpt_neo) | ✅ | ❌ | ✅ | +| [GPT NeoX](model_doc/gpt_neox) | ✅ | ❌ | ❌ | +| [GPT NeoX Japanese](model_doc/gpt_neox_japanese) | ✅ | ❌ | ❌ | +| [GPT-J](model_doc/gptj) | ✅ | ✅ | ✅ | +| [GPT-Sw3](model_doc/gpt-sw3) | ✅ | ✅ | ✅ | +| [GPTBigCode](model_doc/gpt_bigcode) | ✅ | ❌ | ❌ | +| [GPTSAN-japanese](model_doc/gptsan-japanese) | ✅ | ❌ | ❌ | +| [Granite](model_doc/granite) | ✅ | ❌ | ❌ | +| [Graphormer](model_doc/graphormer) | ✅ | ❌ | ❌ | +| [Grounding DINO](model_doc/grounding-dino) | ✅ | ❌ | ❌ | +| [GroupViT](model_doc/groupvit) | ✅ | ✅ | ❌ | +| [HerBERT](model_doc/herbert) | ✅ | ✅ | ✅ | +| [Hiera](model_doc/hiera) | ✅ | ❌ | ❌ | +| [Hubert](model_doc/hubert) | ✅ | ✅ | ❌ | +| [I-BERT](model_doc/ibert) | ✅ | ❌ | ❌ | +| [IDEFICS](model_doc/idefics) | ✅ | ✅ | ❌ | +| [Idefics2](model_doc/idefics2) | ✅ | ❌ | ❌ | +| [ImageGPT](model_doc/imagegpt) | ✅ | ❌ | ❌ | +| [Informer](model_doc/informer) | ✅ | ❌ | ❌ | +| [InstructBLIP](model_doc/instructblip) | ✅ | ❌ | ❌ | +| [InstructBlipVideo](model_doc/instructblipvideo) | ✅ | ❌ | ❌ | +| [Jamba](model_doc/jamba) | ✅ | ❌ | ❌ | +| [JetMoe](model_doc/jetmoe) | ✅ | ❌ | ❌ | +| [Jukebox](model_doc/jukebox) | ✅ | ❌ | ❌ | +| [KOSMOS-2](model_doc/kosmos-2) | ✅ | ❌ | ❌ | +| [LayoutLM](model_doc/layoutlm) | ✅ | ✅ | ❌ | +| [LayoutLMv2](model_doc/layoutlmv2) | ✅ | ❌ | ❌ | +| [LayoutLMv3](model_doc/layoutlmv3) | ✅ | ✅ | ❌ | +| [LayoutXLM](model_doc/layoutxlm) | ✅ | ❌ | ❌ | +| [LED](model_doc/led) | ✅ | ✅ | ❌ | +| [LeViT](model_doc/levit) | ✅ | ❌ | ❌ | +| [LiLT](model_doc/lilt) | ✅ | ❌ | ❌ | +| [LLaMA](model_doc/llama) | ✅ | ❌ | ✅ | +| [Llama2](model_doc/llama2) | ✅ | ❌ | ✅ | +| [Llama3](model_doc/llama3) | ✅ | ❌ | ✅ | +| [LLaVa](model_doc/llava) | ✅ | ❌ | ❌ | +| [LLaVA-NeXT](model_doc/llava_next) | ✅ | ❌ | ❌ | +| [LLaVa-NeXT-Video](model_doc/llava_next_video) | ✅ | ❌ | ❌ | +| [Longformer](model_doc/longformer) | ✅ | ✅ | ❌ | +| [LongT5](model_doc/longt5) | ✅ | ❌ | ✅ | +| [LUKE](model_doc/luke) | ✅ | ❌ | ❌ | +| [LXMERT](model_doc/lxmert) | ✅ | ✅ | ❌ | +| [M-CTC-T](model_doc/mctct) | ✅ | ❌ | ❌ | +| [M2M100](model_doc/m2m_100) | ✅ | ❌ | ❌ | +| [MADLAD-400](model_doc/madlad-400) | ✅ | ✅ | ✅ | +| [Mamba](model_doc/mamba) | ✅ | ❌ | ❌ | +| [mamba2](model_doc/mamba2) | ✅ | ❌ | ❌ | +| [Marian](model_doc/marian) | ✅ | ✅ | ✅ | +| [MarkupLM](model_doc/markuplm) | ✅ | ❌ | ❌ | +| [Mask2Former](model_doc/mask2former) | ✅ | ❌ | ❌ | +| [MaskFormer](model_doc/maskformer) | ✅ | ❌ | ❌ | +| [MatCha](model_doc/matcha) | ✅ | ❌ | ❌ | +| [mBART](model_doc/mbart) | ✅ | ✅ | ✅ | +| [mBART-50](model_doc/mbart50) | ✅ | ✅ | ✅ | +| [MEGA](model_doc/mega) | ✅ | ❌ | ❌ | +| [Megatron-BERT](model_doc/megatron-bert) | ✅ | ❌ | ❌ | +| [Megatron-GPT2](model_doc/megatron_gpt2) | ✅ | ✅ | ✅ | +| [MGP-STR](model_doc/mgp-str) | ✅ | ❌ | ❌ | +| [Mistral](model_doc/mistral) | ✅ | ✅ | ✅ | +| [Mixtral](model_doc/mixtral) | ✅ | ❌ | ❌ | +| [mLUKE](model_doc/mluke) | ✅ | ❌ | ❌ | +| [MMS](model_doc/mms) | ✅ | ✅ | ✅ | +| [MobileBERT](model_doc/mobilebert) | ✅ | ✅ | ❌ | +| [MobileNetV1](model_doc/mobilenet_v1) | ✅ | ❌ | ❌ | +| [MobileNetV2](model_doc/mobilenet_v2) | ✅ | ❌ | ❌ | +| [MobileViT](model_doc/mobilevit) | ✅ | ✅ | ❌ | +| [MobileViTV2](model_doc/mobilevitv2) | ✅ | ❌ | ❌ | +| [MPNet](model_doc/mpnet) | ✅ | ✅ | ❌ | +| [MPT](model_doc/mpt) | ✅ | ❌ | ❌ | +| [MRA](model_doc/mra) | ✅ | ❌ | ❌ | +| [MT5](model_doc/mt5) | ✅ | ✅ | ✅ | +| [MusicGen](model_doc/musicgen) | ✅ | ❌ | ❌ | +| [MusicGen Melody](model_doc/musicgen_melody) | ✅ | ❌ | ❌ | +| [MVP](model_doc/mvp) | ✅ | ❌ | ❌ | +| [NAT](model_doc/nat) | ✅ | ❌ | ❌ | +| [Nemotron](model_doc/nemotron) | ✅ | ❌ | ❌ | +| [Nezha](model_doc/nezha) | ✅ | ❌ | ❌ | +| [NLLB](model_doc/nllb) | ✅ | ❌ | ❌ | +| [NLLB-MOE](model_doc/nllb-moe) | ✅ | ❌ | ❌ | +| [Nougat](model_doc/nougat) | ✅ | ✅ | ✅ | +| [Nyströmformer](model_doc/nystromformer) | ✅ | ❌ | ❌ | +| [OLMo](model_doc/olmo) | ✅ | ❌ | ❌ | +| [OneFormer](model_doc/oneformer) | ✅ | ❌ | ❌ | +| [OpenAI GPT](model_doc/openai-gpt) | ✅ | ✅ | ❌ | +| [OpenAI GPT-2](model_doc/gpt2) | ✅ | ✅ | ✅ | +| [OpenLlama](model_doc/open-llama) | ✅ | ❌ | ❌ | +| [OPT](model_doc/opt) | ✅ | ✅ | ✅ | +| [OWL-ViT](model_doc/owlvit) | ✅ | ❌ | ❌ | +| [OWLv2](model_doc/owlv2) | ✅ | ❌ | ❌ | +| [PaliGemma](model_doc/paligemma) | ✅ | ❌ | ❌ | +| [PatchTSMixer](model_doc/patchtsmixer) | ✅ | ❌ | ❌ | +| [PatchTST](model_doc/patchtst) | ✅ | ❌ | ❌ | +| [Pegasus](model_doc/pegasus) | ✅ | ✅ | ✅ | +| [PEGASUS-X](model_doc/pegasus_x) | ✅ | ❌ | ❌ | +| [Perceiver](model_doc/perceiver) | ✅ | ❌ | ❌ | +| [Persimmon](model_doc/persimmon) | ✅ | ❌ | ❌ | +| [Phi](model_doc/phi) | ✅ | ❌ | ❌ | +| [Phi3](model_doc/phi3) | ✅ | ❌ | ❌ | +| [PhoBERT](model_doc/phobert) | ✅ | ✅ | ✅ | +| [Pix2Struct](model_doc/pix2struct) | ✅ | ❌ | ❌ | +| [PLBart](model_doc/plbart) | ✅ | ❌ | ❌ | +| [PoolFormer](model_doc/poolformer) | ✅ | ❌ | ❌ | +| [Pop2Piano](model_doc/pop2piano) | ✅ | ❌ | ❌ | +| [ProphetNet](model_doc/prophetnet) | ✅ | ❌ | ❌ | +| [PVT](model_doc/pvt) | ✅ | ❌ | ❌ | +| [PVTv2](model_doc/pvt_v2) | ✅ | ❌ | ❌ | +| [QDQBert](model_doc/qdqbert) | ✅ | ❌ | ❌ | +| [Qwen2](model_doc/qwen2) | ✅ | ❌ | ❌ | +| [Qwen2Audio](model_doc/qwen2_audio) | ✅ | ❌ | ❌ | +| [Qwen2MoE](model_doc/qwen2_moe) | ✅ | ❌ | ❌ | +| [Qwen2VL](model_doc/qwen2_vl) | ✅ | ❌ | ❌ | +| [RAG](model_doc/rag) | ✅ | ✅ | ❌ | +| [REALM](model_doc/realm) | ✅ | ❌ | ❌ | +| [RecurrentGemma](model_doc/recurrent_gemma) | ✅ | ❌ | ❌ | +| [Reformer](model_doc/reformer) | ✅ | ❌ | ❌ | +| [RegNet](model_doc/regnet) | ✅ | ✅ | ✅ | +| [RemBERT](model_doc/rembert) | ✅ | ✅ | ❌ | +| [ResNet](model_doc/resnet) | ✅ | ✅ | ✅ | +| [RetriBERT](model_doc/retribert) | ✅ | ❌ | ❌ | +| [RoBERTa](model_doc/roberta) | ✅ | ✅ | ✅ | +| [RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm) | ✅ | ✅ | ✅ | +| [RoCBert](model_doc/roc_bert) | ✅ | ❌ | ❌ | +| [RoFormer](model_doc/roformer) | ✅ | ✅ | ✅ | +| [RT-DETR](model_doc/rt_detr) | ✅ | ❌ | ❌ | +| [RT-DETR-ResNet](model_doc/rt_detr_resnet) | ✅ | ❌ | ❌ | +| [RWKV](model_doc/rwkv) | ✅ | ❌ | ❌ | +| [SAM](model_doc/sam) | ✅ | ✅ | ❌ | +| [SeamlessM4T](model_doc/seamless_m4t) | ✅ | ❌ | ❌ | +| [SeamlessM4Tv2](model_doc/seamless_m4t_v2) | ✅ | ❌ | ❌ | +| [SegFormer](model_doc/segformer) | ✅ | ✅ | ❌ | +| [SegGPT](model_doc/seggpt) | ✅ | ❌ | ❌ | +| [SEW](model_doc/sew) | ✅ | ❌ | ❌ | +| [SEW-D](model_doc/sew-d) | ✅ | ❌ | ❌ | +| [SigLIP](model_doc/siglip) | ✅ | ❌ | ❌ | +| [Speech Encoder decoder](model_doc/speech-encoder-decoder) | ✅ | ❌ | ✅ | +| [Speech2Text](model_doc/speech_to_text) | ✅ | ✅ | ❌ | +| [SpeechT5](model_doc/speecht5) | ✅ | ❌ | ❌ | +| [Splinter](model_doc/splinter) | ✅ | ❌ | ❌ | +| [SqueezeBERT](model_doc/squeezebert) | ✅ | ❌ | ❌ | +| [StableLm](model_doc/stablelm) | ✅ | ❌ | ❌ | +| [Starcoder2](model_doc/starcoder2) | ✅ | ❌ | ❌ | +| [SuperPoint](model_doc/superpoint) | ✅ | ❌ | ❌ | +| [SwiftFormer](model_doc/swiftformer) | ✅ | ✅ | ❌ | +| [Swin Transformer](model_doc/swin) | ✅ | ✅ | ❌ | +| [Swin Transformer V2](model_doc/swinv2) | ✅ | ❌ | ❌ | +| [Swin2SR](model_doc/swin2sr) | ✅ | ❌ | ❌ | +| [SwitchTransformers](model_doc/switch_transformers) | ✅ | ❌ | ❌ | +| [T5](model_doc/t5) | ✅ | ✅ | ✅ | +| [T5v1.1](model_doc/t5v1.1) | ✅ | ✅ | ✅ | +| [Table Transformer](model_doc/table-transformer) | ✅ | ❌ | ❌ | +| [TAPAS](model_doc/tapas) | ✅ | ✅ | ❌ | +| [TAPEX](model_doc/tapex) | ✅ | ✅ | ✅ | +| [Time Series Transformer](model_doc/time_series_transformer) | ✅ | ❌ | ❌ | +| [TimeSformer](model_doc/timesformer) | ✅ | ❌ | ❌ | +| [Trajectory Transformer](model_doc/trajectory_transformer) | ✅ | ❌ | ❌ | +| [Transformer-XL](model_doc/transfo-xl) | ✅ | ✅ | ❌ | +| [TrOCR](model_doc/trocr) | ✅ | ❌ | ❌ | +| [TVLT](model_doc/tvlt) | ✅ | ❌ | ❌ | +| [TVP](model_doc/tvp) | ✅ | ❌ | ❌ | +| [UDOP](model_doc/udop) | ✅ | ❌ | ❌ | +| [UL2](model_doc/ul2) | ✅ | ✅ | ✅ | +| [UMT5](model_doc/umt5) | ✅ | ❌ | ❌ | +| [UniSpeech](model_doc/unispeech) | ✅ | ❌ | ❌ | +| [UniSpeechSat](model_doc/unispeech-sat) | ✅ | ❌ | ❌ | +| [UnivNet](model_doc/univnet) | ✅ | ❌ | ❌ | +| [UPerNet](model_doc/upernet) | ✅ | ❌ | ❌ | +| [VAN](model_doc/van) | ✅ | ❌ | ❌ | +| [VideoLlava](model_doc/video_llava) | ✅ | ❌ | ❌ | +| [VideoMAE](model_doc/videomae) | ✅ | ❌ | ❌ | +| [ViLT](model_doc/vilt) | ✅ | ❌ | ❌ | +| [VipLlava](model_doc/vipllava) | ✅ | ❌ | ❌ | +| [Vision Encoder decoder](model_doc/vision-encoder-decoder) | ✅ | ✅ | ✅ | +| [VisionTextDualEncoder](model_doc/vision-text-dual-encoder) | ✅ | ✅ | ✅ | +| [VisualBERT](model_doc/visual_bert) | ✅ | ❌ | ❌ | +| [ViT](model_doc/vit) | ✅ | ✅ | ✅ | +| [ViT Hybrid](model_doc/vit_hybrid) | ✅ | ❌ | ❌ | +| [VitDet](model_doc/vitdet) | ✅ | ❌ | ❌ | +| [ViTMAE](model_doc/vit_mae) | ✅ | ✅ | ❌ | +| [ViTMatte](model_doc/vitmatte) | ✅ | ❌ | ❌ | +| [ViTMSN](model_doc/vit_msn) | ✅ | ❌ | ❌ | +| [VITS](model_doc/vits) | ✅ | ❌ | ❌ | +| [ViViT](model_doc/vivit) | ✅ | ❌ | ❌ | +| [Wav2Vec2](model_doc/wav2vec2) | ✅ | ✅ | ✅ | +| [Wav2Vec2-BERT](model_doc/wav2vec2-bert) | ✅ | ❌ | ❌ | +| [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer) | ✅ | ❌ | ❌ | +| [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme) | ✅ | ✅ | ✅ | +| [WavLM](model_doc/wavlm) | ✅ | ❌ | ❌ | +| [Whisper](model_doc/whisper) | ✅ | ✅ | ✅ | +| [X-CLIP](model_doc/xclip) | ✅ | ❌ | ❌ | +| [X-MOD](model_doc/xmod) | ✅ | ❌ | ❌ | +| [XGLM](model_doc/xglm) | ✅ | ✅ | ✅ | +| [XLM](model_doc/xlm) | ✅ | ✅ | ❌ | +| [XLM-ProphetNet](model_doc/xlm-prophetnet) | ✅ | ❌ | ❌ | +| [XLM-RoBERTa](model_doc/xlm-roberta) | ✅ | ✅ | ✅ | +| [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl) | ✅ | ❌ | ❌ | +| [XLM-V](model_doc/xlm-v) | ✅ | ✅ | ✅ | +| [XLNet](model_doc/xlnet) | ✅ | ✅ | ❌ | +| [XLS-R](model_doc/xls_r) | ✅ | ✅ | ✅ | +| [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2) | ✅ | ✅ | ✅ | +| [YOLOS](model_doc/yolos) | ✅ | ❌ | ❌ | +| [YOSO](model_doc/yoso) | ✅ | ❌ | ❌ | +| [ZoeDepth](model_doc/zoedepth) | ✅ | ❌ | ❌ | + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/installation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..d3bd4c655b6038238ec7bacf3a2723685a7c3a21 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/installation.md @@ -0,0 +1,246 @@ +# التثبيت (Installation) + +قم بتثبيت مكتبة 🤗 Transformers المناسبة لمكتبة التعلم العميق التي تستخدمها، وقم بإعداد ذاكرة التخزين المؤقت الخاصة بك، وقم بإعداد 🤗 Transformers للعمل دون اتصال بالإنترنت (اختياري). + +تم اختبار 🤗 Transformers على Python 3.6 والإصدارات الأحدث، وPyTorch 1.1.0 والإصدارات الأحدث، وTensorFlow 2.0 والإصدارات الأحدث، وFlax. اتبع تعليمات التثبيت أدناه لمكتبة التعلم العميق التي تستخدمها: + +* تعليمات تثبيت [PyTorch](https://pytorch.org/get-started/locally/). +* تعليمات تثبيت [TensorFlow 2.0](https://www.tensorflow.org/install/pip). +* تعليمات تثبيت [Flax](https://flax.readthedocs.io/en/latest/). + +## التثبيت باستخدام pip + +يجب عليك تثبيت 🤗 Transformers داخل [بيئة افتراضية](https://docs.python.org/3/library/venv.html). إذا لم تكن غير ملم ببيئات Python الافتراضية، فراجع هذا [الدليل](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). البيئة الافتراضية تسهل إدارة المشاريع المختلف، وتجنب مشكلات التوافق بين المكتبات المطلوبة (اعتماديات المشروع). + +ابدأ بإنشاء بيئة افتراضية في دليل مشروعك: + +```bash +python -m venv .env +``` + +قم بتفعيل البيئة الافتراضية. على Linux وMacOs: + +```bash +source .env/bin/activate +``` + +قم بتفعيل البيئة الافتراضية على Windows: + +```bash +.env/Scripts/activate +``` + +الآن أنت مستعد لتثبيت 🤗 Transformers باستخدام الأمر التالي: + +```bash +pip install transformers +``` + +للحصول على الدعم الخاص بـ CPU فقط، يمكنك تثبيت 🤗 Transformers ومكتبة التعلم العميق في خطوة واحدة. على سبيل المثال، قم بتثبيت 🤗 Transformers وPyTorch باستخدام: + +```bash +pip install 'transformers[torch]' +``` + +🤗 Transformers وTensorFlow 2.0: + +```bash +pip install 'transformers[tf-cpu]' +``` + + + +لمستخدمي M1 / ARM + +ستحتاج إلى تثبيت ما يلي قبل تثبيت TensorFLow 2.0 +```bash +brew install cmake +brew install pkg-config +``` + + + +🤗 Transformers وFlax: + +```bash +pip install 'transformers[flax]' +``` + +أخيرًا، تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي. سيقوم بتنزيل نموذج مدرب مسبقًا: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" +``` + +ثم قم بطباعة التسمية والنتيجة: + +```bash +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +## التثبيت من المصدر + +قم بتثبيت 🤗 Transformers من المصدر باستخدام الأمر التالي: + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +يقوم هذا الأمر بتثبيت أحدث إصدار تجريبي `main` بدلاً من الإصدار المستقر `stable`. يعد إصدار `main` مفيدًا للمواكبة مع أحدث التطورات. على سبيل المثال، إذا تم إصلاح خطأ منذ الإصدار الرسمي الأخير ولكن لم يتم طرح إصدار جديد بعد. ومع ذلك، فإن هذا يعني أن إصدار التجريبي `main` قد لا يكون مستقرًا دائمًا. نسعى جاهدين للحفاظ على تشغيل إصدار `main`، ويتم حل معظم المشكلات عادةً في غضون بضع ساعات أو يوم. إذا واجهتك مشكلة، يرجى فتح [تقرير عن خلل](https://github.com/huggingface/transformers/issues) حتى نتمكن من إصلاحها في أقرب وقت ممكن! + +تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +تحقق مما إذا كان 🤗 Transformers قد تم تثبيته بشكل صحيح عن طريق تشغيل الأمر التالي: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +## التثبيت القابل للتعديل + +ستحتاج إلى تثبيت قابل للتعديل إذا كنت ترغب في: + +* استخدام إصدار `main` من كود المصدر. +* المساهمة في 🤗 Transformers وتحتاج إلى اختبار التغييرات في الكود. + +قم باستنساخ المستودع وقم بتثبيت 🤗 Transformers باستخدام الأوامر التالية: + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + + ستقوم هذه الأوامر بربط المجلد الذي قمت باستنساخ المستودع فيه بمسارات مكتبة Python. بمعنى آخر، سيبحث Python داخل المجلد الذي قمت باستنساخه بالإضافة إلى المسارات المعتادة للمكتبات. على سبيل المثال، إذا تم تثبيت حزم Python الخاصة بك عادةً في `~/anaconda3/envs/main/lib/python3.7/site-packages/`, فسيقوم Python أيضًا بالبحث في المجلد الذي قمت باستنساخه: `~/transformers/`. + + + +يجب عليك الاحتفاظ بمجلد `transformers` إذا كنت تريد الاستمرار في استخدام المكتبة. + + + +الآن يمكنك تحديث المستنسخ الخاص بك بسهولة إلى أحدث إصدار من 🤗 Transformers باستخدام الأمر التالي: + +```bash +cd ~/transformers/ +git pull +``` + +ستجد بيئة Python الإصدار `main` من 🤗 Transformers في المرة التالية التي تقوم فيها بتشغيله. + +## التثبيت باستخدام conda + +قم بالتثبيت من قناة conda `conda-forge`: + +```bash +conda install conda-forge::transformers +``` + +## إعداد ذاكرة التخزين المؤقت + +تُحمّل النماذج المُسبقة التدريب وتُخزّن مؤقتًا في: `~/.cache/huggingface/hub`. هذا هو المجلد الافتراضي الذي يُحدده متغير البيئة `TRANSFORMERS_CACHE`. على Windows، يكون دليل ذاكرة التخزين المؤقت الافتراضي هو `C:\Users\username\.cache\huggingface\hub`. يمكنك تغيير متغيرات البيئة shell الموضحة أدناه - حسب الأولوية - لتحديد دليل ذاكرة تخزين مؤقت مختلف: + +1. متغير البيئة (افتراضي): `HF_HUB_CACHE` أو `TRANSFORMERS_CACHE`. +2. متغير البيئة: `HF_HOME`. +3. متغير البيئة: `XDG_CACHE_HOME` + `/huggingface`. + + + +سيستخدم 🤗 Transformers متغيرات البيئة `PYTORCH_TRANSFORMERS_CACHE` أو `PYTORCH_PRETRAINED_BERT_CACHE` إذا كنت قادمًا من إصدار سابق من هذه المكتبة وقمت بتعيين متغيرات البيئة هذه، ما لم تحدد متغير البيئة `TRANSFORMERS_CACHE`. + + + +## الوضع دون اتصال بالإنترنت + +قم بتشغيل 🤗 Transformers في بيئة محمية بجدار حماية أو غير متصلة باستخدام الملفات المخزنة مؤقتًا محليًا عن طريق تعيين متغير البيئة `HF_HUB_OFFLINE=1`. + + + +أضف [🤗 Datasets](https://huggingface.co/docs/datasets/) إلى سير عمل التدريب غير المتصل باستخدام متغير البيئة `HF_DATASETS_OFFLINE=1`. + + + +```bash +HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +يجب أن يعمل هذا البرنامج النصي دون توقف أو انتظار انتهاء المهلة الزمنية لأنه لن يحاول تنزيل النموذج من Hub. + +يمكنك أيضًا تجاوز تحميل نموذج من Hub من كل استدعاء [`~PreTrainedModel.from_pretrained`] باستخدام معلمة [`local_files_only`]. عندما يتم تعيينها على `True`، يتم تحميل الملفات المحلية فقط: + +```py +from transformers import T5Model + +model = T5Model.from_pretrained("./path/to/local/directory", local_files_only=True) +``` + +### جلب النماذج والمُجزّئات لاستخدامها دون اتصال بالإنترنت + +خيار آخر لاستخدام 🤗 Transformers دون اتصال هو تنزيل الملفات مسبقًا، ثم الإشارة إلى مسارها المحلي عند الحاجة إلى استخدامها دون اتصال. هناك ثلاث طرق للقيام بذلك: + +* قم بتنزيل ملف عبر واجهة المستخدم على [Model Hub](https://huggingface.co/models) بالنقر فوق أيقونة ↓. + + ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png) + +* استخدم سير عمل [`PreTrainedModel.from_pretrained`] و [`PreTrainedModel.save_pretrained`]: + + 1. قم بتنزيل ملفاتك مسبقًا باستخدام [`PreTrainedModel.from_pretrained`]: +* استخدم سير عمل [`PreTrainedModel.from_pretrained`] و [`PreTrainedModel.save_pretrained`]: + + 1. قم بتنزيل ملفاتك مسبقًا باستخدام [`PreTrainedModel.from_pretrained`]: + + ```py + >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + + >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") + >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") + ``` + + 2. احفظ ملفاتك إلى دليل محدد باستخدام [`PreTrainedModel.save_pretrained`]: + + ```py + >>> tokenizer.save_pretrained("./your/path/bigscience_t0") + >>> model.save_pretrained("./your/path/bigscience_t0") + ``` + + 3. الآن عندما تكون غير متصل بالإنترنت، أعد تحميل ملفاتك باستخدام [`PreTrainedModel.from_pretrained`] من الدليل المحدد: + + ```py + >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") + >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0") + ``` + +* قم بتنزيل الملفات برمجيًا باستخدام مكتبة [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub): + + 1. قم بتثبيت مكتبة `huggingface_hub` في بيئتك الافتراضية: + + ```bash + python -m pip install huggingface_hub + ``` + + 2. استخدم وظيفة [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) لتنزيل ملف إلى مسار محدد. على سبيل المثال، يقوم الأمر التالي بتنزيل ملف `config.json` من نموذج [T0](https://huggingface.co/bigscience/T0_3B) إلى المسار المطلوب: + + ```py + >>> from huggingface_hub import hf_hub_download + + >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") + ``` + +بمجرد تنزيل ملفك وتخزينه مؤقتًا محليًا، حدد مساره المحلي الخاص به لتحميله واستخدامه: + +```py +>>> from transformers import AutoConfig + +>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") +``` + + + +راجع قسم [كيفية تنزيل الملفات من Hub](https://huggingface.co/docs/hub/how-to-downstream) لمزيد من التفاصيل حول تنزيل الملفات المخزنة على Hub. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..264797a982b9ade0c70c29d7acf3c10ff498dc0b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial.md @@ -0,0 +1,248 @@ +# التوليد باستخدام نماذج اللغات الكبيرة (LLMs) + +[[open-in-colab]] + +تعد LLMs، أو نماذج اللغة الكبيرة، المكون الرئيسي وراء توليد النصوص. وباختصار، تتكون من نماذج محول كبيرة مسبقة التدريب تم تدريبها للتنبؤ بالكلمة التالية (أو، بشكل أكثر دقة، الرمز اللغوي) بالنظر إلى نص معين. نظرًا لأنها تتنبأ برمز واحد في كل مرة، يجب عليك القيام بشيء أكثر تعقيدًا لتوليد جمل جديدة بخلاف مجرد استدعاء النموذج - يجب عليك إجراء التوليد التلقائي. + +التوليد التلقائي هو إجراء وقت الاستدلال الذي يتضمن استدعاء النموذج بشكل متكرر باستخدام مخرجاته الخاصة، بالنظر إلى بعض المدخلات الأولية. في 🤗 Transformers، يتم التعامل مع هذا بواسطة دالة [`~generation.GenerationMixin.generate`]، والتي تتوفر لجميع النماذج ذات القدرات التوليدية. + +سيوضح هذا البرنامج التعليمي كيفية: + +* تتوليد نص باستخدام نموذج اللغات الكبيرة (LLM) +* تجنب الوقوع في الأخطاء الشائعة +* الخطوات التالية لمساعدتك في الاستفادة القصوى من LLM الخاص بك + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers bitsandbytes>=0.39.0 -q +``` + +## توليد النص + +يأخذ نموذج اللغة المدرب لـ [نمذجة اللغة السببية](tasks/language_modeling) يأخذ تسلسلًا من رموز نصية كمدخل ويعيد توزيع الاحتمالية للرمز التالي. + + +
+ +
"التنبؤ بالكلمة التالية لنموذج اللغة (LLM)"
+
+ +هناك جانب بالغ الأهمية في التوليد التلقائي باستخدام LLMs وهو كيفية اختيار الرمز التالي من توزيع الاحتمالية هذا. كل شيء مسموح به في هذه الخطوة طالما أنك تنتهي برمز للتكرار التالي. وهذا يعني أنه يمكن أن يكون بسيطًا مثل اختيار الرمز الأكثر احتمالًا من توزيع الاحتمالية أو معقدًا مثل تطبيق عشرات التحولات قبل أخذ العينات من التوزيع الناتج. + + +
+ +
"التوليد التلقائي المتسلسل"
+
+ +تتكرر العملية الموضحة أعلاه بشكل تكراري حتى يتم الوصول إلى شرط التوقف. في الوضع المثالي، يحدد النموذج شرط التوقف، والذي يجب أن يتعلم عند إخراج رمز نهاية التسلسل (`EOS`). إذا لم يكن الأمر كذلك، يتوقف التوليد عند الوصول إلى طول أقصى محدد مسبقًا. + +من الضروري إعداد خطوة اختيار الرمز وشرط التوقف بشكل صحيح لجعل نموذجك يتصرف كما تتوقع في مهمتك. ولهذا السبب لدينا [`~generation.GenerationConfig`] ملف مرتبط بكل نموذج، والذي يحتوي على معلمة توليدية افتراضية جيدة ويتم تحميله جنبًا إلى جنب مع نموذجك. + +دعنا نتحدث عن الكود! + + + + +إذا كنت مهتمًا بالاستخدام الأساسي لـ LLM، فإن واجهة [`Pipeline`](pipeline_tutorial) عالية المستوى هي نقطة انطلاق رائعة. ومع ذلك، غالبًا ما تتطلب LLMs ميزات متقدمة مثل التكميم والتحكم الدقيق في خطوة اختيار الرمز، والتي يتم تنفيذها بشكل أفضل من خلال [`~generation.GenerationMixin.generate`]. التوليد التلقائي باستخدام LLMs يستهلك الكثير من المواردد ويجب تنفيذه على وحدة معالجة الرسومات للحصول على أداء كافٍ. + + + +أولاً، تحتاج إلى تحميل النموذج. + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained( +... "mistralai/Mistral-7B-v0.1", device_map="auto", load_in_4bit=True +... ) +``` + +ستلاحظ وجود معاملين في الاستدعاء `from_pretrained`: + + - `device_map` يضمن انتقال النموذج إلى وحدة معالجة الرسومات (GPU) الخاصة بك + - `load_in_4bit` يطبق [4-bit dynamic quantization](main_classes/quantization) لخفض متطلبات الموارد بشكل كبير + +هناك طرق أخرى لتهيئة نموذج، ولكن هذا خط أساس جيد للبدء باستخدام LLM. + +بعد ذلك، تحتاج إلى معالجة إدخال النص الخاص بك باستخدام [مُجزّئ اللغوي](tokenizer_summary). + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +>>> model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +يحتوي متغير `model_inputs` على النص المدخل بعد تقسيمه إلى وحدات لغوية (tokens)، بالإضافة إلى قناع الانتباه. في حين أن [`~generation.GenerationMixin.generate`] تبذل قصارى جهدها لاستنتاج قناع الانتباه عندما لا يتم تمريره، نوصي بتمريره كلما أمكن ذلك للحصول على نتائج مثالية. + +بعد تقسيم المدخلات إلى وحدات لغوية، يمكنك استدعاء الدالة [`~generation.GenerationMixin.generate`] لإرجاع الوحدات اللغوية الناتجة. يجب بعد ذلك تحويل الوحدات المولدة إلى نص قبل طباعته. + +```py +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A list of colors: red, blue, green, yellow, orange, purple, pink,' +``` + +أخيرًا، ليس عليك معالجة المتتاليات الواحدة تلو الأخرى! يمكنك معالجة مجموعة من المدخلات دفعة واحدة، والتي ستعمل على تحسين الإنتاجية بشكل كبير بتكلفة صغيرة في زمن الاستجابة واستهلاك الذاكر. كل ما عليك التأكد منه هو تعبئة المدخلات بشكل صحيح (المزيد حول ذلك أدناه). + +```py +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model_inputs = tokenizer( +... ["A list of colors: red, blue", "Portugal is"], return_tensors="pt", padding=True +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +['A list of colors: red, blue, green, yellow, orange, purple, pink,', +'Portugal is a country in southwestern Europe, on the Iber'] +``` + +وهذا كل شيء! في بضع سطور من التعليمات البرمجية، يمكنك تسخير قوة LLM. + +## الأخطاء الشائعة + +هناك العديد من [استراتيجيات التوليد](generation_strategies)، وفي بعض الأحيان قد لا تكون القيم الافتراضية مناسبة لحالتك الاستخدام. إذا لم تكن الإخراج الخاصة بك متوافقة مع ما تتوقعه، فقد قمنا بإنشاء قائمة بأكثر الأخطاء الشائعة وكيفية تجنبها. + +```py +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model = AutoModelForCausalLM.from_pretrained( +... "mistralai/Mistral-7B-v0.1", device_map="auto", load_in_4bit=True +... ) +``` + +### الإخراج المولد قصير جدًا/طويل جدًا + +إذا لم يتم تحديد العدد الأقصى للرموز في [`~generation.GenerationConfig`] الملف، `generate` يعيد ما يصل إلى 20 رمزًا بشكل افتراضي. نوصي بشدة بتعيين `max_new_tokens` يدويًا في مكالمة `generate` للتحكم في العدد الأقصى من الرموز الجديدة التي يمكن أن يعيدها. ضع في اعتبارك أن LLMs (بشكل أكثر دقة، [نماذج فك التشفير فقط](https://huggingface.co/learn/nlp-course/chapter1/6؟fw=pt)) تعيد أيضًا المدخلات الأصلية كجزء من الناتج. +```py +>>> model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") + +>>> # By default, the output will contain up to 20 tokens +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' + +>>> # Setting `max_new_tokens` allows you to control the maximum length +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=50) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + +### وضع التوليد الافتراضي + +بشكل افتراضي، وما لم يتم تحديده في [`~generation.GenerationConfig`] الملف، `generate` يحدد الكلمة الأكثر احتمالًا فى كل خطوة من خطوات عملية التوليد (وهذا يُعرف بالتشفير الجشع). اعتمادًا على مهمتك، قد يكون هذا غير مرغوب فيه؛ تستفيد المهام الإبداعية مثل برامج الدردشة أو كتابة مقال ستفيد من أسلوب العينة العشوائية في اختيار الكلمات، تمن ناحية أخرى، فإن المهام التي تعتمد على مدخلات محددة مثل تحويل الصوت إلى نص أو الترجم من فك التشفير الجشع. قم بتفعيل أسلوب العينات العشوائية باستخدام `do_sample=True`، ويمكنك معرفة المزيد حول هذا الموضوع في [تدوينة المدونة](https://huggingface.co/blog/how-to-generate). + +```py +>>> # Set seed or reproducibility -- you don't need this unless you want full reproducibility +>>> from transformers import set_seed +>>> set_seed(42) + +>>> model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") + +>>> # LLM + greedy decoding = repetitive, boring output +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. I am a cat. I am a cat. I am a cat' + +>>> # With sampling, the output becomes more creative! +>>> generated_ids = model.generate(**model_inputs, do_sample=True) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. Specifically, I am an indoor-only cat. I' +``` + +### مشكلة حشو المدخلات فى الاتجاة الخطأ + +LLMs هي [معماريات فك التشفير فقط](https://huggingface.co/learn/nlp-course/chapter1/6؟fw=pt)، مما يعني أنها تستمر في التكرار على موجه الإدخال الخاص بك. فإن جميع المدخلات يجب أن تكون بنفس الطول. لحل هذه المسألة، يتم إضافة رموز حشو إلى المدخلات الأقصر. نظرًا لأن LLMs لا تولي اهتمامًا لرموز الحشو هذه، ذلك، يجب تحديد الجزء المهم من المدخل الذي يجب أن يركز عليه النموذج، وهذا يتم عن طريق ما يسمى بـ "قناع الانتباه". يجب أن يكون الحشو في بداية المدخل (الحشو من اليسار)، وليس في نهايته. + +```py +>>> # The tokenizer initialized above has right-padding active by default: the 1st sequence, +>>> # which is shorter, has padding on the right side. Generation fails to capture the logic. +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 33333333333' + +>>> # With left-padding, it works as expected! +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +>>> tokenizer.pad_token = tokenizer.eos_token # Most LLMs don't have a pad token by default +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + +### موجه غير صحيح + +تتوقع بعض نماذج اللغات الكبيرة على صيغة محددة للمدخلات للعمل بشكل صحيح. إذا لم يتم اتباع هذه الصيغة، فإن أداء النموذج يتأثر سلبًا: لكن هذا التدهور قد لا يكون واضحًا للعيان. تتوفر معلومات إضافية حول التوجيه، بما في ذلك النماذج والمهام التي تحتاج إلى توخي الحذر، في [الدليل](tasks/prompting). دعنا نرى مثالاً باستخدام LLM للدردشة، والذي يستخدم [قالب الدردشة](chat_templating): +```python +>>> tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha") +>>> model = AutoModelForCausalLM.from_pretrained( +... "HuggingFaceH4/zephyr-7b-alpha", device_map="auto", load_in_4bit=True +... ) +>>> set_seed(0) +>>> prompt = """How many helicopters can a human eat in one sitting? Reply as a thug.""" +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +>>> input_length = model_inputs.input_ids.shape[1] +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=20) +>>> print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"I'm not a thug, but i can tell you that a human cannot eat" +>>> # Oh no, it did not follow our instruction to reply as a thug! Let's see what happens when we write +>>> # a better prompt and use the right template for this model (through `tokenizer.apply_chat_template`) + +>>> set_seed(0) +>>> messages = [ +... { +... "role": "system", +... "content": "You are a friendly chatbot who always responds in the style of a thug", +... }, +... {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, +... ] +>>> model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda") +>>> input_length = model_inputs.shape[1] +>>> generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=20) +>>> print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +'None, you thug. How bout you try to focus on more useful questions?' +>>> # As we can see, it followed a proper thug style 😎 +``` + +## موارد إضافية + +في حين أن عملية التوليد التلقائي بسيطة نسبيًا، فإن الاستفادة القصوى من LLM الخاص بك يمكن أن تكون مهمة صعبة لأن هناك العديد من الأجزاء المتحركة. للخطوات التالية لمساعدتك في الغوص بشكل أعمق في استخدام LLM وفهمه: + +### استخدامات متقدمة للتوليد في نماذج اللغات الكبيرة + +1. دليل حول كيفية [التحكم في طرق التوليد المختلفة](generation_strategies)، وكيفية إعداد ملف تكوين التوليد، وكيفية بث الناتج؛ +2. [تسريع توليد النص](llm_optims)؛ +3.[قوالب موجهات للدردشة LLMs](chat_ +4. [دليل تصميم الموجه](tasks/prompting); +5. مرجع واجهة برمجة التطبيقات (API) [`~generation.GenerationConfig`], [`~generation.GenerationMixin.generate`], و [generate-related classes](internal/generation_utils). والعديد من الفئات الأخرى المرتبطة بعملية التوليد.! + +### لوحات صدارة نماذج اللغات الكبيرة +1. لوحة صدارة نماذج اللغات الكبيرة المفتوحة المصدر (Open LLM Leaderboard): تركز على جودة النماذج مفتوحة المصدر [رابط لوحة الصدارة](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). +2. لوحة صدارة أداء نماذج اللغات الكبيرة المفتوحة المصدر (Open LLM-Perf Leaderboard): تركز على إنتاجية نماذج اللغات الكبيرة [رابط لوحة الصدارة](https://huggingface.co/spaces/optimum/llm-perf-leaderboard). + +### زمن الاستجابة والإنتاجية واستهلاك الذاكرة +1. دليل تحسين نماذج اللغات الكبيرة من حيث السرعة والذاكرة: دليل تحسين نماذج اللغات الكبيرة. +2. التكميم (Quantization): دليل حول تقنية التكميم التكميم مثل تقنيتي bitsandbytes و autogptq، والتي توضح كيفية تقليل متطلبات الذاكرة بشكل كبير. + +### مكتبات مرتبطة +1. [`optimum`](https://github.com/huggingface/optimum), امتداد لمكتبة Transformers يعمل على تحسين الأداء لأجهزة معينة. +2. [`outlines`](https://github.com/outlines-dev/outlines), مكتبة للتحكم في توليد النصوص (على سبيل المثال، لتوليد ملفات JSON). +3. [`SynCode`](https://github.com/uiuc-focal-lab/syncode), مكتبة للتوليد الموجه بقواعد اللغة الخالية من السياق (على سبيل المثال، JSON، SQL، Python). +4. [`text-generation-inference`](https://github.com/huggingface/text-generation-inference), خادم جاهز للإنتاج لنماذج اللغات الكبيرة. +5. [`text-generation-webui`](https://github.com/oobabooga/text-generation-webui), واجهة مستخدم لتوليد النصوص.   diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial_optimization.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial_optimization.md new file mode 100644 index 0000000000000000000000000000000000000000..59f17f7f8a92c2c997e8c97df8e55d07b76e3c09 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/llm_tutorial_optimization.md @@ -0,0 +1,795 @@ +# تحسين نماذج اللغة الكبيرة من حيث السرعة والذاكرة + + +[[open-in-colab]] + +تحقق نماذج اللغة الكبيرة (LLMs) مثل GPT3/4، [Falcon](https://huggingface.co/tiiuae/falcon-40b)، و [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) تقدمًا سريعًا في قدرتها على معالجة المهام التي تركز على الإنسان، مما يجعلها أدوات أساسية في الصناعات القائمة على المعرفة الحديثة. +لا يزال نشر هذه النماذج في المهام الواقعية يمثل تحديًا، ومع ذلك: + +- لكي تظهر نماذج اللغة الكبيرة قدرات فهم وتوليد النصوص قريبة من قدرات الإنسان، فإنها تتطلب حاليًا إلى تكوينها من مليارات المعلمات (انظر [كابلان وآخرون](https://arxiv.org/abs/2001.08361)، [وي وآخرون](https://arxiv.org/abs/2206.07682)). وهذا بدوره يزيد من متطلبات الذاكرة للاستدلال. +- في العديد من المهام الواقعية، تحتاج نماذج اللغة الكبيرة إلى معلومات سياقية شاملة. يتطلب ذلك قدرة النموذج على إدارة تسلسلات إدخال طويلة للغاية أثناء الاستدلال. + +يكمن جوهر صعوبة هذه التحديات في تعزيز القدرات الحسابية والذاكرة لنماذج اللغة الكبيرة، خاصة عند التعامل مع تسلسلات الإدخال الضخمة. + +في هذا الدليل، سنستعرض التقنيات الفعالة لتُحسِّن من كفاءة نشر نماذج اللغة الكبيرة: + +1. سنتناول تقنية "دقة أقل" التي أثبتت الأبحاث فعاليتها في تحقيق مزايا حسابية دون التأثير بشكل ملحوظ على أداء النموذج عن طريق العمل بدقة رقمية أقل [8 بت و4 بت](/main_classes/quantization.md). + +2. **اFlash Attention:** إن Flash Attention وهي نسخة مُعدَّلة من خوارزمية الانتباه التي لا توفر فقط نهجًا أكثر كفاءة في استخدام الذاكرة، ولكنها تحقق أيضًا كفاءة متزايدة بسبب الاستخدام الأمثل لذاكرة GPU. + +3. **الابتكارات المعمارية:** حيث تم اقتراح هياكل متخصصة تسمح باستدلال أكثر فعالية نظرًا لأن نماذج اللغة الكبيرة يتم نشرها دائمًا بنفس الطريقة أثناء عملية الاستدلال، أي توليد النص التنبؤي التلقائي مع سياق الإدخال الطويل، فقد تم اقتراح بنيات نموذج متخصصة تسمح بالاستدلال الأكثر كفاءة. أهم تقدم في بنيات النماذج هنا هو [عذر](https://arxiv.org/abs/2108.12409)، [الترميز الدوار](https://arxiv.org/abs/2104.09864)، [الاهتمام متعدد الاستعلامات (MQA)](https://arxiv.org/abs/1911.02150) و [مجموعة الانتباه بالاستعلام (GQA)]((https://arxiv.org/abs/2305.13245)). + +على مدار هذا الدليل، سنقدم تحليلًا للتوليد التنبؤي التلقائي من منظور المُوتِّرات. نتعمق في مزايا وعيوب استخدام دقة أقل، ونقدم استكشافًا شاملاً لخوارزميات الانتباه الأحدث، ونناقش بنيات نماذج نماذج اللغة الكبيرة المحسنة. سندعم الشرح بأمثلة عملية تُبرِز كل تحسين على حدة. + +## 1. دقة أقل + +يمكن فهم متطلبات ذاكرة نماذج اللغة الكبيرة بشكل أفضل من خلال النظر إلى نموذج اللغة الكبيرة على أنها مجموعة من المصفوفات والمتجهات الوزنية، ومدخلات النص على أنها تسلسل من المتجهات. فيما يلي، سيتم استخدام تعريف "الأوزان" للإشارة إلى جميع مصفوفات الأوزان والمتجهات في النموذج. +في وقت كتابة هذا الدليل، تتكون نماذج اللغة الكبيرة من مليارات المعلمات على الأقل.كل معلمة يتم تمثيلها برقم عشري مثل 4.5689 `` والذي يتم تخزينه عادةً بتنسيق [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format)، [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format)، أو [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) . يسمح لنا هذا بحساب متطلبات الذاكرة لتحميل نموذج اللغة الكبيرة في الذاكرة بسهولة: + +> *يتطلب تحميل أوزان نموذج به X مليار معلمة حوالي 4 * X جيجابايت من ذاكرة الفيديو العشوائية (VRAM) بدقة float32* + +ومع ذلك، نادرًا ما يتم تدريب النماذج في الوقت الحالي بدقة float32 الكاملة، ولكن عادةً ما تكون بدقة bfloat16 أو بشكل أقل في تنسيق float16. لذلك، تصبح القاعدة الإرشادية كما يلي: + +> *يتطلب تحميل أوزان نموذج به X مليار معلمة حوالي 2 * X جيجابايت من ذاكرة الفيديو العشوائية (VRAM) بدقة bfloat16/float16* + +بالنسبة لمدخلات النصوص القصيرة (أقل من 1024 رمزًا)، فإن متطلبات الذاكرة للاستدلال تهيمن عليها إلى حد كبير متطلبات الذاكرة لتحميل الأوزان. لذلك، دعنا نفترض، في الوقت الحالي، أن متطلبات الذاكرة للاستدلال تساوي متطلبات الذاكرة لتحميل النموذج في ذاكرة VRAM لوحدة معالجة الرسومات GPU.. + +ولإعطاء بعض الأمثلة على مقدار ذاكرة الفيديو العشوائية (VRAM) التي يتطلبها تحميل نموذج بتنسيق bfloat16 تقريبًا: + +- **GPT3** يتطلب 2 \* 175 جيجا بايت = **350 جيجا بايت** VRAM +- [**بلوم**](https://huggingface.co/bigscience/bloom) يتطلب 2 \* 176 جيجا بايت = **352 جيجا بايت** VRAM +- [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) يتطلب 2 \* 70 جيجا بايت = **140 جيجا بايت** VRAM +- [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) يتطلب 2 \* 40 جيجا بايت = **80 جيجا بايت** VRAM +- [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) يتطلب 2 \* 30 جيجا بايت = **60 جيجا بايت** VRAM +- [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) يتطلب 2 \* 15.5 = **31 جيجا بايت** VRAM + +عند كتابة هذا الدليل، أكبر شريحة لوحدة معالجة الرسومات المتوفّرة هي A100 و H100 التي توفر 80 جيجابايت من ذاكرة الفيديو العشوائية (VRAM). تتطلب معظم النماذج المدرجة أعلاه أكثر من 80 جيجابايت فقط لتحميلها، وبالتالي فهي تتطلب بالضرورة [التوازي للموتّرات](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) و/أو [لتوازي الخطي](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +🤗 لا يدعم Transformers موازاة التنسور خارج الصندوق لأنه يتطلب كتابة هيكلة النموذج بطريقة محددة. إذا كنت مهتمًا بكتابة نماذج بطريقة صديقة لموازاة التنسور، فلا تتردد في إلقاء نظرة على [مكتبة الاستدلال بتوليد النص](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling). + +بدعم موازاة قنوات المعالجة البسيطة خارج الصندوق. للقيام بذلك، قم بتحميل النموذج باستخدام `device="auto"` والذي سيقوم تلقائيًا بوضع الطبقات المختلفة على وحدات معالجة الرسومات (GPU) المتاحة كما هو موضح [هنا](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference). +لاحظ، مع ذلك، أنه في حين أن موازاة قنوات المعالجة البسيطة فعالة للغاية، إلا أنها لا تعالج مشكلات عدم نشاط وحدة معالجة الرسومات (GPU). لهذا، تكون موازاة قنوات المعالجة المتقدمة مطلوبة كما هو موضح [هنا](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +إذا كان لديك حق الوصول إلى عقدة 8 x 80 جيجابايت A100، فيمكنك تحميل BLOOM كما يلي + +```bash +!pip install transformers accelerate bitsandbytes optimum +``` +```python +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0) +``` + +من خلال استخدام `device_map="auto"` سيتم توزيع طبقات الاهتمام بالتساوي عبر جميع وحدات معالجة الرسومات (GPU) المتاحة. + +في هذا الدليل، سنستخدم [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) لأنه يمكن تشغيله على شريحة جهاز GPU A100 ذات 40 جيجا بايت. لاحظ أن جميع تحسينات الذاكرة والسرعة التي سنطبقها من الآن فصاعدًا تنطبق بالتساوي على النماذج التي تتطلب موازاة النماذج أو المصفوفات. + +نظرًا لأن النموذج مُحمَّل بدقة bfloat16، فباستخدام قاعدتنا الإرشادية أعلاه، نتوقع أن تكون متطلبات الذاكرة لتشغيل الاستدلال باستخدام `bigcode/octocoder` حوالي 31 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM). دعنا نجرب. + +نقوم أولاً بتحميل النموذج والمجزىء اللغوي ثم نقوم بتمرير كلاهما إلى كائن [قنوات المعالجة](https://huggingface.co/docs/transformers/main_classes/pipelines) في Transformers. + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline +import torch + +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0) +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +```python +prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:" + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +رائع، يمكننا الآن استخدام النتيجة مباشرة لتحويل البايت إلى جيجا بايت. + +```python +def bytes_to_giga_bytes(bytes): + return bytes / 1024 / 1024 / 1024 +``` + +دعونا نستدعي [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) لقياس ذروة تخصيص ذاكرة وحدة معالجة الرسومات (GPU). + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +```bash +29.0260648727417 +``` + +قريب بما يكفي من حسابنا التقريبي! يمكننا أن نرى أن الرقم غير صحيح تمامًا لأن الانتقال من البايت إلى الكيلوبايت يتطلب الضرب في 1024 بدلاً من 1000. لذلك يمكن أيضًا فهم صيغة التقريب على أنها حساب "بحد أقصى X جيجا بايت". +لاحظ أنه إذا حاولنا تشغيل النموذج بدقة float32 الكاملة، فستكون هناك حاجة إلى 64 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM). + +> يتم تدريب جميع النماذج تقريبًا بتنسيق bfloat16 في الوقت الحالي، ولا يوجد سبب لتشغيل النموذج بدقة float32 الكاملة إذا [كانت وحدة معالجة الرسومات (GPU) الخاصة بك تدعم bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). لن توفر دقة float32 نتائج استدلال أفضل من الدقة التي تم استخدامها لتدريب النموذج. + +إذا لم تكن متأكدًا من تنسيق تخزين أوزان النموذج على Hub، فيمكنك دائمًا الاطلاع على تهيئة نقطة التفتيش في `"torch_dtype"`، على سبيل المثال [هنا](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). يوصى بتعيين النموذج إلى نفس نوع الدقة كما هو مكتوب في التهيئة عند التحميل باستخدام `from_pretrained(..., torch_dtype=...)` إلا إذا كان النوع الأصلي هو float32، وفي هذه الحالة يمكن استخدام `float16` أو `bfloat16` للاستدلال. + + +دعونا نحدد وظيفة `flush(...)` لتحرير جميع الذاكرة المخصصة بحيث يمكننا قياس ذروة ذاكرة وحدة معالجة الرسومات (GPU) المخصصة بدقة. + +```python +del pipe +del model + +import gc +import torch + +def flush(): + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() +``` + +دعونا نستدعيه الآن للتجربة التالية. + +```python +flush() +``` +في الإصدار الأخير من مكتبة Accelerate، يمكنك أيضًا استخدام طريقة مساعدة تسمى `release_memory()` + +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` + +والآن ماذا لو لم يكن لدى وحدة معالجة الرسومات (GPU) لديك 32 جيجا بايت من ذاكرة الفيديو العشوائية (VRAM)؟ لقد وجد أن أوزان النماذج يمكن تحويلها إلى 8 بتات أو 4 بتات دون خسارة كبيرة في الأداء (انظر [Dettmers et al.](https://arxiv.org/abs/2208.07339)). +يمكن تحويل النموذج إلى 3 بتات أو 2 بتات مع فقدان مقبول في الأداء كما هو موضح في ورقة [GPTQ](https://arxiv.org/abs/2210.17323) 🤯. + +دون الدخول في الكثير من التفاصيل، تهدف مخططات التكميم إلى تخفيض دقة الأوزان مع محاولة الحفاظ على دقة نتائج النموذج كما هي (*أي* أقرب ما يمكن إلى bfloat16). +لاحظ أن التكميم يعمل بشكل خاص جيدًا لتوليد النص حيث كل ما نهتم به هو اختيار *مجموعة الرموز الأكثر احتمالًا التالية* ولا نهتم حقًا بالقيم الدقيقة لتوزيع الرمز التالي *logit*. +كل ما يهم هو أن توزيع الرمز التالي *logit* يظل كما هو تقريبًا بحيث تعطي عملية `argmax` أو `topk` نفس النتائج. + +هناك عدة تقنيات للتكميم، والتي لن نناقشها بالتفصيل هنا، ولكن بشكل عام، تعمل جميع تقنيات التكميم كما يلي: + +- 1. تكميم جميع الأوزان إلى الدقة المستهدفة +- 2. تحميل الأوزان المحولة، ومرر تسلسل المدخلات من المتجهات بتنسيق bfloat16 +- 3. قم بتحويل الأوزان ديناميكيًا إلى bfloat1 لإجراء الحسابات مع متجهات المدخلات بدقة `bfloat16` + +باختصار، هذا يعني أن مضروبات *مصفوفة المدخلات-الوزن*، حيث \\( X \\) هي المدخلات، \\( W \\) هي مصفوفة وزن و \\( Y \\) هي الناتج: + +$$ Y = X * W $$ + +تتغير إلى + +$$ Y = X * \text{dequantize}(W) $$ + +لكل عملية ضرب المصفوفات. يتم تنفيذ إلغاء التكميم وإعادة التكميم بشكل متسلسل لجميع مصفوفات الأوزان أثناء مرور المدخلات عبر رسم الشبكة. + +لذلك، غالبًا ما لا يتم تقليل وقت الاستدلال عند استخدام الأوزان المكممة، ولكن بدلاً من ذلك يزيد. + +كفى نظرية، دعنا نجرب! لتكميم الأوزان باستخدام المحولات، تحتاج إلى التأكد من تثبيت مكتبة [`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes). + +```bash +!pip install bitsandbytes +``` + +يمكننا بعد ذلك تحميل النماذج في تكميم 8 بت ببساطة عن طريق إضافة علامة `load_in_8bit=True` إلى `from_pretrained`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0) +``` + +الآن، دعنا نعيد تشغيل مثالنا ونقيس استخدام الذاكرة. + +```python +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +جميل، نحصل على نفس النتيجة كما في السابق، لذلك لا يوجد فقدان في الدقة! دعنا نلقي نظرة على مقدار الذاكرة المستخدمة هذه المرة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +15.219234466552734 +``` + +أقل بكثير! لقد انخفضنا إلى ما يزيد قليلاً عن 15 جيجابايت، وبالتالي يمكننا تشغيل هذا النموذج على وحدات معالجة الرسومات للمستهلك مثل 4090. + +نرى مكسبًا لطيفًا جدًا في كفاءة الذاكرة ولا يوجد تقريبًا أي تدهور في ناتج النموذج. ومع ذلك، يمكننا أيضًا ملاحظة تباطؤ طفيف أثناء الاستدلال. + +نحذف النماذج ونفرغ الذاكرة مرة أخرى. +```python +del model +del pipe +``` + +```python +flush() +``` + +دعنا نرى ما هو استهلاك ذاكرة GPU الذروة الذي يوفره تكميم 4 بت. يمكن تكميم النموذج إلى 4 بت باستخدام نفس واجهة برمجة التطبيقات كما في السابق - هذه المرة عن طريق تمرير `load_in_4bit=True` بدلاً من `load_in_8bit=True`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, low_cpu_mem_usage=True, pad_token_id=0) + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**الإخراج**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument +``` + +نحن نرى تقريبًا نفس نص الإخراج كما في السابق - فقط `python` مفقود قبل مقطع الكود. دعنا نرى مقدار الذاكرة المطلوبة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +9.543574333190918 +``` + +فقط 9.5 جيجابايت! هذا ليس كثيرًا بالفعل لنموذج يزيد عدد معاملاته عن 15 مليار. + +على الرغم من أننا نرى تدهورًا بسيطًا جدًا في الدقة لنموذجنا هنا، إلا أن تكميم 4 بت يمكن أن يؤدي في الممارسة العملية غالبًا إلى نتائج مختلفة مقارنة بتكميم 8 بت أو الاستدلال الكامل `bfloat16`. الأمر متروك للمستخدم لتجربته. + +لاحظ أيضًا أن الاستدلال هنا كان أبطأ قليلاً مقارنة بتكميم 8 بت والذي يرجع إلى طريقة التكميم الأكثر عدوانية المستخدمة لتكميم 4 بت مما يؤدي إلى \\( \text{quantize} \\) و \\( \text{dequantize} \\) يستغرق وقتًا أطول أثناء الاستدلال. + +```python +del model +del pipe +``` +```python +flush() +``` + +بشكل عام، رأينا أن تشغيل OctoCoder بدقة 8 بت قلل من ذاكرة GPU VRAM المطلوبة من 32G GPU VRAM إلى 15 جيجابايت فقط، وتشغيل النموذج بدقة 4 بت يقلل من ذاكرة GPU VRAM المطلوبة إلى ما يزيد قليلاً عن 9 جيجابايت. + +يسمح تكميم 4 بت بتشغيل النموذج على وحدات معالجة الرسومات مثل RTX3090 و V100 و T4 والتي يمكن الوصول إليها بسهولة لمعظم الأشخاص. + +لمزيد من المعلومات حول التكميم ولمعرفة كيف يمكن تكميم النماذج لطلب ذاكرة GPU VRAM أقل حتى من 4 بت، نوصي بالاطلاع على تنفيذ [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60). + +> كاستنتاج، من المهم تذكر أن تكميم النموذج يتداول كفاءة الذاكرة المحسنة مقابل الدقة وفي بعض الحالات وقت الاستدلال. + +إذا لم تكن ذاكرة GPU قيدًا لحالتك الاستخدام، فغالبًا لا توجد حاجة للنظر في التكميم. ومع ذلك، لا يمكن للعديد من وحدات معالجة الرسومات ببساطة تشغيل نماذج اللغة الكبيرة بدون طرق التكميم وفي هذه الحالة، تعد مخططات التكميم 4 بت و 8 بت أدوات مفيدة للغاية. + +لمزيد من المعلومات حول الاستخدام التفصيلي، نوصي بشدة بإلقاء نظرة على [وثائق تكميم المحولات](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage). + +بعد ذلك، دعنا نلقي نظرة على كيفية تحسين الكفاءة الحسابية وكفاءة الذاكرة باستخدام خوارزميات أفضل وبنية نموذج محسنة. + +## 2. الانتباه السريع + +تتشارك نماذج اللغة الكبيرة (LLMs) الأعلى أداءً اليوم تقريبًا نفس البنية الأساسية التي تتكون من طبقات التغذية الأمامية، وطبقات التنشيط، وطبقات التطبيع الطبقي، والأهم من ذلك، طبقات الانتباه الذاتي. + +تعد طبقات الانتباه الذاتي مركزية لنماذج اللغة الكبيرة (LLMs) حيث تمكن النموذج من فهم العلاقات السياقية بين رموز المدخلات. +ومع ذلك، فإن استهلاك ذاكرة GPU الذروة لطبقات الانتباه الذاتي ينمو بشكل *رباعي* في كل من التعقيد الحسابي وتعقيد الذاكرة مع عدد رموز المدخلات (والذي يُطلق عليه أيضًا *طول التسلسل*) الذي نسميه في ما يلي بـ \\( N \\) . +على الرغم من أن هذا غير ملحوظ حقًا للتسلسلات الأقصر (حتى 1000 رمز إدخال)، إلا أنه يصبح مشكلة خطيرة للتسلسلات الأطول (حوالي 16000 رمز إدخال). + +دعنا نلقي نظرة أقرب. الصيغة لحساب الناتج \\( \mathbf{O} \\) لطبقة الانتباه الذاتي لإدخال \\( \mathbf{X} \\) بطول \\( N \\) هي: + +$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$ + +يعد \\( \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) بالتالي تسلسل الإدخال إلى طبقة الاهتمام. وستتكون كل من الإسقاطات \\( \mathbf{Q} \\) و \\( \mathbf{K} \\) من \\( N \\) من المتجهات مما يؤدي إلى أن يكون حجم \\( \mathbf{QK}^T \\) هو \\( N^2 \\). + +عادة ما يكون لدى LLMs العديد من رؤوس الاهتمام، وبالتالي يتم إجراء العديد من حسابات الاهتمام الذاتي بالتوازي. +وبافتراض أن LLM لديها 40 رأس اهتمام وتعمل بدقة bfloat16، يمكننا حساب متطلبات الذاكرة لتخزين مصفوفات \\( \mathbf{QK^T} \\) لتكون \\( 40 * 2 * N^2 \\) بايت. بالنسبة لـ \\( N=1000 \\)، لا يلزم سوى حوالي 50 ميجابايت من VRAM، ولكن بالنسبة لـ \\( N=16000 \\) سنحتاج إلى 19 جيجابايت من VRAM، وبالنسبة لـ \\( N=100,000 \\) سنحتاج إلى ما يقرب من 1 تيرابايت فقط لتخزين مصفوفات \\( \mathbf{QK}^T \\). + +باختصار، سرعان ما يصبح خوارزمية الانتباه الذاتي الافتراضية مكلفة للغاية من حيث الذاكرة بالنسبة لسياقات الإدخال الكبيرة. + +مع تحسن LLMs في فهم النص وتوليد النص، يتم تطبيقها على مهام متزايدة التعقيد. في حين أن النماذج كانت تتعامل سابقًا مع ترجمة أو تلخيص بضع جمل، فإنها الآن تدير صفحات كاملة، مما يتطلب القدرة على معالجة أطوال إدخال واسعة. + +كيف يمكننا التخلص من متطلبات الذاكرة الباهظة للتطويلات المدخلة الكبيرة؟ نحن بحاجة إلى طريقة جديدة لحساب آلية الاهتمام الذاتي التي تتخلص من مصفوفة \\( QK^T \\). [طريقه داو وآخرون.](Https://arxiv.org/abs/2205.14135) طوروا بالضبط مثل هذا الخوارزمية الجديدة وأطلقوا عليها اسم **Flash Attention**. + +باختصار، يكسر الاهتمام الفلاشي حساب \\( \mathbf{V} \times \operatorname{Softmax}(\mathbf{QK}^T\\)) ويحسب بدلاً من ذلك قطعًا أصغر من الإخراج عن طريق التكرار عبر العديد من خطوات حساب Softmax: + +$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \operatorname{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations } $$ + +مع \\( s^a_{ij} \\) و \\( s^b_{ij} \\) كونها بعض إحصائيات التطبيع softmax التي يجب إعادة حسابها لكل \\( i \\) و \\( j \\). + +يرجى ملاحظة أن Flash Attention بالكامل أكثر تعقيدًا إلى حد ما ويتم تبسيطه بشكل كبير هنا حيث أن التعمق كثيرًا يخرج عن نطاق هذا الدليل. القارئ مدعو لإلقاء نظرة على ورقة Flash Attention المكتوبة جيدًا [1] لمزيد من التفاصيل. + +الفكرة الرئيسية هنا هي: + +> من خلال تتبع إحصائيات التطبيع softmax واستخدام بعض الرياضيات الذكية، يعطي Flash Attention **مخرجات متطابقة رقميًا** مقارنة بطبقة الاهتمام الذاتي الافتراضية بتكلفة ذاكرة لا تزيد خطيًا مع \\( N \\). + +عند النظر إلى الصيغة، قد يقول المرء بديهيًا أن الاهتمام الفلاشي يجب أن يكون أبطأ بكثير مقارنة بصيغة الاهتمام الافتراضية حيث يلزم إجراء المزيد من الحسابات. في الواقع، يتطلب Flash Attention المزيد من عمليات الفاصلة العائمة مقارنة بالاهتمام العادي حيث يجب إعادة حساب إحصائيات التطبيع softmax باستمرار (راجع [الورقة](https://arxiv.org/abs/2205.14135) لمزيد من التفاصيل إذا كنت مهتمًا) + +> ومع ذلك، فإن الاهتمام الفلاشي أسرع بكثير في الاستدلال مقارنة بالاهتمام الافتراضي الذي يأتي من قدرته على تقليل الطلبات على ذاكرة GPU الأبطأ ذات النطاق الترددي العالي (VRAM)، والتركيز بدلاً من ذلك على ذاكرة SRAM الأسرع الموجودة على الشريحة. + +من الناحية الأساسية، يتأكد Flash Attention من إمكانية إجراء جميع عمليات الكتابة والقراءة الوسيطة باستخدام ذاكرة SRAM السريعة الموجودة على الشريحة بدلاً من الاضطرار إلى الوصول إلى ذاكرة VRAM الأبطأ لحساب متجه الإخراج \\( \mathbf{O} \\). + +من الناحية العملية، لا يوجد حاليًا أي سبب **عدم** استخدام الاهتمام الفلاشي إذا كان متاحًا. الخوارزمية تعطي نفس المخرجات رياضيا، وأسرع وأكثر كفاءة في استخدام الذاكرة. + +لنلقِ نظرة على مثال عملي. + + +يحصل نموذج OctoCoder الخاص بنا الآن على موجه إدخال أطول بشكل كبير يتضمن ما يسمى *موجه النظام*. تُستخدم موجهات النظام لتوجيه LLM إلى مساعد أفضل مصمم لمهام المستخدمين. +فيما يلي، نستخدم موجه النظام الذي سيجعل OctoCoder مساعد ترميز أفضل. + +```python +system_prompt = """Below are a series of dialogues between various people and an AI technical assistant. +The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable. +The assistant is happy to help with code questions and will do their best to understand exactly what is needed. +It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer. +That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful. + +The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests). +The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data. +----- + +Question: Write a function that takes two lists and returns a list that has alternating elements from each input list. + +Answer: Sure. Here is a function that does that. + +def alternating(list1, list2): + results = [] + for i in range(len(list1)): + results.append(list1[i]) + results.append(list2[i]) + return results + +Question: Can you write some test cases for this function? + +Answer: Sure, here are some tests. + +assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3] +assert alternating([True, False], [4, 5]) == [True, 4, False, 5] +assert alternating([], []) == [] + +Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end. + +Answer: Here is the modified function. + +def alternating(list1, list2): + results = [] + for i in range(min(len(list1), len(list2))): + results.append(list1[i]) + results.append(list2[i]) + if len(list1) > len(list2): + results.extend(list1[i+1:]) + else: + results.extend(list2[i+1:]) + return results +----- +""" +``` +لأغراض التوضيح، سنكرر موجه النظام عشر مرات بحيث يكون طول الإدخال طويلاً بما يكفي لملاحظة وفورات ذاكرة Flash Attention. +نضيف موجه النص الأصلي "سؤال: يرجى كتابة وظيفة في Python تقوم بتحويل البايتات إلى جيجا بايت. + +```python +long_prompt = 10 * system_prompt + prompt +``` + +نقوم بتنفيذ نموذجنا مرة أخرى بدقة bfloat16. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto") +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +دعنا الآن نقوم بتشغيل النموذج تمامًا مثلما كان من قبل *بدون اهتمام فلاشي* وقياس متطلبات ذاكرة GPU وقت الذروة ووقت الاستدلال. + +```python +import time + +start_time = time.time() +result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**الإخراج**: +``` +تم التوليد في 10.96854019165039 ثانية. +بالتأكيد. إليك وظيفة للقيام بذلك. + +def bytes_to_giga(bytes): +return bytes / 1024 / 1024 / 1024 + +الإجابة: بالتأكيد. إليك وظيفة للقيام بذلك. + +ديف +``` + +نحصل على نفس الإخراج كما كان من قبل، ولكن هذه المرة، يقوم النموذج بتكرار الإجابة عدة مرات حتى يتم قطعها عند 60 رمزًا. ليس من المستغرب أننا كررنا موجه النظام عشر مرات لأغراض التوضيح وبالتالي قمنا بتشغيل النموذج لتكرار نفسه. + +**ملاحظة** لا ينبغي تكرار موجه النظام عشر مرات في التطبيقات الواقعية - مرة واحدة كافية! + +دعنا نقيس متطلبات ذاكرة GPU وقت الذروة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +37.668193340301514 +``` + +كما نرى، فإن متطلبات ذاكرة GPU وقت الذروة أعلى بكثير مما كانت عليه في البداية، وهو ما يرجع إلى حد كبير إلى تسلسل الإدخال الأطول. أيضًا، يستغرق التوليد أكثر من دقيقة بقليل الآن. + +نستدعي `flush()` لتحرير ذاكرة GPU لتجربتنا التالية. + +```python +flush() +``` + +لمقارنة، دعونا نقوم بتشغيل نفس الدالة، ولكن تمكين الاهتمام فلاش بدلا من ذلك. +للقيام بذلك، نقوم بتحويل النموذج إلى [BetterTransformer](Https://huggingface.co/docs/optimum/bettertransformer/overview) ومن خلال القيام بذلك تمكين PyTorch's [SDPA self-attention](Https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) والتي بدورها قادرة على استخدام الاهتمام فلاش. + +```python +model.to_bettertransformer() +``` + +الآن نقوم بتشغيل نفس مقتطف التعليمات البرمجية بالضبط كما كان من قبل وتحت الغطاء سوف تستخدم المحولات الاهتمام فلاش. + +```py +start_time = time.time() +with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): + result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**الإخراج**: +``` +تم التوليد في 3.0211617946624756 ثانية. +بالتأكيد. إليك وظيفة للقيام بذلك. + +def bytes_to_giga(bytes): +return bytes / 1024 / 1024 / 1024 + +الإجابة: بالتأكيد. إليك وظيفة للقيام بذلك. + +ديف +``` + +نحصل على نفس النتيجة بالضبط كما كان من قبل، ولكن يمكننا ملاحظة تسريع كبير بفضل الاهتمام فلاش. + +دعنا نقيس استهلاك الذاكرة لآخر مرة. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**الإخراج**: +``` +32.617331981658936 +``` + +ونحن تقريبا مرة أخرى إلى ذاكرة GPU الذروة الأصلية لدينا 29GB. + +يمكننا أن نلاحظ أننا نستخدم فقط حوالي 100 ميجابايت إضافية من ذاكرة GPU عند تمرير تسلسل إدخال طويل جدًا مع الاهتمام فلاش مقارنة بتمرير تسلسل إدخال قصير كما فعلنا في البداية. + +```py +flush() +``` + +لمزيد من المعلومات حول كيفية استخدام Flash Attention، يرجى الاطلاع على [صفحة doc هذه](Https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2). + +## 3. الابتكارات المعمارية + +حتى الآن، نظرنا في تحسين الكفاءة الحسابية والذاكرة من خلال: + +- صب الأوزان في تنسيق دقة أقل +- استبدال خوارزمية الاهتمام الذاتي بإصدار أكثر كفاءة من حيث الذاكرة والحساب + +دعونا الآن نلقي نظرة على كيفية تغيير بنية LLM بحيث تكون أكثر فعالية وكفاءة للمهام التي تتطلب مدخلات نصية طويلة، على سبيل المثال: +- استرجاع الأسئلة المعززة، +- تلخيص، +- الدردشة + +لاحظ أن "الدردشة" لا تتطلب من LLM التعامل مع مدخلات نصية طويلة فحسب، بل تتطلب أيضًا أن يكون LLM قادرًا على التعامل بكفاءة مع الحوار ذهابًا وإيابًا بين المستخدم والمساعد (مثل ChatGPT). + +بمجرد تدريبها، يصبح من الصعب تغيير بنية LLM الأساسية، لذلك من المهم مراعاة مهام LLM مسبقًا وتحسين بنية النموذج وفقًا لذلك. +هناك مكونان مهمان لبنية النموذج يصبحان بسرعة عنق زجاجة للذاكرة و/أو الأداء لتسلسلات الإدخال الكبيرة. + +- الترميزات الموضعية +- ذاكرة التخزين المؤقت للقيمة الرئيسية + +دعنا نلقي نظرة على كل مكون بمزيد من التفاصيل + +### 3.1 تحسين الترميزات الموضعية لـ LLMs + +يضع الاهتمام الذاتي كل رمز في علاقة مع رموز أخرى. +كمثال، يمكن أن تبدو مصفوفة \\( \operatorname{Softmax}(\mathbf{QK}^T) \\) لتسلسل الإدخال النصي *"مرحبًا"، "أنا"، "أحب"، "أنت"* كما يلي: + +![](/blog/assets/163_optimize_llm/self_attn_tokens.png) + +يتم منح كل رمز كلمة كتلة احتمال يتم من خلالها الاهتمام بجميع رموز الكلمات الأخرى، وبالتالي يتم وضعها في علاقة مع جميع رموز الكلمات الأخرى. على سبيل المثال، تحضر كلمة *"الحب"* كلمة *"مرحبًا"* بنسبة 5%، و *"أنا"* بنسبة 30%، ونفسها بنسبة 65%. + +سيواجه LLM القائم على الاهتمام الذاتي، ولكن بدون الترميزات الموضعية، صعوبات كبيرة في فهم مواضع نصوص الإدخال بالنسبة لبعضها البعض. +ويرجع ذلك إلى أن درجة الاحتمال التي يحسبها \\( \mathbf{QK}^T \\) تربط كل رمز كلمة بكل رمز كلمة أخرى في حسابات \\( O (1) \\) بغض النظر عن مسافة الموضع النسبي بينهما. +لذلك، بالنسبة إلى LLM بدون ترميزات موضعية، يبدو أن كل رمز له نفس المسافة إلى جميع الرموز الأخرى، على سبيل المثال، سيكون من الصعب التمييز بين *"مرحبًا أنا أحبك"* و *"أنت تحبني مرحبًا"*. + +لكي يفهم LLM ترتيب الجملة، يلزم وجود *إشارة* إضافية ويتم تطبيقها عادةً في شكل *الترميزات الموضعية* (أو ما يُطلق عليه أيضًا *الترميزات الموضعية*). +لم يتم ترجمة النص الخاص والروابط وأكواد HTML وCSS بناءً على طلبك. + +قدم مؤلفو الورقة البحثية [*Attention Is All You Need*](https://arxiv.org/abs/1706.03762) تضمينات موضعية جيبية مثلثية \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) حيث يتم حساب كل متجه \\( \mathbf{p}_i \\) كدالة جيبية لموضعه \\( i \\) . +بعد ذلك يتم ببساطة إضافة التضمينات الموضعية إلى متجهات تسلسل الإدخال \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) وبالتالي توجيه النموذج لتعلم ترتيب الجملة بشكل أفضل. + +بدلاً من استخدام التضمينات الموضعية الثابتة، استخدم آخرون (مثل [Devlin et al.](https://arxiv.org/abs/1810.04805)) تضمينات موضعية مكتسبة يتم من خلالها تعلم التضمينات الموضعية \\( \mathbf{P} \\) أثناء التدريب. + +كانت التضمينات الموضعية الجيبية والمكتسبة هي الطرق السائدة لترميز ترتيب الجملة في نماذج اللغة الكبيرة، ولكن تم العثور على بعض المشكلات المتعلقة بهذه التضمينات الموضعية: + +1. التضمينات الموضعية الجيبية والمكتسبة هي تضمينات موضعية مطلقة، أي ترميز تضمين فريد لكل معرف موضعي: \\( 0, \ldots, N \\) . كما أظهر [Huang et al.](https://arxiv.org/abs/2009.13658) و [Su et al.](https://arxiv.org/abs/2104.09864)، تؤدي التضمينات الموضعية المطلقة إلى أداء ضعيف لنماذج اللغة الكبيرة للمدخلات النصية الطويلة. بالنسبة للمدخلات النصية الطويلة، يكون من المفيد إذا تعلم النموذج المسافة الموضعية النسبية التي تمتلكها رموز المدخلات إلى بعضها البعض بدلاً من موضعها المطلق. +2. عند استخدام التضمينات الموضعية المكتسبة، يجب تدريب نموذج اللغة الكبيرة على طول إدخال ثابت \\( N \\)، مما يجعل من الصعب الاستقراء إلى طول إدخال أطول مما تم تدريبه عليه. + +في الآونة الأخيرة، أصبحت التضمينات الموضعية النسبية التي يمكنها معالجة المشكلات المذكورة أعلاه أكثر شعبية، وأبرزها: + +- [تضمين الموضع الدوراني (RoPE)](https://arxiv.org/abs/2104.09864) +- [ALiBi](https://arxiv.org/abs/2108.12409) + +يؤكد كل من *RoPE* و *ALiBi* أنه من الأفضل توجيه نموذج اللغة الكبيرة حول ترتيب الجملة مباشرة في خوارزمية الانتباه الذاتي حيث يتم وضع رموز الكلمات في علاقة مع بعضها البعض. على وجه التحديد، يجب توجيه ترتيب الجملة عن طريق تعديل عملية \\( \mathbf{QK}^T \\) . + +دون الدخول في الكثير من التفاصيل، يشير *RoPE* إلى أنه يمكن ترميز المعلومات الموضعية في أزواج الاستعلام-المفتاح، على سبيل المثال \\( \mathbf{q}_i \\) و \\( \mathbf{x}_j \\) عن طريق تدوير كل متجه بزاوية \\( \theta * i \\) و \\( \theta * j \\) على التوالي مع \\( i, j \\) تصف موضع الجملة لكل متجه: + +$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j. $$ + +يمثل \\( \mathbf{R}_{\theta, i - j} \\) مصفوفة دورانية. \\( \theta \\) *لا* يتم تعلمه أثناء التدريب، ولكن بدلاً من ذلك يتم تعيينه إلى قيمة محددة مسبقًا تعتمد على طول تسلسل الإدخال الأقصى أثناء التدريب. + +> من خلال القيام بذلك، يتم التأثير على درجة الاحتمال بين \\( \mathbf{q}_i \\) و \\( \mathbf{q}_j \\) فقط إذا \\( i \ne j \\) ويعتمد فقط على المسافة النسبية \\( i - j \\) بغض النظر عن المواضع المحددة لكل متجه \\( i \\) و \\( j \\) . + +يستخدم *RoPE* في العديد من نماذج اللغة الكبيرة الأكثر أهمية اليوم، مثل: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**Llama**](https://arxiv.org/abs/2302.13971) +- [**PaLM**](https://arxiv.org/abs/2204.02311) + +كبديل، يقترح *ALiBi* مخطط ترميز موضعي نسبي أبسط بكثير. يتم إضافة المسافة النسبية التي تمتلكها رموز المدخلات إلى بعضها البعض كعدد صحيح سلبي مقياس بقيمة محددة مسبقًا `m` إلى كل إدخال استعلام-مفتاح لمصفوفة \\( \mathbf{QK}^T \\) مباشرة قبل حساب softmax. + +![](/blog/assets/163_optimize_llm/alibi.png) + +كما هو موضح في ورقة [ALiBi](https://arxiv.org/abs/2108.12409)، يسمح هذا الترميز الموضعي النسبي البسيط للنموذج بالحفاظ على أداء عالٍ حتى في تسلسلات المدخلات النصية الطويلة جدًا. + +يُستخدم *ALiBi* في العديد من أهم نماذج اللغة الكبيرة المستخدمة اليوم، مثل: + +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +يمكن لكل من ترميزات الموضع *RoPE* و *ALiBi* الاستقراء إلى أطوال إدخال لم يتم ملاحظتها أثناء التدريب، في حين ثبت أن الاستقراء يعمل بشكل أفضل بكثير خارج الصندوق لـ *ALiBi* مقارنة بـ *RoPE*. +بالنسبة لـ ALiBi، ما عليك سوى زيادة قيم مصفوفة الموضع المثلث السفلي لمطابقة طول تسلسل الإدخال. +بالنسبة لـ *RoPE*، يؤدي الحفاظ على نفس \\( \theta \\) الذي تم استخدامه أثناء التدريب إلى نتائج سيئة عند تمرير إدخالات نصية أطول بكثير من تلك التي شوهدت أثناء التدريب، راجع [Press et al.](https://arxiv.org/abs/2108.12409). ومع ذلك، وجد المجتمع بعض الحيل الفعالة التي تقوم بتعديل \\( \theta \\)، مما يسمح لترميزات الموضع *RoPE* بالعمل بشكل جيد لتسلسلات إدخال النص المستقرئة (راجع [هنا](https://github.com/huggingface/transformers/pull/24653)). + +> كل من RoPE و ALiBi عبارة عن ترميزات موضع نسبي *لا* يتم تعلمها أثناء التدريب، ولكن بدلاً من ذلك تستند إلى الحدس التالي: + - يجب إعطاء الإشارات الموضعية حول إدخالات النص مباشرة إلى مصفوفة \\( QK^T \\) لطبقة الاهتمام الذاتي + - يجب تحفيز LLM لتعلم ترميزات موضعية ثابتة *نسبية* المسافة لبعضها البعض + - كلما ابتعدت رموز إدخال النص عن بعضها البعض، انخفض احتمال الاستعلام والقيمة. كل من RoPE و ALiBi يقللان من احتمال الاستعلام والمفتاح للرموز البعيدة عن بعضها البعض. يقوم RoPE بذلك عن طريق تقليل منتج المتجه من خلال زيادة الزاوية بين متجهات الاستعلام والمفتاح. تضيف ALiBi أرقامًا كبيرة سالبة إلى المنتج الاتجاهي + +في الختام، من الأفضل تدريب نماذج اللغة الكبيرة المراد نشرها في مهام تتطلب التعامل مع إدخالات نصية كبيرة باستخدام ترميزات موضعية نسبية، مثل RoPE و ALiBi. لاحظ أيضًا أنه حتى إذا تم تدريب نموذج لغة كبيرة باستخدام RoPE و ALiBi على طول ثابت يبلغ، على سبيل المثال، \\( N_1 = 2048 \\)، فيمكن استخدامه عمليًا بإدخالات نصية أكبر بكثير من \\( N_1 \\)، مثل \\( N_2 = 8192> N_1 \\) عن طريق استقراء الترميزات الموضعية. + +### 3.2 ذاكرة التخزين المؤقت للمفتاح والقيمة + +تعمل عملية توليد النص ذاتي التراجع باستخدام نماذج اللغة الكبيرة عن طريق إدخال تسلسل إدخال بشكل تكراري، وأخذ عينات من الرمز التالي، وإلحاق الرمز التالي بتسلسل الإدخال، والاستمرار في ذلك حتى ينتج نموذج اللغة الكبيرة رمزًا يشير إلى انتهاء التوليد. + +يرجى الاطلاع على [دليل إنشاء النص الخاص بـ Transformer](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) للحصول على شرح مرئي أفضل لكيفية عمل التوليد ذاتي التراجع. + +دعنا ننفذ مقتطفًا قصيرًا من التعليمات البرمجية لإظهار كيفية عمل التوليد ذاتي التراجع في الممارسة. ببساطة، سنأخذ الرمز الأكثر احتمالًا عبر `torch.argmax`. + +```python +input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits = model(input_ids)["logits"][:, -1:] + next_token_id = torch.argmax(next_logits,dim=-1) + + input_ids = torch.cat([input_ids, next_token_id], dim=-1) + print("shape of input_ids", input_ids.shape) + +generated_text = tokenizer.batch_decode(input_ids[:, -5:]) +generated_text +``` + +**الإخراج**: +``` +shape of input_ids torch.Size([1, 21]) +shape of input_ids torch.Size([1, 22]) +shape of input_ids torch.Size([1, 23]) +shape of input_ids torch.Size([1, 24]) +shape of input_ids torch.Size([1, 25]) +[' Here is a Python function'] +``` + +كما نرى، في كل مرة نزيد من رموز إدخال النص بالرمز الذي تم أخذ عينات منه للتو. + +باستثناءات قليلة جدًا، يتم تدريب نماذج اللغة الكبيرة باستخدام [هدف نمذجة اللغة السببية](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) وبالتالي يتم قناع المثلث العلوي لمصفوفة نتيجة الاهتمام - وهذا هو السبب في ترك نتائج الاهتمام فارغة (*أي لها احتمال 0*) في المخططين أعلاه. للحصول على ملخص سريع حول نمذجة اللغة السببية، يمكنك الرجوع إلى مدونة [*Illustrated Self Attention*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention). + +ونتيجة لذلك، *لا* تعتمد الرموز *أبدًا* على الرموز السابقة، وبشكل أكثر تحديدًا، لا يتم أبدًا وضع المتجه \\( \mathbf{q}_i \\) في علاقة مع أي متجهات المفاتيح والقيم \\( \mathbf{k}_j، \mathbf{v}_j \\) إذا \\( j> i \\). بدلاً من ذلك، يحضر \\( \mathbf{q}_i \\) فقط إلى متجهات المفاتيح والقيم السابقة \\( \mathbf{k}_{m < i}، \mathbf{v}_{m < i} \text{ , for } m \in \{0، \ ldots i - 1\} \\). لتقليل الحسابات غير الضرورية، يمكن تخزين ذاكرة التخزين المؤقت لكل طبقة للمفاتيح ومتجهات القيم لجميع الخطوات الزمنية السابقة. + +فيما يلي، سنطلب من نموذج اللغة الكبيرة استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم عن طريق استردادها وإرسالها لكل عملية توجيه. +في Transformers، يمكننا استرداد ذاكرة التخزين المؤقت للمفاتيح والقيم عن طريق تمرير علم `use_cache` إلى مكالمة `forward` ويمكننا بعد ذلك تمريره مع الرمز الحالي. + +```python +past_key_values = None # past_key_values is the key-value cache +generated_tokens = [] +next_token_id = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits, past_key_values = model(next_token_id, past_key_values=past_key_values, use_cache=True).to_tuple() + next_logits = next_logits[:, -1:] + next_token_id = torch.argmax(next_logits, dim=-1) + + print("shape of input_ids", next_token_id.shape) + print("length of key-value cache", len(past_key_values[0][0])) # past_key_values are of shape [num_layers, 0 for k, 1 for v, batch_size, length, hidden_dim] + generated_tokens.append(next_token_id.item()) + +generated_text = tokenizer.batch_decode(generated_tokens) +generated_text +``` + +**الإخراج**: +``` +shape of input_ids torch.Size([1, 1]) +length of key-value cache 20 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 21 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 22 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 23 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 24 +[' Here', ' is', ' a', ' Python', ' function'] +``` + +كما هو موضح، عند استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم، لا يتم زيادة رموز إدخال النص في الطول، ولكنها تظل متجه إدخال واحدًا. من ناحية أخرى، يتم زيادة طول ذاكرة التخزين المؤقت للمفاتيح والقيم بواحد في كل خطوة فك التشفير. + +> يعني استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم أن \\( \mathbf{QK}^T \\) يتم تقليله بشكل أساسي إلى \\( \mathbf{q}_c\mathbf{K}^T \\) مع \\( \mathbf{q}_c \\) كونها إسقاط الاستعلام للرمز المدخل الحالي الذي يكون *دائمًا* مجرد متجه واحد. + +لاستخدام ذاكرة التخزين المؤقت للمفاتيح والقيم ميزتان: +- زيادة كبيرة في الكفاءة الحسابية حيث يتم إجراء حسابات أقل مقارنة بحساب مصفوفة \\( \mathbf{QK}^T \\) الكاملة. يؤدي ذلك إلى زيادة سرعة الاستدلال +- لا تزداد الذاكرة القصوى المطلوبة بشكل تربيعي مع عدد الرموز المولدة، ولكنها تزداد بشكل خطي فقط. + +> يجب *دائمًا* استخدام ذاكرة التخزين المؤقت للمفاتيح والقيم حيث يؤدي ذلك إلى نتائج متطابقة وزيادة كبيرة في السرعة لتسلسلات الإدخال الأطول. ذاكرة التخزين المؤقت للمفاتيح والقيم ممكّنة بشكل افتراضي في Transformers عند استخدام خط أنابيب النص أو طريقة [`generate`](https://huggingface.co/docs/transformers/main_classes/text_generation). + + + + +لاحظ أنه على الرغم من نصيحتنا باستخدام ذاكرة التخزين المؤقت للمفاتيح والقيم، فقد يكون إخراج نموذج اللغة الكبيرة مختلفًا قليلاً عند استخدامها. هذه خاصية نوى ضرب المصفوفة نفسها - يمكنك قراءة المزيد عنها [هنا](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535). + + + +#### 3.2.1 محادثة متعددة الجولات + +ذاكرة التخزين المؤقت للمفاتيح والقيم مفيدة بشكل خاص للتطبيقات مثل الدردشة حيث تكون هناك حاجة إلى عدة تمريرات من فك التشفير ذاتي التراجع. دعنا نلقي نظرة على مثال. + +``` +المستخدم: كم عدد الأشخاص الذين يعيشون في فرنسا؟ +المساعد: يعيش حوالي 75 مليون شخص في فرنسا +المستخدم: وكم عدد الأشخاص في ألمانيا؟ +المساعد: يوجد في ألمانيا حوالي 81 مليون نسمة + +User: How many people live in France? +Assistant: Roughly 75 million people live in France +User: And how many are in Germany? +Assistant: Germany has ca. 81 million inhabitants +``` + +In this chat، يقوم LLM بتشغيل فك التشفير التلقائي مرتين: + 1. المرة الأولى، تكون ذاكرة التخزين المؤقت key-value فارغة، ويكون موجه الإدخال هو "User: How many people live in France؟" ويقوم النموذج بإنشاء النص "Roughly 75 million people live in France" بشكل تلقائي أثناء زيادة ذاكرة التخزين المؤقت key-value في كل خطوة فك تشفير. + 2. في المرة الثانية، يكون موجه الإدخال هو "User: How many people live in France؟ \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany؟". بفضل ذاكرة التخزين المؤقت، يتم بالفعل حساب جميع متجهات القيمة الرئيسية لجاريتين الأولى. لذلك يتكون موجه الإدخال فقط من "User: And how many in Germany؟". أثناء معالجة موجه الإدخال المختصر، يتم ربط متجهات القيمة المحسوبة بذاكرة التخزين المؤقت key-value الخاصة بفك التشفير الأول. يتم بعد ذلك إنشاء إجابة المساعد الثانية "Germany has ca. 81 million inhabitants" بشكل تلقائي باستخدام ذاكرة التخزين المؤقت key-value المكونة من متجهات القيمة المشفرة لـ "User: How many people live in France؟ \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany؟". + +يجب ملاحظة أمرين هنا: + 1. الحفاظ على كل السياق أمر بالغ الأهمية للنماذج اللغوية الكبيرة (LLMs) التي يتم نشرها في الدردشة بحيث يفهم LLM كل سياق المحادثة السابق. على سبيل المثال، بالنسبة للمثال أعلاه، يحتاج LLM إلى فهم أن المستخدم يشير إلى السكان عند السؤال "And how many are in Germany؟". + 2. ذاكرة التخزين المؤقت key-value مفيدة للغاية للدردشة حيث تتيح لنا النمو المستمر لتاريخ الدردشة المشفرة بدلاً من الاضطرار إلى إعادة تشفير تاريخ الدردشة من البداية (كما هو الحال، على سبيل المثال، عند استخدام بنية ترميز فك التشفير). + +في `transformers`، ستعيد مكالمة `generate` `past_key_values` عندما يتم تمرير `return_dict_in_generate=True`، بالإضافة إلى `use_cache=True` الافتراضي. لاحظ أنه غير متوفر بعد من خلال واجهة `pipeline`. + +```python +# Generation as usual +prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here" +model_inputs = tokenizer(prompt، return_tensors='pt') +generation_output = model.generate(**model_inputs، max_new_tokens=60، return_dict_in_generate=True) +decoded_output = tokenizer.batch_decode(generation_output.sequences)[0] + +# Piping the returned `past_key_values` to speed up the next conversation round +prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here" +model_inputs = tokenizer(prompt، return_tensors='pt') +generation_output = model.generate( + **model_inputs، + past_key_values=generation_output.past_key_values، + max_new_tokens=60، + return_dict_in_generate=True +) +tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):] +``` + +**الإخراج**: +``` + هي نسخة معدلة من الدالة التي تعيد ميجا بايت بدلاً من ذلك. + +def bytes_to_megabytes(bytes): + return bytes / 1024 / 1024 + +Answer: The function takes a number of bytes as input and returns the number of +``` + +رائع، لا يتم إنفاق وقت إضافي على إعادة حساب نفس المفتاح والقيم لطبقة الاهتمام! ومع ذلك، هناك شيء واحد يجب ملاحظته. في حين أن ذروة الذاكرة المطلوبة لمصفوفة \\( \mathbf{QK}^T \\) يتم تقليلها بشكل كبير، فإن الاحتفاظ بذاكرة التخزين المؤقت key-value في الذاكرة يمكن أن يصبح مكلفًا جدًا من حيث الذاكرة لسلاسل الإدخال الطويلة أو الدردشة متعددة الجولات. تذكر أن ذاكرة التخزين المؤقت key-value بحاجة إلى تخزين متجهات القيمة الرئيسية لجميع متجهات الإدخال السابقة \\( \mathbf{x}_i \text{، لـ } i \in \{1، \ ldots، c - 1\} \\) لجميع طبقات الاهتمام الذاتي وكل رؤوس الاهتمام. + +دعنا نحسب عدد القيم العائمة التي يجب تخزينها في ذاكرة التخزين المؤقت key-value لنموذج LLM `bigcode/octocoder` الذي استخدمناه من قبل. +يبلغ عدد القيم العائمة ضعف طول التسلسل مضروبًا في عدد رؤوس الاهتمام مضروبًا في بعد رأس الاهتمام ومضروبًا في عدد الطبقات. +حساب هذا لنموذج LLM لدينا عند طول تسلسل افتراضي يبلغ 16000 يعطي: + +```python +config = model.config +2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head +``` + +**الإخراج**: +``` +7864320000 +``` + +Roughly 8 مليار قيمة عائمة! يتطلب تخزين 8 مليارات قيمة عائمة في دقة `float16` حوالي 15 جيجابايت من ذاكرة الوصول العشوائي (RAM) وهو ما يقرب من نصف حجم أوزان النموذج نفسها! +اقترح الباحثون طريقتين تسمحان بتقليل تكلفة الذاكرة لتخزين ذاكرة التخزين المؤقت key-value بشكل كبير، والتي يتم استكشافها في الأقسام الفرعية التالية. + +#### 3.2.2 Multi-Query-Attention (MQA) + +[Multi-Query-Attention](https://arxiv.org/abs/1911.02150) اقترحها Noam Shazeer في ورقته *Fast Transformer Decoding: One Write-Head is All You Need*. كما يقول العنوان، اكتشف Noam أنه بدلاً من استخدام `n_head` من أوزان إسقاط القيمة الرئيسية، يمكن استخدام زوج واحد من أوزان إسقاط رأس القيمة التي يتم مشاركتها عبر جميع رؤوس الاهتمام دون أن يتدهور أداء النموذج بشكل كبير. + +> باستخدام زوج واحد من أوزان إسقاط رأس القيمة، يجب أن تكون متجهات القيمة الرئيسية \\( \mathbf{k}_i، \mathbf{v}_i \\) متطابقة عبر جميع رؤوس الاهتمام والتي بدورها تعني أننا بحاجة فقط إلى تخزين زوج إسقاط قيمة رئيسي واحد في ذاكرة التخزين المؤقت بدلاً من `n_head` منها. + +نظرًا لأن معظم LLMs تستخدم ما بين 20 و100 رأس اهتمام، فإن MQA يقلل بشكل كبير من استهلاك الذاكرة لذاكرة التخزين المؤقت key-value. بالنسبة إلى LLM المستخدم في هذا الدفتر، يمكننا تقليل استهلاك الذاكرة المطلوبة من 15 جيجابايت إلى أقل من 400 ميجابايت عند طول تسلسل الإدخال 16000. + +بالإضافة إلى توفير الذاكرة، يؤدي MQA أيضًا إلى تحسين الكفاءة الحسابية كما هو موضح في ما يلي. +في فك التشفير التلقائي، يجب إعادة تحميل متجهات القيمة الرئيسية الكبيرة، ودمجها مع زوج متجه القيمة الحالي، ثم إدخالها في \\( \mathbf{q}_c\mathbf{K}^T \\) الحساب في كل خطوة. بالنسبة لفك التشفير التلقائي، يمكن أن تصبح عرض النطاق الترددي للذاكرة المطلوبة لإعادة التحميل المستمر عنق زجاجة زمنيًا خطيرًا. من خلال تقليل حجم متجهات القيمة الرئيسية، يجب الوصول إلى ذاكرة أقل، وبالتالي تقليل عنق الزجاجة في عرض النطاق الترددي للذاكرة. لمزيد من التفاصيل، يرجى إلقاء نظرة على [ورقة Noam](https://arxiv.org/abs/1911.02150). + +الجزء المهم الذي يجب فهمه هنا هو أن تقليل عدد رؤوس الاهتمام بالقيمة الرئيسية إلى 1 لا معنى له إلا إذا تم استخدام ذاكرة التخزين المؤقت للقيمة الرئيسية. يظل الاستهلاك الذروي لذاكرة النموذج لمرور واحد للأمام بدون ذاكرة التخزين المؤقت للقيمة الرئيسية دون تغيير لأن كل رأس اهتمام لا يزال لديه متجه استعلام فريد بحيث يكون لكل رأس اهتمام مصفوفة \\( \mathbf{QK}^T \\) مختلفة. + +شهدت MQA اعتمادًا واسع النطاق من قبل المجتمع ويتم استخدامها الآن بواسطة العديد من LLMs الأكثر شهرة: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**PaLM**](https://arxiv.org/abs/2204.02311) +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +كما يستخدم نقطة التحقق المستخدمة في هذا الدفتر - `bigcode/octocoder` - MQA. + +#### 3.2.3 مجموعة الاستعلام الاهتمام (GQA) + +[مجموعة الاستعلام الاهتمام](https://arxiv.org/abs/2305.13245)، كما اقترح Ainslie et al. من Google، وجد أن استخدام MQA يمكن أن يؤدي غالبًا إلى تدهور الجودة مقارنة باستخدام إسقاطات رأس القيمة الرئيسية المتعددة. تجادل الورقة بأنه يمكن الحفاظ على أداء النموذج بشكل أكبر عن طريق تقليل عدد أوزان إسقاط رأس الاستعلام بشكل أقل حدة. بدلاً من استخدام وزن إسقاط قيمة رئيسية واحدة فقط، يجب استخدام `n كخاتمة، من المستحسن بشدة استخدام GQA أو MQA إذا تم نشر LLM باستخدام فك التشفير التلقائي ويتطلب التعامل مع تسلسلات الإدخال الكبيرة كما هو الحال على سبيل المثال للدردشة. + + +## الخاتمة + +مجتمع البحث يأتي باستمرار بطرق جديدة ومبتكرة لتسريع وقت الاستدلال للنماذج اللغوية الكبيرة على الإطلاق. كمثال، أحد اتجاهات البحث الواعدة هو [فك التشفير التخميني](https://arxiv.org/abs/2211.17192) حيث تقوم "الرموز السهلة" بإنشائها نماذج اللغة الأصغر والأسرع ويتم إنشاء "الرموز الصعبة" فقط بواسطة LLM نفسه. إن التعمق في التفاصيل يتجاوز نطاق هذا الدفتر، ولكن يمكن قراءته في هذه [تدوينة المدونة اللطيفة](https://huggingface.co/blog/assisted-generation). + +السبب في أن LLMs الضخمة مثل GPT3/4، وLlama-2-70b، وClaude، وPaLM يمكن أن تعمل بسرعة كبيرة في واجهات الدردشة مثل [Hugging Face Chat](https://huggingface.co/chat/) أو ChatGPT يرجع إلى حد كبير إلى التحسينات المذكورة أعلاه في الدقة والخوارزميات والهندسة المعمارية. +في المستقبل، ستكون أجهزة التسريع مثل وحدات معالجة الرسومات (GPUs) ووحدات معالجة الرسومات (TPUs)، وما إلى ذلك... ستكون أسرع فقط وستسمح بمزيد من الذاكرة، ولكن يجب دائمًا التأكد من استخدام أفضل الخوارزميات والهندسة المعمارية المتاحة للحصول على أكبر قدر من المال diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_memory_anatomy.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_memory_anatomy.md new file mode 100644 index 0000000000000000000000000000000000000000..6fc2552321b79944d07bc0b35045654e0e8b3899 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_memory_anatomy.md @@ -0,0 +1,226 @@ +# تشريح عملية تدريب النموذج + +لفهم تقنيات تحسين الأداء التي يمكن تطبيقها لتحسين كفاءة استخدام الذاكرة وسرعة تدريب النموذج، من المفيد التعرف على كيفية استخدام وحدة معالجة الرسوميات (GPU) أثناء التدريب، وكيف تختلف كثافة العمليات الحسابية باختلاف العملية التي يتم تنفيذها. + +لنبدأ باستكشاف مثال توضيحي على استخدام وحدة GPU وتشغيل تدريب نموذج. وللتوضيح، سنحتاج إلى تثبيت بعض المكتبات: + +```bash +pip install transformers datasets accelerate nvidia-ml-py3 +``` + +تتيح مكتبة `nvidia-ml-py3` إمكانية مراقبة استخدام الذاكرة في النماذج من داخل بايثون. قد تكون على دراية بأمر `nvidia-smi` في الجهاز - تسمح هذه المكتبة بالوصول إلى نفس المعلومات مباشرة في بايثون. + +ثم، نقوم بإنشاء بعض البيانات الوهمية:معرّفات رموز عشوائية بين 100 و30000 وتصنيفات ثنائية للمصنف. + +في المجموع، نحصل على 512 تسلسلًا، لكل منها طول 512، ونخزنها في [`~datasets.Dataset`] بتنسيق PyTorch. + +```py +>>> import numpy as np +>>> from datasets import Dataset + +>>> seq_len, dataset_size = 512, 512 +>>> dummy_data = { +... "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)), +... "labels": np.random.randint(0, 1, (dataset_size)), +... } +>>> ds = Dataset.from_dict(dummy_data) +>>> ds.set_format("pt") +``` + +لطباعة إحصائيات موجزة لاستخدام وحدة GPU وتشغيل التدريب مع [`Trainer`]، نقوم بتعريف دالتين مساعدتين: + +```py +>>> from pynvml import * + +>>> def print_gpu_utilization(): +... nvmlInit() +... handle = nvmlDeviceGetHandleByIndex(0) +... info = nvmlDeviceGetMemoryInfo(handle) +... print(f"GPU memory occupied: {info.used//1024**2} MB.") + +>>> def print_summary(result): +... print(f"Time: {result.metrics['train_runtime']:.2f}") +... print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}") +... print_gpu_utilization() +``` + +دعنا نتأكد من أننا نبدأ بذاكرة وحدة GPU خالية: + +```py +>>> print_gpu_utilization() +GPU memory occupied: 0 MB. +``` + +يبدو ذلك جيدًا: لم يتم شغل ذاكرة وحدة معالجة الرسومات كما نتوقع قبل تحميل أي نماذج. إذا لم يكن الأمر كذلك على جهازك، فتأكد من إيقاف جميع العمليات التي تستخدم ذاكرة وحدة GPU. ومع ذلك، لا يمكن للمستخدم استخدام كل ذاكرة وحدة GPU الفارغة. عندما يتم تحميل نموذج إلى وحدة GPU، يتم أيضًا تحميل النواة، والتي يمكن أن تستهلك 1-2 جيجابايت من الذاكرة. ولرؤية مقدار ذلك، نقوم بتحميل مصفوفة صغيرة إلى وحدة GPU والتي تؤدي إلى تحميل النواة أيضًا. + +```py +>>> import torch + +>>> torch.ones((1, 1)).to("cuda") +>>> print_gpu_utilization() +GPU memory occupied: 1343 MB. +``` + +نلاحظ أن النواة وحدها تستهلك 1.3 جيجابايت من ذاكرة وحدة GPU. الآن دعنا نرى مقدار المساحة التي يستخدمها النموذج. + +## تحميل النموذج + +أولاً، نقوم بتحميل نموذج `google-bert/bert-large-uncased`. نقوم بتحميل أوزان النموذج مباشرة إلى وحدة GPU حتى نتمكن من التحقق من مقدار المساحة التي تستخدمها الأوزان فقط. + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda") +>>> print_gpu_utilization() +GPU memory occupied: 2631 MB. +``` + +يمكننا أن نرى أن أوزان النموذج وحدها تستهلك 1.3 جيجابايت من ذاكرة وحدة GPU. يعتمد الرقم الدقيق على وحدة GPU المحددة التي تستخدمها. لاحظ أنه في وحدات GPU الأحدث، قد يستغرق النموذج في بعض الأحيان مساحة أكبر نظرًا لأن الأوزان يتم تحميلها بطريقة مُحسّنة تُسرّع من استخدام النموذج. الآن يمكننا أيضًا التحقق بسرعة مما إذا كنا نحصل على نفس النتيجة كما هو الحال مع `nvidia-smi` CLI: + +```bash +nvidia-smi +``` + +```bash +Tue Jan 11 08:58:05 2022 ++-----------------------------------------------------------------------------+ +| NVIDIA-SMI 460.91.03 Driver Version: 460.91.03 CUDA Version: 11.2 | +|-------------------------------+----------------------+----------------------+ +| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | +| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | +| | | MIG M. | +|===============================+======================+======================| +| 0 Tesla V100-SXM2... On | 00000000:00:04.0 Off | 0 | +| N/A 37C P0 39W / 300W | 2631MiB / 16160MiB | 0% Default | +| | | N/A | ++-------------------------------+----------------------+----------------------+ + ++-----------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=============================================================================| +| 0 N/A N/A 3721 C ...nvs/codeparrot/bin/python 2629MiB | ++-----------------------------------------------------------------------------+ +``` + +نحصل على نفس الرقم كما كان من قبل، ويمكنك أيضًا أن ترى أننا نستخدم GPU من طراز V100 مع 16 جيجابايت من الذاكرة. لذا الآن يمكننا بدء تدريب النموذج ورؤية كيف يتغير استخدام ذاكرة GPU. أولاً، نقوم بإعداد بعض معاملات التدريب القياسية: + +```py +default_args = { + "output_dir": "tmp"، + "eval_strategy": "steps"، + "num_train_epochs": 1، + "log_level": "error"، + "report_to": "none"، +} +``` + + + + إذا كنت تخطط لتشغيل عدة تجارب، من أجل مسح الذاكرة بشكل صحيح بين التجارب، قم بإعادة تشغيل نواة Python بين التجارب. + + + +## استخدام الذاكرة في التدريب الأساسي + +دعونا نستخدم [`Trainer`] وقم بتدريب النموذج دون استخدام أي تقنيات تحسين أداء GPU وحجم دفعة يبلغ 4: + +```py +>>> from transformers import TrainingArguments، Trainer، logging + +>>> logging.set_verbosity_error() + + +>>> training_args = TrainingArguments(per_device_train_batch_size=4، **default_args) +>>> trainer = Trainer(model=model، args=training_args، train_dataset=ds) +>>> result = trainer.train() +>>> print_summary(result) +``` + +``` +الوقت: 57.82 +العينات / الثانية: 8.86 +ذاكرة GPU المشغولة: 14949 ميجابايت. +``` + +يمكننا أن نرى أن حجم دفعة صغير نسبيًا يملأ تقريبًا ذاكرة GPU بالكامل. ومع ذلك، غالبًا ما يؤدي حجم دفعة أكبر في تقارب نموذج أسرع أو أداء أفضل في النهاية. لذلك نريد أن نضبط حجم الدفعة وفقًا لاحتياجات النموذج لدينا وليس مع قيود وحدة GPU. ما يثير الاهتمام هو أننا نستخدم ذاكرة أكثر بكثير من حجم النموذج. +لفهم سبب ذلك بشكل أفضل، دعنا نلقي نظرة على عمليات النموذج واحتياجاته من الذاكرة. + +## تشريح عمليات النموذج + +تتضمن بنية المحولات 3 مجموعات رئيسية من العمليات مُجمعة أدناه حسب كثافة العمليات الحسابية. + +1. **عمليات ضرب المصفوفات** + + تقوم الطبقات الخطية ومكونات الانتباه متعدد الرؤوس جميعها بعمليات ضرب ** المصفوفة بالمصفوفة** على دفعات. هذه العمليات هي أكثر أجزاء تدريب المحولات كثافة من الناحية الحسابية. + +2. **عمليات التسوية الإحصائية** + +تُعد عمليات Softmax والتسوية الطبقية أقل كثافة من ناحية الحسابية من عمليات ضرب المصفوفات، وتنطوي على عملية أو أكثر من عمليات **الاختزال**، والتي يتم تطبيق نتيجتها بعد ذلك عبر خريطة. + +3. **العمليات على مستوى العناصر** + + هذه هي العمليات المتبقية: **الانحيازات، والتسرب، ووظائف التنشيط، والوصلات المتبقية**. هذه هي عمليات أقل كثافة من الناحية الحسابية. + +يمكن أن تكون هذه المعرفة مفيدة لمعرفة عند تحليل اختناقات الأداء. + +هذا الملخص مُشتق من [نقل البيانات هو كل ما تحتاجه: دراسة حالة حول تحسين المحولات 2020](https://arxiv.org/abs/2007.00072) + + +## تشريح ذاكرة النموذج + +لقد رأينا أن تدريب النموذج يستخدم ذاكرة أكثر بكثير من مجرد وضع النموذج على GPU. ويرجع ذلك إلى +هناك العديد من المكونات أثناء التدريب التي تستخدم ذاكرة GPU. المكونات الموجودة في ذاكرة GPU هي التالية: + +1. أوزان النموذج +2. الدول المُحسّن +3. المُتدرجات +4. تنشيطات المسار الأمامي المحفوظة لحساب المُتدرجات +5. المخازن المؤقتة +6. ذاكرة محددة الوظائف + +يتطلب نموذج نموذجي مدرب بدقة مختلطة 18 بايت للمُحسّن AdamW كل معلمة نموذج بالإضافة إلى ذاكرة التنشيط. للاستدلال لا توجد حالات مُحسّن و مُتدرجات، لذلك يمكننا طرح تلك. وهكذا ننتهي مع 6 بايت لكل +معلمة نموذج للدقة المختلطة الاستدلال، بالإضافة إلى ذاكرة التنشيط. + +دعنا نلقي نظرة على التفاصيل. + +**أوزان النموذج:** + +- 4 بايت * عدد المعلمات للتدريب على دقة fp32 +- 6 بايت * عدد المعلمات لتدريب الدقة المختلطة (يحافظ على نموذج في fp32 وآخر بدقة fp16 في الذاكرة) + +**حالات المُحسّن:** + +- 8 بايت * عدد المعلمات للمُحسّن AdamW العادي (يحافظ على حالتين) +- 2 بايت * عدد المعلمات لمُحسّنات 8 بت AdamW مثل [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) +- 4 بايت * عدد المعلمات لمُحسّنات مثل SGD مع الزخم momentum (يحافظ على حالة واحدة فقط) + +**المُتدرجات** + +- 4 بايت * عدد المعلمات للتدريب بدقة fp32 أو بدقة مختلطة (المُتدرجات تكون دائمًا بدقة fp32) + +**تنشيطات المسار الأمامي** + +- يعتمد الحجم على العديد من العوامل، وأهمها طول التسلسل وحجم المخفية وحجم الدُفعة. + +هناك المدخلات والمخرجات لذي يتم تمريرها وإرجاعها بواسطة وظائف المسار الأمامي والمسار الخلفي وتنشيطات المسار الأمامي المحفوظة لحساب المُتدرجات. + +**الذاكرة المؤقتة** + +بالإضافة إلى ذلك، هناك جميع أنواع المتغيرات المؤقتة التي يتم تحريرها بمجرد الانتهاء من الحساب، ولكن في +لحظة يمكن أن تتطلب هذه المتغيرات المؤقتة ذاكرة إضافية ويقد تؤدي إلى نفاد الذاكرة المُخصصة (OOM). لذلك، عند البرمجة، من المهم التفكير بشكل استراتيجي حول هذه المتغيرات المؤقتة وأحيانًا تحريرها بشكل صريح بمجرد عدم الحاجة إليها. + +**ذاكرة محددة الوظائف** + +ثم، قد يكون لبرنامجك احتياجات خاصة بالذاكرة. على سبيل المثال، عند إنشاء نص باستخدام البحث الشعاعي، يحتاج البرنامج +إلى الاحتفاظ بنسخ متعددة من المدخلات والمخرجات. + +**سرعة تنفيذ `forward` مقابل `backward`** + +بالنسبة للالتفافات والطبقات الخطية، هناك ضِعف عدد العمليات 2x flops في المسار الخلفى مقارنة بالمسار الأمامي، والتي يُترجم عمومًا إلى ~2x أبطأ (أحيانًا أكثر، لأن الأحجام في المسار الخلفى تميل إلى أن تكون أكثر صعوبة). عادةً ما تكون عمليات التنشيط محدودة بعرض النطاق الترددي، ومن المعتاد أن يتعين على التنشيط قراءة المزيد من البيانات في المسار الخلفى أكثر من المسار الأمامى. +(على سبيل المثال، قراءة التنشيط المسار الأمامى مرة واحدة، وتكتب مرة واحدة، وبينما تقرأ عملية التنشيط الخلفي مرتين، gradOutput وإخراج الأمام، وتكتب مرة واحدة، gradInput). + +كما ترى، هناك بضعة أماكن يمكننا فيها توفير ذاكرة GPU أو تسريع العمليات. +الآن بعد أن فهمت ما يؤثر على استخدام GPU وسرعة الحساب، راجع +صفحة وثائق [أساليب وأدوات التدريب الفعال على GPU واحد](perf_train_gpu_one) لمعرفة المزيد حول تقنيات تحسين الأداء. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_sharing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..b802eb3ef038f0bb853599307479e6efb9d6e618 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_sharing.md @@ -0,0 +1,223 @@ +# شارك نموذجك مع العالم + +أظهرت آخر درسين تعليميين كيفية ضبط نموذج بدقة باستخدام PyTorch و Keras و 🤗 Accelerate لعمليات التهيئة الموزعة. والخطوة التالية هي مشاركة نموذجك مع المجتمع! في Hugging Face، نؤمن بالمشاركة المفتوحة للمعرفة والموارد لتمكين الجميع من الاستفادة من الذكاء الاصطناعي. ونشجعك على مشاركة نموذجك مع المجتمع لمساعدة الآخرين على توفير الوقت والموارد. + +في هذا الدرس، ستتعلم طريقتين لمشاركة نموذجك المدرب أو مضبوط على منصة [Model Hub](https://huggingface.co/models): + +- رفع ملفاتك إلى منصة Hub مباشرة باستخدام الكود البرمجي. + +- قم بسحب وإفلات ملفاتك إلى Hub باستخدام الواجهة web. + + + + + +لمشاركة نموذج مع المجتمع، تحتاج إلى حساب على [huggingface.co](https://huggingface.co/join). يمكنك أيضًا الانضمام إلى منظمة موجودة أو إنشاء منظمة جديدة. + + + +## ميزات المستودع + +يعمل كل مستودع على Model Hub مثل مستودع GitHub النتقليدي. تقدم مستودعاتنا التحكم في الإصدارات وسجل التغييرات، وقدرة على رؤية الاختلافات بين الإصدارات. + +تعتمد آلية التحكم في الإصدارات على منصة Model Hub على نظامي git و [git-lfs](https://git-lfs.github.com/). وبعبارة أخرى، يمكنك التعامل مع كل نموذج كأنه مستودع مستقل، مما يمكّن من زيادة التحكم في الوصول والقابلية للتطوير. يسمح التحكم في الإصدار بإجراء تعديلات وتثبيت إصدار محدد من النموذج باستخدام رمز التغيير (commit hash) أو وسم (tag) أو فرع (branch). + +بفضل هذه الميزة، يمكنك تحميل إصدار محدد من النموذج باستخدام معلمة الإصدار "revision": + +```py +>>> model = AutoModel.from_pretrained( +... "julien-c/EsperBERTo-small", revision="4c77982" # اسم العلامة، أو اسم الفرع، أو تجزئة الالتزام +... ) +``` + +من السهل أيضًا تعديل الملفات الموجودة داخل مستودع، ويمكنك عرض سجل التغييرات التي طرأت على هذه الملفات ومعاينة الاختلافات بين الإصدارات المختلفة: + +![vis_diff](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vis_diff.png) + +## الإعداد + +قبل مشاركة نموذج على Hub، ستحتاج إلى بيانات اعتماد حساب Hugging Face الخاصة بك. إذا كنت تستخدم منصة الأوامر، فقم بتشغيل الأمر التالي في بيئة افتراضية حيث تم تثبيت 🤗 Transformers. سيقوم هذا الأمر بتخزين رمز الدخول الخاص بك في مجلد تخزين المؤقت لـ Hugging Face (`~/.cache/` بشكل افتراضي): + +```bash +huggingface-cli login +``` + +إذا كنت تستخدم دفتر ملاحظات مثل Jupyter أو Colaboratory، فتأكد من تثبيت مكتبة [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library). تسمح لك هذه المكتبة بالتفاعل برمجيًا مع Hub. + +```bash +pip install huggingface_hub +``` + +ثم استخدم `notebook_login` لتسجيل الدخول إلى Hub، واتبع الرابط [هنا](https://huggingface.co/settings/token) لإنشاء رمز للتسجيل: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + + +## تحويل النموذج ليتوافق مع جميع الأطر العمل + +لضمان إمكانية استخدام نموذجك من قبل شخص يعمل بإطار عمل مختلف، نوصي بتحويل نموذجك ورفعه مع نقاط التحقق من PyTorch و TensorFlow. في حين أن المستخدمين لا يزال بإمكانهم تحميل نموذجك من إطار عمل مختلف إذا تخطيت هذه الخطوة، إلا أنه سيكون أبطأ لأن 🤗 Transformers ستحتاج إلى تحويل نقطة التحقق أثناء التشغيل. + +تحويل نقطة التحقق لإطار عمل آخر أمر سهل. تأكد من تثبيت PyTorch و TensorFlow (راجع [هنا](installation) لتعليمات التثبيت)، ثم ابحث عن النموذج الملائم لمهمتك في الإطار الآخر. + + + +حدد `from_tf=True` لتحويل نقطة تحقق من TensorFlow إلى PyTorch: + +```py +>>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True) +>>> pt_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +حدد `from_pt=True` لتحويل نقطة تحقق من PyTorch إلى TensorFlow: + +```py +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True) +``` + +بعد ذلك، يمكنك حفظ نموذج TensorFlow الجديد بنقطة التحقق الجديدة: + +```py +>>> tf_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +إذا كان النموذج متاحًا في Flax، فيمكنك أيضًا تحويل نقطة تحقق من PyTorch إلى Flax: + +```py +>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained( +... "path/to/awesome-name-you-picked", from_pt=True +... ) +``` + + + +## دفع نموذج أثناء التدريب + + + + + +مشاركة نموذجك على Hub مر بسيط للغاية كل ما عليك هو إضافة معلمة أو استدعاء رد إضافي. كما تذكر من درس [التدريب الدقيق](training)، فإن فئة [`TrainingArguments`] هي المكان الذي تحدد فيه المعلمات الفائقة وخيارات التدريب الإضافية. تشمل إحدى خيارات التدريب هذه القدرة على دفع النموذج مباشرة إلى المنصة Hub. قم بتعيين `push_to_hub=True` في [`TrainingArguments`]: + +```py +>>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True) +``` + +مرر معامﻻت التدريب كالمعتاد إلى [`Trainer`]: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +بعد ضبط نموذجك بدقة، يمكنك استخدام دالة [`~transformers.Trainer.push_to_hub`] المتاحة في [`Trainer`] لدفع النموذج المدرب إلى المنصة Hub. سوف تضيف 🤗 Transformers تلقائيًا المعلمات الفائقة المستخدمة في التدريب ونتائج التدريب وإصدارات الإطار إلى بطاقة معلومات النموذج الخاصة بك! + +```py +>>> trainer.push_to_hub() +``` + + +شارك نموذجًا على Hub باستخدام [`PushToHubCallback`]. في دالة [`PushToHubCallback`], أضف: + +- دليل إخراج لنموذجك. +- مُجزّئ اللغوي. +- `hub_model_id`، والذي هو اسم مستخدم Hub واسم النموذج الخاص بك. + +```py +>>> from transformers import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model" +... ) +``` + +أضف الاستدعاء إلى [`fit`](https://keras.io/api/models/model_training_apis/)، وسيقوم 🤗 Transformers بدفع النموذج المدرب إلى Hub: + +```py +>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback) +``` + + + +## استخدام دالة `push_to_hub` + +يمكنك أيضًا استدعاء `push_to_hub` مباشرة على نموذجك لتحميله إلى Hub. + +حدد اسم نموذجك في `push_to_hub`: + +```py +>>> pt_model.push_to_hub("my-awesome-model") +``` + +ينشئ هذا مستودعًا تحت اسم المستخدم الخاص بك باسم نموذج `my-awesome-model`. يمكن للمستخدمين الآن تحميل نموذجك باستخدام دالة `from_pretrained`: + +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` + +إذا كنت تنتمي إلى منظمة وتريد دفع نموذجك تحت اسم المنظمة بدلاً من ذلك، فما عليك سوى إضافته إلى `repo_id`: + +```py +>>> pt_model.push_to_hub("my-awesome-org/my-awesome-model") +``` + +يمكن أيضًا استخدام دالة `push_to_hub` لإضافة ملفات أخرى إلى مستودع النماذج. على سبيل المثال، أضف رموزًا إلى مستودع نموذج: + +```py +>>> tokenizer.push_to_hub("my-awesome-model") +``` + +أو ربما تريد إضافة إصدار TensorFlow من نموذج PyTorch المضبوط: + +```py +>>> tf_model.push_to_hub("my-awesome-model") +``` + +الآن عند الانتقال إلى ملفك الشخصي على Hugging Face، يجب أن ترى مستودع النماذج الذي أنشأته حديثًا. سيؤدي النقر فوق علامة التبويب **Files** إلى عرض جميع الملفات التي قمت بتحميلها في المستودع. + +للحصول على مزيد من التفاصيل حول كيفية إنشاء الملفات وتحميلها إلى مستودع، راجع وثائق Hub [هنا](https://huggingface.co/docs/hub/how-to-upstream). + +## التحميل باستخدام الواجهة web + +يمكن للمستخدمين الذين يفضلون نهج عدم الترميز تحميل نموذج من خلال واجهة Hub web. قم بزيارة [huggingface.co/new](https://huggingface.co/new) لإنشاء مستودع جديد: + +![new_model_repo](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/new_model_repo.png) + +من هنا، أضف بعض المعلومات حول نموذجك: + +- حدد **مالك** المستودع. يمكن أن يكون هذا أنت أو أي من المنظمات التي تنتمي إليها. +- اختر اسمًا لنموذجك، والذي سيكون أيضًا اسم المستودع. +- اختر ما إذا كان نموذجك عامًا أم خاصًا. +- حدد ترخيص الاستخدام لنموذجك. + +الآن انقر فوق علامة التبويب **Files** ثم انقر فوق الزر **Add file** لإضافة ملف جديد إلى مستودعك. ثم اسحب وأسقط ملفًا لتحميله وأضف رسالة الالتزام. + +![upload_file](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/upload_file.png) + +## إضافة بطاقة نموذج + +للتأكد من فهم المستخدمين لقدرات نموذجك وقيوده وتحيزاته المحتملة واعتباراته الأخلاقية، يرجى إضافة بطاقة نموذج إلى مستودعك. يتم تعريف بطاقة النموذج في ملف `README.md`. يمكنك إضافة بطاقة نموذج عن طريق: + +* قم بإنشاء ملف `README.md` وتحميله يدويًا. +* انقر فوق الزر **Edit model card** في مستودع نموذجك. + +الق نظرة على بطاقة [DistilBert](https://huggingface.co/distilbert/distilbert-base-uncased) للحصول على مثال جيد على نوع المعلومات التي يجب أن تتضمنها بطاقة النموذج. للحصول على مزيد من التفاصيل حول الخيارات الأخرى التي يمكنك التحكم فيها في ملف `README.md` مثل البصمة الكربونية للنموذج أو أمثلة الأداة، راجع الوثائق [هنا](https://huggingface.co/docs/hub/models-cards). \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_summary.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..57de935b70f4597619786d5ced1906b5186d2284 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/model_summary.md @@ -0,0 +1,89 @@ +# عائلة نماذج المحول + +منذ إطلاقه في عام 2017، ألهم نموذج [المحول الأصلي](https://arxiv.org/abs/1706.03762) (راجع مدونة [المحول المشروح](http://nlp.seas.harvard.edu/2018/04/03/attention.html) لمقدمة تقنية مبسطة)، ألهم العديد من النماذج الجديدة والمبتكرة التي تتجاوز مهام معالجة اللغات الطبيعية (NLP). هناك نماذج للتنبؤ [بالبنية البروتينات المطوية](https://huggingface.co/blog/deep-learning-with-proteins)، و[تدريب على اتخاذ القرار](https://huggingface.co/blog/train-decision-transformers)، و[التنبؤ بالسلاسل الزمنية](https://huggingface.co/blog/time-series-transformers). مع وجود العديد من متغيرات المحول المتاحة، قد يكون من السهل أن تفوتك الصورة الأكبر. ما تشترك فيه جميع هذه النماذج هو أنها تستند إلى بنية المحول الأصلية. تستخدم بعض النماذج فقط الترميز أو فك الترميز، بينما تستخدم نماذج أخرى كليهما. يوفر هذا تصنيفًا مفيدًا لتصنيف واستعراض الفروقات الرئيسية بين نماذج عائلة المحولات، وسيساعدك على فهم النماذج التي لم تصادفها من قبل. + +إذا لم تكن على دراية بنموذج المحول الأصلي أو تحتاج إلى تذكير، فراجع الفصل الخاص بـ [كيف تعمل المحولات](https://huggingface.co/course/chapter1/4؟fw=pt) من دورة Hugging Face. + +
+ +
+ +## رؤية الحاسب (Computer vision) + + + +### الشبكة التلافيفية (Convolutional network) + +لطالما كانت الشبكات التلافيفية (CNNs) الطريقة السائدة لمهام رؤية الحاسب حتى برز [محول الرؤية](https://arxiv.org/abs/2010.11929) قابليته للتطوير وكفاءته العالية. وحتى بعد ذلك، لا تزال بعض أفضل صفات CNN، مثل ثبات الإزاحة، قوية جدًا (خاصة بالنسبة لمهام معينة) لدرجة أن بعض المحولات تدمج التلافيف في بنيتها. قلب [ConvNeXt](model_doc/convnext) هذا التبادل رأسًا على عقب وأدرج خيارات التصميم من المحولات لتحديث CNN. على سبيل المثال، يستخدم ConvNeXt نوافذ منزلقة غير متداخلة لتقسيم الصورة إلى رقع وزيادة حقل مجال العام الخاص بها. كما يقوم ConvNeXt بعدة خيارات مثل تصميم الطبقة لتكون أكثر كفاءة في الذاكرة وتحسين الأداء، مما يجعله منافسًا قويًا للمحولات! + +### الترميز[[cv-encoder]] (Encoder) + +فتح [محول الرؤية (ViT)](model_doc/vit) الباب أمام مهام رؤية الحاسب دون الاعتماد على التلافيف. يستخدم ViT ترميز محول قياسي، لكن إنجازه الرئيسي كان طريقة معالجته للصورة. فهو تقسّم الصورة إلى رقّعات ذات حجم ثابت ويستخدمها لإنشاء تضمين، تمامًا مثل تقسيم الجملة إلى رموز. استفاد ViT من بنية المُحوِّلات الفعالة لإظهار نتائج تنافسية مع CNNs في ذلك الوقت مع الحاجة إلى موارد أقل للتدريب. وسرعان ما تبع ViT نماذج رؤية أخرى يمكنها أيضًا التعامل مع مهام الرؤية الكثيفة مثل التجزئة والتعرف. + +من بين هذه النماذج [Swin](model_doc/swin) Transformer. فهو يبني خرائط سمات هرمية (مثل CNN 👀 على عكس ViT) من رقّعات أصغر حجمًا ودمجها مع الرقع المجاورة في طبقات أعمق. يتم حساب الانتباه فقط ضمن نافذة محلية، ويتم تحويل النافذة بين طبقات الانتباه لإنشاء اتصالات تساعد النموذج على التعلم بشكل أفضل. نظرًا لأن محول Swin يمكنه إنتاج خرائط خصائص هرمية، فهو مرشح جيد لمهام التنبؤ الكثيفة مثل التجزئة والتعرف. كما يستخدم [SegFormer](model_doc/segformer) ترميز محول لبناء خرائط خصائص هرمية، ولكنه يضيف فك تشفير بسيط متعدد الطبقات (MLP) في الأعلى لدمج جميع خرائط الخصائص وإجراء تنبؤ. + +استلهمت نماذج الرؤية الأخرى، مثل BeIT وViTMAE، الإلهام من هدف التدريب المسبق لـ BERT. يتم تدريب [BeIT](model_doc/beit) مسبقًا من خلال *نمذجة الصور المقنعة (MIM)*؛ يتم إخفاء رقّعات الصور بشكل عشوائي، كما يتم تحويل الصورة إلى رموز بصرية. يتم تدريب BeIT للتنبؤ بالرموز البصرية المُناظرة للرقع المخفية. لدى [ViTMAE](model_doc/vitmae) هدف تدريب مسبق مُماثل، باستثناء أنه يجب عليه التنبؤ بالبكسلات بدلاً من الرموز البصرية. ما هو غير عادي هو أن إخفاء 75% من رقع الصور! يقوم فك التشفير بإعادة بناء البكسلات من الرموز المخفية والرقّعات المشفرة. بعد التدريب المسبق، يتم التخلص من فك التشفير، ويصبح الترميز جاهزًا للاستخدام في مهام التالية. + +### فك التشفير[[cv-decoder]] (Decoder) + +نادرًا ما تستخدم نماذج الرؤية التي تعتمد على فك التشفير فقط لأن معظم نماذج الرؤية تعتمد على الترميز لتعلم تمثيل الصورة. ولكن بالنسبة للاستخدامات مثل توليد الصور، يعد فك التشفير مناسبًا بشكل طبيعي، كما رأينا من نماذج توليد النصوص مثل GPT-2. يستخدم نموذج [ImageGPT](model_doc/imagegpt) نفس بنية GPT-2، ولكنه بدلاً من التنبؤ بالرمز التالي في تسلسل، فإنه يتنبأ بالبكسل التالي في صورة. بالإضافة إلى توليد الصور، يمكن أيضًا ضبط ImageGPT بدقة لتصنيف الصور. + +### الترميز وفك التشفير[[cv-encoder-decoder]] (Encoder-decoder) + +تستخدم نماذج الرؤية بشكل شائع ترميزًا (يُعرف أيضًا باسم العمود الفقري) لاستخراج ميزات الصورة المهمة قبل تمريرها إلى فك التشفير لنموذج المُحوّل. يستخدم [DETR](model_doc/detr) عمودًا فقريًا مُدربًا مسبقًا، ولكنه يستخدم أيضًا الببنية الكاملة للترميز وفك تشفير لنموذج المحول للكشف عن الأشياء. يتعلم الترميز تمثيلات الصور ويجمعها مع استعلامات الكائنات (كل استعلام كائن هو تضمين مُتعلم يركز على منطقة أو كائن في صورة) في فك التشفير. يتنبأ DETR بإحداثيات مربع الحدود وتسمية الفئة لكل استعلام كائن. + +## معالجة اللغات الطبيعية (Natural language processing - NLP) + + + +### الترميز اللغوي[[nlp-encoder]] + +نموذج [BERT](model_doc/bert) هو محوّل (Transformer) يعتمد على الترميز فقط يقوم بشكل عشوائي بإخفاء رموز معينة في المدخلات لتجنب رؤية باقى الرموز الأخرى، مما يسمح له "بالغش". يتمثل هدف التدريب المسبق في التنبؤ بالرمز المخفي بناءً على السياق. يسمح هذا لـ BERT باستخدام السياقات اليمنى واليسرى بالكامل لمساعدته في تعلم تمثيل أعمق وأغنى للبيانات المدخلة. ومع ذلك، كان هناك مجال للتحسين في استراتيجية التدريب المسبق لـ BERT. نموذج [RoBERTa](model_doc/roberta) اضاف تحسين من خلال تقديم وصفة تدريب مسبق جديدة تشمل التدريب لفترة أطول وعلى دفعات أكبر، وإخفاء الرموز عشوائيًا في كل حقبة بدلاً من مرة واحدة فقط أثناء المعالجة المسبقة، وإزالة هدف التنبؤ بالجملة التالية. + +تتمثل الاستراتيجية السائدة لتحسين الأداء في زيادة حجم النموذج. ولكن تدريب النماذج الكبيرة مكلف من الناحية الحسابية. إحدى طرق تقليل التكاليف الحسابية هي استخدام نموذج أصغر مثل [DistilBERT](model_doc/distilbert). يستخدم DistilBERT [ تقنية تقطير المعرفة](https://arxiv.org/abs/1503.02531) - وهي تقنية ضغط - لإنشاء نموذج أصغر من BERT مع الحفاظ على معظم قدراته على فهم اللغةا. + +مرت معظم نماذج المحول في الاتجاه نحو المزيد من المعلمات، مما أدى إلى ظهور نماذج جديدة تركز على تحسين كفاءة التدريب. يقلّل [ALBERT](model_doc/albert) من استهلاك الذاكرة عن طريق تقليل عدد المعلمات بطريقتين: فصل تضمين المفردات الأكبر إلى مصفوفتين أصغر والسماح للمستويات بمشاركة المعلمات. أضاف [DeBERTa](model_doc/deberta) آلية انتباه منفصلة حيث يتم ترميز الكلمة وموضعها بشكل منفصل في متجهين. يتم حساب الانتباه من هذه المتجهات المنفصلة بدلاً من متجه واحد يحتوي على تضمين الكلمة والموقع. ركز [Longformer](model_doc/longformer) أيضًا على جعل الانتباه أكثر كفاءة، خاصة لمعالجة المستندات ذات تسلسلات أطولل. فهو يستخدم مزيجًا من انتباه النوافذ المحلية (يتم حساب الانتباه فقط ن نافذة ذات حجم ثابت حول كل رمز) والانتباه العام (فقط لرموز مهمة محددة مثل `[CLS]` للتصنيف) لإنشاء مصفوفة انتباه متفرقة بدلاً من مصفوفة انتباه كاملة. + +### فك التشفير[[nlp-decoder]] + + نموذج [GPT-2](model_doc/gpt2) هو محول فك تشفير فقط يتنبأ بالكلمة التالية في التسلسل. إنه يخفي الرموز التالية الموجودة على اليمين حتى لا يتمكن النموذج من "الغش" بالنظر إليها. من خلال التدريب المسبق على كميات هائلة من النصوص، أصبح [GPT-2](model_doc/gpt2) بارعًا في توليد النصوص، حتى لو لم تكن النص دقيقًا أو صحيحًا في بعض الأحيان فقط. ولكن كان يفتقر إلى سياق لترابط المتبادل (bidirectional context) الموجود من التدريب المسبق لـ [BERT](model_doc/bert) ، مما جعله غير مناسب لمهام معينة. يجمع [XLNET](model_doc/xlnet) بين أفضل ما في أهداف التدريب المسبق لـ [BERT](model_doc/bert) و [GPT-2](model_doc/gpt2) من خلال اعتماد نهج النمذجة اللغوية باستخدام التباديل (Permutation Language Modeling - PLM) الذي يسمح له بتعلم الترابط ثنائي الاتجاه. + +بعد ظهور [GPT-2](model_doc/gpt2)، تطورت النماذج اللغوية بشكل أكبر حجمًا وأكثر تعقيدًا وأصبحت تُعرف الآن باسم *نماذج اللغة الكبيرة (LLMs)*. توضح LLMs مهارات تعلم قليلة الكمية أو حتى معدومة إذا تم تدريبها على مجموعة بيانات كبيرة بما يكفي. [GPT-J](model_doc/gptj) هو LLM به 6 مليارات معلمة مدربة على 400 مليار رمز. تبعه نموذج [OPT](model_doc/opt)، وهي عائلة من نماذج فك التشفير فقط، أكبرها 175 مليار معلمة ودُرب على 180 مليار رمز. تم إصدار [BLOOM](model_doc/bloom) في نفس الوقت تقريبًا، ويحتوي أكبر نموذج في العائلة على 176 مليار معلمة ودُرب على 366 مليار رمز في 46 لغة و13 لغة برمجة. + +### الترميز وفك التشفير[[nlp-encoder-decoder]] + +يحتفظ [BART](model_doc/bart) ببنية المحول الأصلية، ولكنه يعدّل هدف التدريب المسبق باستخدام إفساد *إدخال النصوص*، حيث يتم استبدال بعض نطاقات النص برمز `mask` واحد. يتنبأ فك التشفير بالرموز غير الفاسدة (يتم إخفاء الرموز المستقبلية) ويستخدم حالات الترميز المخفية للمساعدة. [Pegasus](model_doc/pegasus) مشابه لـ BART، ولكن Pegasus يقوم بإخفاء جمل كاملة بدلاً من مقاطع النص. بالإضافة إلى نمذجة اللغة المقنعة، يتم تدريب Pegasus مسبقًا بواسطة توليد الجمل الفارغة (GSG). يقوم هدف GSG بإخفاء الجمل الكاملة المهمة للمستند، واستبدالها برمز `mask`. يجب على فك التشفير توليد المخرجات من الجمل المتبقية. [T5](model_doc/t5) هو نموذج فريد من نوعه يحوّل جميع مهام معالجة اللغة الطبيعية إلى مشكلة نص إلى نص باستخدام بادئات محددة. على سبيل المثال، يشير البادئة `Summarize:` إلى مهمة تلخيص. يتم تدريب T5 مسبقًا بواسطة التدريب الخاضع للإشراف (GLUE وSuperGLUE) والتدريب ذاتي الإشراف (اختيار عينة عشوائية وحذف 15% من الرموز). + +## الصوت (Audio) + + + +### الترميز[[audio-encoder]] + +يستخدم [Wav2Vec2](model_doc/wav2vec2) ترميز من نوع المحوّل لتعلم تمثيلات الكلام بشكلٍ مباشر من موجات الصوت الخام. يتم تدريبه مسبقًا باستخدام مهمة تباينية لتحديد تمثيل الكلام الصحيح من مجموعة من التمثيلات الخاطئة. [HuBERT](model_doc/hubert) مشابه لـ Wav2Vec2 ولكنه له عملية تدريب مختلفة. يتم إنشاء تسميات الهدف عن طريق خطوة تجميع يتم فيها ت تخصيص مقاطع الصوت المتشابهة إلى مجموعات، تُصبح كل واحدة منها وحدةً خفية. ويتم تعيين الوحدة الخفية إلى تمثيل لإجراء تنبؤ. + +### الترميز وفك التشفير[[audio-encoder-decoder]] + +[Speech2Text](model_doc/speech_to_text) هو نموذج كلام مصمم للتعرف التلقائي على الكلام (ASR) وترجمة الكلام. يقبل النموذج ميزات بنك المرشح اللغوي التي تم استخراجها من شكل موجة الصوت وتم تدريبه مسبقًا بطريقة ذاتية التعلم لتوليد نسخة أو ترجمة. [Whisper](model_doc/whisper) هو أيضًا نموذج ASR، ولكنه على عكس العديد من نماذج الكلام الأخرى، يتم تدريبه مسبقًا على كمية كبيرة من بيانات نسخ النص الصوتي ✨ المسماة ✨ لتحقيق الأداء الصفري. يحتوي جزء كبير من مجموعة البيانات أيضًا على لغات غير اللغة الإنجليزية، مما يعني أنه يمكن استخدام Whisper أيضًا للغات منخفضة الموارد. من الناحية الهيكلية، يشبه Whisper نموذج Speech2Text. يتم تحويل إشارة الصوت إلى طيف لوجاريتم مل-ميل يتم تشفيره بواسطة الترميز. يقوم فك التشفير بتوليد النسخة بطريقة ذاتية التعلم من حالات الترميز المخفية والرموز السابقة. + +## متعدد الوسائط (Multimodal) + + + +### Encoder[[mm-encoder]] + +نموذج [VisualBERT](model_doc/visual_bert) هو نموذج متعدد الوسائط لمهام الرؤية اللغوية تم إصداره بعد فترة وجيزة من BERT. فهو يجمع بين BERT ونظام اكتشاف كائن مسبق التدريب لاستخراج ميزات الصورة في تضمينات بصرية، يتم تمريرها جنبًا إلى جنب مع التضمينات النصية إلى BERT. يتنبأ VisualBERT بالنص المقنع بناءً على النص غير المقنع والتضمينات المرئية، ويجب عليه أيضًا التنبؤ بما إذا كان النص متوافقًا مع الصورة. عندما تم إصدار ViT، اعتمد [ViLT](model_doc/vilt) ViT في بنيتها لأنه كان من الأسهل الحصول على تضمينات الصورة بهذه الطريقة. يتم معالجة تضمينات الصورة بشكل مشترك مع التضمينات النصية. ومن هناك، يتم التدريب المسبق لـ ViLT بواسطة مطابقة الصورة النصية، ونمذجة اللغة المقنعة، وإخفاء كلمة كاملة. + +يتّبع [CLIP](model_doc/clip) نهجًا مختلفًا ويقوم بتنبؤ ثنائي من ("الصورة"، "النص"). يتم تدريب مشفر صورة (ViT) ومشفر نص (Transformer) بشكل مشترك على مجموعة بيانات مكونة من 400 مليون ثنائي من ("صورة"، "نص") لتعظيم التشابه بين متجهات ترميز الصورة ومتجهات النص ثنائي ("الصورة"، "النص"). بعد التدريب المسبق، يمكنك استخدام اللغة الطبيعية لتوجيه CLIP للتنبؤ بالنص المُعطى بناءً على صورة أو العكس بالعكس. [OWL-ViT](model_doc/owlvit) يبني على CLIP باستخدامه كعمود فقري للكشف عن الكائنات بدون إشراف. بعد التدريب المسبق، يتم إضافة رأس كشف الأجسام لإجراء تنبؤ بمجموعة مُحدّد عبر ثنائيات ("class"، "bounding box"). + +### Encoder-decoder[[mm-encoder-decoder]] + +التعرّف البصري على الحروف (OCR) مهمة قديمة لتعرّف النصوص، التي تنطوي عادةً على عدة مكونات لفهم الصورة وتوليد النص. [TrOCR](model_doc/trocr) بتبسيط العملية باستخدام محول متكامل من النهاية إلى النهاية. المشفر هو نموذج على غرار ViT لفهم الصورة ويعالج الصورة كقطع ثابتة الحجم. يقبل فك التشفير حالات الإخفاء للمشفر وينشئ النص بشكل تلقائي. [Donut](model_doc/donut) هو نموذج أكثر عمومية لفهم المستندات المرئية لا يعتمد على نهج OCR. يستخدم محول Swin كمشفر وBART متعدد اللغات كمُفكّك تشفير. يتم تدريب Donut على قراءة النص عن طريق التنبؤ بالكلمة التالية بناءً على ملاحظات الصورة والنص. يقوم فك التشفير بتوليد تتسلسلًا رمزيًا بناءً على موجه (Prompt). يتم تمثيل الموجه بواسطة رمز خاص لكل مهمة. على سبيل المثال، يحتوي تحليل المستند على رمز خاص "parsing" يتم دمجه مع حالات الإخفاء للـمُشفّر لتحليل المستند بتنسيق إخراج منظم (JSON). + +## التعلم التعزيزي (Reinforcement learning - RL) + + + +### فك التشفير[[rl-decoder]] + +يقوم نموذج "محوّل القرارات والمسارات" (Decision and Trajectory Transformer) بتحويل الحالة (State) والإجراء (Action) والمكافأة (Reward) كمشكلة نمذجة تسلسلية. [محوّل القرارات](model_doc/decision_transformer) يقوم بتوليد سلسلة من الإجراءات التي تؤدي إلى عائد مرغوب في المستقبل بناءً على العوائد المتوقعة، والحالات والإجراءات السابقة. في الخطوات الزمنية *K* الأخيرة، يتم تحويل كل وسائط البيانات الثلاث vإلى متجهات تضمين رمزيّة ومعالجتها بواسطة نموذج مشابه لـ GPT للتنبؤ برمز الإجراء المستقبلي.يقوم [محول المسار](model_doc/trajectory_transformer) أيضًا بتحويل الحالات والإجراءات والمكافآت إلى رموز ومعالجتها باستخدام هيكلية GPT. على عكس "محوّل القرارات"، الذي يركز على تكييف المكافأة، يقوم "محوّل المسارات" بتوليد إجراءات مستقبلية باستخدام البحث الشعاعي (Beam Search). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/modular_transformers.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/modular_transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..b500fec1c92d25efc0de93890c69cd9cafeefd67 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/modular_transformers.md @@ -0,0 +1,184 @@ +# المحولات النمطية + +مكتبة `transformers` هي إطار عمل ذو فلسفة محدد؛ يتم تعريف فلسفتنا في [الدليل المفاهيمي](./philosophy). + +جوهر هذه الفلسفة يتمثل في مبدأ [نموذج واحد، ملف واحد](https://huggingface.co/blog/transformers-design-philosophy) +في المكتبة. الجانب السلبي لهذا المكون هو تقييده لوراثة واستيراد مكونات الملفات. + +نتيجة لذلك، تتكرر مكونات النموذج عبر العديد من الملفات. يحتوي `transformers` على عدد كبير من طبقات الانتباه، يقارب عدد النماذج، والكثير منها متطابق. يتسبب هذا في تباعد عمليات التنفيذ المستقلة مع تطبيق الإصلاحات والتغييرات. +على أجزاء محددة من التعليمات البرمجية. + +ولمعالجة ذلك، اعتمدنا مفهوم "النسخ" في المكتبة. فبإضافة تعليق يُشير إلى أن التعليمات البرمجية هي نسخة من أخرى، نضمن من خلال أنظمة CI والأوامر المحلية عدم تباعد النسخ. لكن هذه العملية، رغم بساطتها، تُسبب إرهاقاً. كما أنها تزيد العبء على المساهمين، وهو ما نهدف إلى تجاوزه. + +غالباً ما تتطلب مساهمات النماذج إضافة تعليمات برمجية (حوالي 1000 سطر)، ومعالج (حوالي 500 سطر)، واختبارات، ووثائق، إلخ. ونادراً ما تقل مساهمات النماذج عن 3000-5000 سطر من التعليمات البرمجية، معظمها أكواد نمطية. هذا يرفع مستوى المساهمات، + +ونهدف مع المحولات النمطية إلى خفض هذا المستوى إلى حدّ مقبول. + +## ما هو؟ + +تقدم المحولات النمطية مفهوم ملف "نمطي" لمجلد نموذج. يقبل هذا الملف النمطي تعليمات برمجية +غير مقبولة عادة في ملفات النمذجة/المعالجة، حيث يسمح بالاستيراد من نماذج مجاورة وكذلك +الوراثة من الفئات إلى فئات أخرى. + +يعرّف هذا الملف النمطي النماذج والمعالجات وفئة التكوين التي سيتم تعريفها في وحداتهم +المتعلقة. + +وأخيرًا، يقدم هذا الميزة أداة `linter` جديدة والتي ستعمل على "تفكيك" الملف النمطي إلى بنية "نموذج واحد، ملف واحد" +هيكل الدليل. سيتم إنشاء هذه الملفات تلقائيًا في كل مرة يتم فيها تشغيل البرنامج النصي؛ مما يقلل من المساهمات المطلوبة +إلى الملف النمطي، وبالتالي فقط إلى التغييرات بين النموذج المساهم والنماذج الأخرى. + +سيقوم مستخدمو النموذج في النهاية باستيراد واستخدام واجهة الملف الواحد، لذا لا يتوقع حدوث أي تغيير هنا. من خلال القيام بذلك، +نأمل في الجمع بين أفضل ما في العالمين: تمكين المساهمات البسيطة مع الالتزام بفلسفتنا. + +لذلك، هذا بديل لعلامات `# Copied from`، ويمكن توقع انتقال النماذج المساهمة سابقًا إلى +تنسيق المحولات النمطية الجديد في الأشهر المقبلة. + +### التفاصيل + +تُبسط أداة "linter" الوراثة، مُنشئةً جميع الملفات المفردة من الملف النمطي، مع الحفاظ على شفافيتها أمام مستخدمي Python. حاليًا، تُبسط الأداة مستوىً واحدًا من الوراثة + +على سبيل المثال: +- إذا ورثت فئة التكوين من فئة أخرى وأضافت/حذفت معامل، فسيتم إما الإشارة إلى الملف المولد مباشرةً + (في حالة الإضافة) أو إزالته تمامًا (في حالة الحذف). +- إذا ورثت فئة من فئة أخرى، على سبيل المثال: `class GemmaModel(LlamaModel):`، تُستنتج التبعيات تلقائيًا + سيتم استنتاج جميع الوحدات الفرعية تلقائيًا من الفئة الأصلية. +- إذا قمت بتعريف وظائف جديدة في الملف `modular` واستخدمتها داخل الفئات، فستستنتج أداة linter ذلك تلقائيًا + +يجب أن تكون قادرًا على كتابة كل شيء (المجزىء اللغوي، ومُعالِج الصور، والنموذج، والتكوين) في الملف `modular`، وسيتم إنشاء الملفات المُقابلة تلقائيًا. + +### التطبيق + +[TODO] نقدم اختبارًا جديدًا، للتأكد من أن المحتوى المولد يتطابق مع ما هو موجود في `modular_xxxx.py` + +### الأمثلة + +هنا مثال سريع باستخدام BERT و RoBERTa. النموذجان مرتبطان ارتباطًا وثيقًا: يختلف تنفيذهما النموذجي في طبقة تضمين. + +بدلاً من إعادة تعريف النموذج بالكامل، إليك كيف يبدو ملف `modular_roberta.py` لفئات النمذجة والتكوين (لأغراض المثال، يتم تجاهل المجزىء اللغوي في هذا الوقت حيث أنه مختلف جدًا). + +```python +from torch import nn +from ..bert.configuration_bert import BertConfig +from ..bert.modeling_bert import ( + BertModel, + BertEmbeddings, + BertForMaskedLM +) + +# تكوين RoBERTa مطابق لتكوين BERT +class RobertaConfig(BertConfig): + model_type = 'roberta' + +# نعيد تعريف الإضافات هنا لتسليط الضوء على اختلاف معرف الحشو، ونعيد تعريف الإضافات الموضعية +class RobertaEmbeddings(BertEmbeddings): + def __init__(self, config): + super().__init__(config()) + + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + +# نموذج RoBERTa مطابق لنموذج BERT، باستثناء طبقة الإضافات. +# نعيد تعريف الإضافات أعلاه، لذا هنا لا توجد حاجة لعمل إضافي +class RobertaModel(BertModel): + def __init__(self, config): + super().__init__(config) + self.embeddings = RobertaEmbeddings(config) + + +# الرؤوس الآن تحتاج فقط إلى إعادة تعريف النموذج داخل `RobertaModel` الصحيح +class RobertaForMaskedLM(BertForMaskedLM): + def __init__(self, config): + super().__init__(config) + self.model = RobertaModel(config) +``` + +لاحظ أنه إذا لم تستخدم الاعتماد الذي حددته، فستحصل على الخطأ التالي: + +```bash +ValueError: You defined `RobertaEmbeddings` in the modular_roberta.py, it should be used + when you define `BertModel`, as it is one of it's direct dependencies. Make sure + you use it in the `__init__` function. +``` + +بالإضافة إلى ذلك، قد تجد قائمة بالأمثلة هنا: + +## ما هو ليس كذلك + +ليس بديلاً لتعليمات برمجة النمذجة (بعد؟)، وإذا لم يكن نموذجك يعتمد على أي شيء آخر موجود من قبل، فيمكنك إضافة ملف `نمذجة` كالعادة. + + +## الاستخدام المتقدم + +### إزالة السمات والوظائف +لإزالة السمات التي لا تستخدم في نموذجك النمطي، والتي لا تريد رؤيتها في النمذجة المفككة: + +```python +class GemmaModel(LlamaModel): | class GemmaModel(PreTrainedModel): + def __init__(self, config): | def __init__(self, config): + super().__init__(self, eos_token) | super().__init__(config) + del self.embed_tokens | self.padding_idx = config.pad_token_id + | self.vocab_size = config.vocab_size + | + | self.layers = nn.ModuleList( + | [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + | ) + | self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + | self.rotary_emb = LlamaRotaryEmbedding(config=config) + | self.gradient_checkpointing = False + | + | # Initialize weights and apply final processing + | self.post_init() +``` +إذا قمت بالتحقق من `LlamaModel` الأصلي، فستجد `embed_tokens` الذي تمت إزالته هنا (كما هو متوقع!) + +إزالة وظيفة مشابهة، تحتاج فقط إلى كتابتها مع `raise ValueError("")` لمحاكاة السلوك الذي تريده فعليًا عند إزالة وظيفة أصلية في بايثون. + +```python +class GemmaTokenizer(LlamaTokenizer): + ... + + def get_spm_processor(self): + raise AttributeError("Not needed for Gemma") + + def unk_token_length(self): + raise AttributeError("Not needed for Gemma") +``` + +### تعريف وظائف جديدة + +إذا قمت بتعريف وظيفة جديدة في الملف `modular` لاستخدامها داخل فئة، على سبيل المثال + +```python +def my_new_function(*args, **kwargs): + # Do something here + pass + +class GemmaModel(LlamaModel): + def forward(*args, **kwargs): + # Call the function + example = my_new_function(*args, **kwargs) + # continue here +``` + +سيتم نسخ وظيفة `my_new_function` (وبشكل متكرر، أي وظائف أخرى جديدة يتم استدعاؤها في جسمها) تلقائيًا +في الملف الذي يتم استخدامه. + +### استدعاء `super()` +قمنا مؤخرًا بشحن بعض الميزات التي تسمح لك بالانتقال من: +```python +class GemmaTokenizer(LlamaTokenizer, PretrainedTokenizerFast): | class GemmaModel(nn.Module): + def __init__(self, eos_token=""): | def __init__(self): + eos_token = AddedToken(eos_token) | eos_token = AddedToken(eos_token) + PretrainedTokenizerFast.__init__(self, eos_token) | super().__init__(eos_token) +``` +هذا مفيد عندما لا تريد تفكيك استدعاء `super()`، وتريد التمييز بين أي استدعاء super init تقوم به! + +### التسمية الخاصة +ندعم الآن أيضًا حالات خاصة مثل +```python +class GemmaVisionModel(CLIPModel): + pass +``` +حيث اسم فئة `GemmaVision` الخاصة بك ليس هو نفسه `Gemma` النمطي. هذا مفيد للغاية للنماذج المركبة. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/multilingual.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/multilingual.md new file mode 100644 index 0000000000000000000000000000000000000000..b4b2a94fd40a33cfb683f88cd8f662df73cb4f0f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/multilingual.md @@ -0,0 +1,160 @@ +# النماذج متعددة اللغات للاستدلال + +هناك العديد من النماذج متعددة اللغات في مكتبة 🤗 Transformers، وتختلف طريقة استخدامها للاستدلال عن النماذج أحادية اللغة. ولكن ليس كل استخدام النماذج متعددة اللغات مختلف. فبعض النماذج، مثل [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased)، يمكن استخدامها تمامًا مثل النموذج أحادي اللغة. سيوضح لك هذا الدليل كيفية استخدام النماذج متعددة اللغات التي تختلف طريقة استخدامها للاستدلال. + +## XLM + +يحتوي XLM على عشر نسخ مختلفة، واحدة منها فقط أحادية اللغة. ويمكن تقسيم نسخ النماذج التسع المتبقية إلى فئتين: نسخ التي تستخدم تضمينات اللغة (language embeddings) وتلك التي لا تستخدمها. + +### XLM مع تضمينات اللغة + +تستخدم النماذج التالية من XLM تضمينات اللغة لتحديد اللغة المستخدمة أثناء الاستدلال: + +- `FacebookAI/xlm-mlm-ende-1024` (نمذجة اللغة المقنعة، الإنجليزية-الألمانية) +- `FacebookAI/xlm-mlm-enfr-1024` (نمذجة اللغة المقنعة، الإنجليزية-الفرنسية) +- `FacebookAI/xlm-mlm-enro-1024` (نمذجة اللغة المقنعة، الإنجليزية-الرومانية) +- `FacebookAI/xlm-mlm-xnli15-1024` (نمذجة اللغة المقنعة، لغات XNLI) +- `FacebookAI/xlm-mlm-tlm-xnli15-1024` (نمذجة اللغة المقنعة + الترجمة، لغات XNLI) +- `FacebookAI/xlm-clm-enfr-1024` (نمذجة اللغة السببية، الإنجليزية-الفرنسية) +- `FacebookAI/xlm-clm-ende-1024` (نمذجة اللغة السببية، الإنجليزية-الألمانية) + +تُمثل تضمينات اللغة على شكل مصفوفة بنفس شكل `input_ids` التي يتم تمريره إلى النموذج. وتعتمد القيم في هذه المصفوفات على اللغة المستخدمة ويتم تحديدها بواسطة معاملى المجزىء `lang2id` و `id2lang`. + +في هذا المثال، قم بتحميل نسخة `FacebookAI/xlm-clm-enfr-1024` ( نمذجة اللغة السببية، الإنجليزية-الفرنسية): + +```py +>>> import torch +>>> from transformers import XLMTokenizer, XLMWithLMHeadModel + +>>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-clm-enfr-1024") +>>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-clm-enfr-1024") +``` + +تُظهر خاصية `lang2id` في المجزىء اللغات وأرقام تعريفها في هذا النموذج: + +```py +>>> print(tokenizer.lang2id) +{'en': 0, 'fr': 1} +``` + +بعد ذلك، قم بإنشاء مثال على المدخلات: + +```py +>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1 +``` + +قم بتعيين معرف اللغة إلى `"en"` واستخدمه لتحديد تضمين اللغة. وتضمين اللغة عبارة عن مصفوفة مملوءة بـ `0` لأن هذا هو معرف اللغة الإنجليزية. يجب أن تكون هذه المصفوفة بنفس حجم `input_ids`. + +```py +>>> language_id = tokenizer.lang2id["en"] # 0 +>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0]) + +>>> # نقوم بإعادة تشكيلها لتكون بالحجم (batch_size، sequence_length) +>>> langs = langs.view(1, -1) # الآن بالحجم [1، sequence_length] (لدينا batch size تساوي 1) +``` + +الآن يمكنك تمرير `input_ids` وتضمين اللغة إلى النموذج: + +```py +>>> outputs = model(input_ids, langs=langs) +``` + +يمكن لنص البرنامج النصي [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) توليد النص باستخدام تضمينات اللغة مع نقاط تفتيش `xlm-clm`. + +### XLM بدون تضمينات اللغة + +النماذج التالية من XLM لا تتطلب تضمينات اللغة أثناء الاستنتاج: + +- `FacebookAI/xlm-mlm-17-1280` (نمذجة اللغة المقنعة، 17 لغة) +- `FacebookAI/xlm-mlm-100-1280` (نمذجة اللغة المقنعة، 100 لغة) + +تُستخدم هذه النماذج لتمثيل الجمل العامة، على عكس نسح XLM السابقة. + +## BERT + +يمكن استخدام النماذج التالية من BERT للمهام متعددة اللغات: + +- `google-bert/bert-base-multilingual-uncased` (نمذجة اللغة المقنعة + التنبؤ بالجملة التالية، 102 لغة) +- `google-bert/bert-base-multilingual-cased` (نمذجة اللغة المقنعة + التنبؤ بالجملة التالية، 104 لغات) + +لا تتطلب هذه النماذج تضمينات اللغة أثناء الاستدلال. يجب أن تُحدّد اللغة من السياق وتستنتج وفقاً لذلك. + +## XLM-RoBERTa + +يمكن استخدام النماذج التالية من XLM-RoBERTa للمهام متعددة اللغات: + +- `FacebookAI/xlm-roberta-base` (نمذجة اللغة المقنعة، 100 لغة) +- `FacebookAI/xlm-roberta-large` (نمذجة اللغة المقنعة، 100 لغة) + +تم تدريب XLM-RoBERTa على 2.5 تيرابايت من بيانات CommonCrawl الجديدة والمحسنة في 100 لغة. ويوفر مكاسب قوية على النماذج متعددة اللغات التي تم إصدارها سابقاً مثل mBERT أو XLM في مهام المصب مثل التصنيف، ووضع العلامات التسلسلية، والأسئلة والأجوبة. + +## M2M100 + +يمكن استخدام النماذج التالية من M2M100 للترجمة متعددة اللغات: + +- `facebook/m2m100_418M` (الترجمة) +- `facebook/m2m100_1.2B` (الترجمة) + +في هذا المثال، قم بتحميل نسحة `facebook/m2m100_418M` لترجمة النص من الصينية إلى الإنجليزية. يمكنك تعيين اللغة المصدر في المجزىء اللغوى: + +```py +>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer + +>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." +>>> chinese_text = "不要插手巫師的事務, 因為他們是微妙的, 很快就會發怒." + +>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh") +>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M") +``` + +تقسيم النّص إلى رموز: + +```py +>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt") +``` + +يجبر M2M100 معرف اللغة الهدف كأول رمز مولد للترجمة إلى اللغة الهدف. قم بتعيين `forced_bos_token_id` إلى `en` في طريقة `generate` للترجمة إلى الإنجليزية: + +```py +>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en")) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.' +``` + +## MBart + +يمكن استخدام النماذج التالية من MBart للترجمة متعددة اللغات: + +- `facebook/mbart-large-50-one-to-many-mmt` (الترجمة الآلية متعددة اللغات من واحد إلى كثير، 50 لغة) +- `facebook/mbart-large-50-many-to-many-mmt` (الترجمة الآلية متعددة اللغات من كثير إلى كثير، 50 لغة) +- `facebook/mbart-large-50-many-to-one-mmt` (الترجمة الآلية متعددة اللغات من كثير إلى واحد، 50 لغة) +- `facebook/mbart-large-50` (الترجمة متعددة اللغات، 50 لغة) +- `facebook/mbart-large-cc25` + +في هذا المثال، قم بتحميل نسخة `facebook/mbart-large-50-many-to-many-mmt` لترجمة النص من الفنلندية إلى الإنجليزية. يمكنك تعيين اللغة المصدر في المجزىء: + +```py +>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + +>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." +>>> fi_text = "Älä sekaannu velhojen asioihin, sillä ne ovat hienovaraisia ja nopeasti vihaisia." + +>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI") +>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") +``` + +تقسيم النّص إلى رموز: + +```py +>>> encoded_en = tokenizer(en_text, return_tensors="pt") +``` + +يجبر MBart معرف لغة الهدف كأول رمز مولد للترجمة إلى اللغة الهدف. قم بتعيين `forced_bos_token_id` إلى `en` في طريقة `generate` للترجمة إلى الإنجليزية: + +```py +>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"]) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry." +``` + +إذا كنت تستخدم نسخة `facebook/mbart-large-50-many-to-one-mmt`، فلا تحتاج إلى إجبار معرف لغة الهدف كأول رمز مولد، وإلا فإن الاستخدام هو نفسه. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/notebooks.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/notebooks.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b481a6c315980d7b6c9003abadd5500d511de2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/notebooks.md @@ -0,0 +1,140 @@ +# دفاتر ملاحظات 🤗 Transformers + +يمكنك أن تجد هنا قائمة بدفاتر الملاحظات الرسمية التي تقدمها Hugging Face. + +كما نود أن ندرج هنا محتوى مثيرًا للاهتمام تم إنشاؤه بواسطة المجتمع. +إذا كتبت دفتر ملاحظات يستفيد من 🤗 Transformers وتود إدراجه هنا، فيُرجى فتح طلب سحب حتى يمكن تضمينه ضمن دفاتر ملاحظات المجتمع. + + +## دفاتر ملاحظات Hugging Face 🤗 + +### دفاتر ملاحظات التوثيق + +يمكنك فتح أي صفحة من صفحات التوثيق كدفتر ملاحظات في Colab (يوجد زر مباشرة على تلك الصفحات) ولكنها مدرجة هنا أيضًا إذا كنت بحاجة إليها: + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [جولة سريعة في المكتبة](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb) | عرض لمختلف واجهات برمجة التطبيقات في Transformers |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/en/transformers_doc/quicktour.ipynb)| +| [ملخص المهام](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb) | كيفية تشغيل نماذج مكتبة Transformers مهمة تلو الأخرى |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| +| [معالجة البيانات مسبقًا](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb) | كيفية استخدام محلل لغوي لمعالجة بياناتك مسبقًا |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| +| [الضبط الدقيق لنموذج مُدرَّب مسبقًا](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb) | كيفية استخدام المدرب لضبط نموذج مُدرَّب مسبقًا بدقة |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| +| [ملخص للمحللات اللغوية](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb) | الاختلافات بين خوارزمية المحلل اللغوي |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| +| [النماذج متعددة اللغات](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb) | كيفية استخدام النماذج متعددة اللغات للمكتبة |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| + + +### أمثلة PyTorch + +#### معالجة اللغة الطبيعية[[pytorch-nlp]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [تدريب محللك اللغوي](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | كيفية تدريب واستخدام محللك اللغوي الخاص بك |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| +| [تدريب نموذج لغتك](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb) | كيفية البدء بسهولة في استخدام المحولات |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على أي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على النمذجة اللغوية](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة LM سببية أو مقنعة. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الرموز المميزة](https://github.com/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة تصنيف الرموز المميزة (NER، PoS). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على الإجابة على الأسئلة](https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SQUAD. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| +| [كيفية ضبط نموذج بدقة على الاختيار من متعدد](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| +| [كيفية ضبط نموذج بدقة على الترجمة](https://github.com/huggingface/notebooks/blob/main/examples/translation.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص](https://github.com/huggingface/notebooks/blob/main/examples/summarization.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)| +| [كيفية تدريب نموذج لغة من البداية](https://github.com/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| تسليط الضوء على جميع الخطوات لتدريب نموذج Transformer بشكل فعال على بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| +| [كيفية إنشاء نص](https://github.com/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| كيفية استخدام أساليب فك التشفير المختلفة لإنشاء اللغة باستخدام المحولات | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| +| [كيفية إنشاء نص (مع قيود)](https://github.com/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| كيفية توجيه إنشاء اللغة باستخدام القيود التي يوفرها المستخدم | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| +| [Reformer](https://github.com/huggingface/blog/blob/main/notebooks/03_reformer.ipynb)| كيف يدفع Reformer حدود النمذجة اللغوية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| + +#### رؤية الكمبيوتر[[pytorch-cv]] + +| دفتر الملاحظات | الوصف | | | +|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------:| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Torchvision)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Torchvision وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Albumentations)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Albumentations وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصور (Kornia)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | يوضح كيفية معالجة البيانات مسبقًا باستخدام Kornia وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)| +| [كيفية إجراء الكشف عن الأشياء بدون لقطات مع OWL-ViT](https://github.com/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb) | يوضح كيفية إجراء الكشف عن الأشياء بدون لقطات على الصور باستخدام استعلامات نصية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)| +| [كيفية ضبط نموذج وصف الصور بدقة](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | يوضح كيفية ضبط BLIP بدقة لوصف الصور على مجموعة بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb)| +| [كيفية بناء نظام تشابه الصور مع Transformers](https://github.com/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | يوضح كيفية بناء نظام تشابه الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb)| +| [كيفية ضبط نموذج SegFormer بدقة على التجزئة الدلالية](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج SegFormer مُدرَّب مسبقًا بدقة على التجزئة الدلالية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb)| +| [كيفية ضبط نموذج VideoMAE بدقة على تصنيف الفيديو](https://github.com/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج VideoMAE مُدرَّب مسبقًا بدقة على تصنيف الفيديو | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb)| + + +#### الصوت[[pytorch-audio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية ضبط نموذج التعرف على الكلام باللغة الإنجليزية بدقة](https://github.com/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا بدقة على TIMIT | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| +| [كيفية ضبط نموذج التعرف على الكلام بأي لغة بدقة](https://github.com/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا متعدد اللغات بدقة على Common Voice | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الصوت](https://github.com/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج كلام مُدرَّب مسبقًا بدقة على Keyword Spotting | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| + + +#### التسلسلات البيولوجية[[pytorch-bio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:----------------------------------------------------------------------------------------|:-------------|------:| +| [كيفية ضبط نموذج بروتين مُدرَّب مسبقًا بدقة](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | شاهد كيفية ترميز البروتينات وضبط نموذج "لغة" بروتين مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | +| [كيفية إنشاء طيات بروتينية](https://github.com/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | شاهد كيفية الانتقال من تسلسل البروتين إلى نموذج بروتين كامل وملف PDB | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | +| [كيفية ضبط نموذج محول النيوكليوتيدات بدقة](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | شاهد كيفية ترميز الحمض النووي وضبط نموذج "لغة" الحمض النووي مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | +| [ضبط نموذج محول النيوكليوتيدات بدقة باستخدام LoRA](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | تدريب نماذج DNA أكبر بكثير بطريقة فعالة من حيث الذاكرة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | + + +#### طرائق أخرى[[pytorch-other]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:----------------------------------------------------------------------------------------|:-------------|------:| +| [التنبؤ الاحتمالي بالسلاسل الزمنية](https://github.com/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | شاهد كيفية تدريب Time Series Transformer على مجموعة بيانات مخصصة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | + +#### دفاتر ملاحظات الأدوات المساعدة [[pytorch-utility]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تصدير النموذج إلى ONNX](https://github.com/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| تسليط الضوء على كيفية التصدير وتشغيل أعباء عمل الاستدلال من خلال ONNX | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| +| [كيفية استخدام المعايير](https://github.com/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| كيفية قياس أداء النماذج باستخدام المحولات | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| + +### أمثلة TensorFlow + +#### معالجة اللغة الطبيعية[[tensorflow-nlp]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [تدريب محللك اللغوي](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | كيفية تدريب واستخدام محللك اللغوي الخاص بك |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| +| [تدريب نموذج لغتك](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb) | كيفية البدء بسهولة في استخدام المحولات |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على أي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على النمذجة اللغوية](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة LM سببية أو مقنعة. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف الرموز المميزة](https://github.com/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على مهمة تصنيف الرموز المميزة (NER، PoS). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الإجابة على الأسئلة](https://github.com/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SQUAD. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الاختيار من متعدد](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على الترجمة](https://github.com/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص](https://github.com/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج مُدرَّب مسبقًا بدقة على XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| + +#### رؤية الكمبيوتر[[tensorflow-cv]] + +| دفتر الملاحظات | الوصف | | | +|:---------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------|:-------------|------:| +| [كيفية ضبط نموذج بدقة على تصنيف الصور](https://github.com/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط أي نموذج رؤية مُدرَّب مسبقًا بدقة على تصنيف الصور | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| +| [كيفية ضبط نموذج SegFormer بدقة على التجزئة الدلالية](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb) | يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج SegFormer مُدرَّب مسبقًا بدقة على التجزئة الدلالية | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| + +#### التسلسلات البيولوجية[[tensorflow-bio]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية ضبط نموذج بروتين مُدرَّب مسبقًا بدقة](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | شاهد كيفية ترميز البروتينات وضبط نموذج "لغة" بروتين مُدرَّب مسبقًا كبير بدقة | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | + +#### دفاتر ملاحظات الأدوات المساعدة [[tensorflow-utility]] + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تدريب نماذج TF/Keras على TPU](https://github.com/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | شاهد كيفية التدريب بسرعة عالية على أجهزة TPU من Google | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | + +### دفاتر ملاحظات Optimum + +🤗 [Optimum](https://github.com/huggingface/optimum) هو امتداد لـ 🤗 Transformers، يوفر مجموعة من أدوات تحسين الأداء التي تمكن من تحقيق أقصى قدر من الكفاءة لتدريب وتشغيل النماذج على الأجهزة المستهدفة. + +| دفتر الملاحظات | الوصف | | | +|:----------|:-------------|:-------------|------:| +| [كيفية تكميم نموذج باستخدام ONNX Runtime لتصنيف النص](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| يوضح كيفية تطبيق التكميم الثابت والديناميكي على نموذج باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime) لأي مهمة GLUE. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| +| [كيفية ضبط نموذج بدقة على تصنيف النص باستخدام ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج بدقة على أي مهمة GLUE باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| +| [كيفية ضبط نموذج بدقة على التلخيص باستخدام ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| يوضح كيفية معالجة البيانات مسبقًا وضبط نموذج بدقة على XSUM باستخدام [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| + + +## دفاتر ملاحظات المجتمع: + +تتوفر المزيد من دفاتر الملاحظات التي طورها المجتمع [هنا](https://hf.co/docs/transformers/community#community-notebooks). + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pad_truncation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pad_truncation.md new file mode 100644 index 0000000000000000000000000000000000000000..d41d4f9c6b453b577b0b1309df87aaba9683f50e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pad_truncation.md @@ -0,0 +1,52 @@ +# الحشو والتقليم + +غالبًا ما تختلف مدخلات الدُفعات في الطول، لذا لا يمكن تحويلها إلى مصفوفات ذات حجم ثابت .يُعدّ الحشو والتقليم هما استراتيجيتان للتعامل مع هذه المشكلة، لإنشاء مصفوفات مستطيلة من مجموعات ذات أطوال مختلفة. ويضيف الحشو رمز **حشو** خاص لضمان أن يكون للتسلسلات الأقصر نفس طول أطول تسلسل في الدفعة أو الطول الأقصى الذي يقبله النموذج. ويعمل التقليم عكس ذلك بتقليم التسلسلات الطويلة. + +في معظم الحالات، ييُعدّ حشو دُفعتك إلى طول أطول تسلسل فيها وتقليمها إلى الطول الأقصى المقبول من النموذج حلًا فعالًا. ومع ذلك، تدعم واجهة برمجة التطبيقات المزيد من الاستراتيجيات إذا كنت بحاجة إليها. هناك ثلاثة معامﻻت تحتاجها لفهم آلية العمل: `padding`، و`truncation`، و`max_length`. + +يحكم معامل `padding` عملية الحشو. يمكن أن يكون قيمة منطقية أو نصية: + + - `True` أو `'longest'`: الحشو إلى أطول تسلسل في الدفعة (لا يتم تطبيق الحشو عند تقديم تسلسل واحد فقط). + - `'max_length'`: الحشو إلى طول محدد بواسطة معامل `max_length` أو الطول الأقصى الذي يقبله + النموذج إذا لم يتم توفير `max_length` (`max_length=None`). سيظل الحشو مطبقًا إذا قدمت تسلسلًا واحدًا فقط. + - `False` أو `'do_not_pad'`: لا يتم تطبيق أي حشو. هذا هو السلوك الافتراضي. + +تحكم معامل `truncation` عملية التقليم. يمكن أن يكون قيمة منطقية أو نصية: + + -قيمة `True` أو `'longest_first'` : تقليم التسلسلات إلى طول أقصى مُحدد بواسطة معامل `max_length`، أو أقصى طول يقبله النموذج في حال عدم تحديد طول مُحدد من قبل المستخدم (`max_length=None`). ستتم عملية التقليم إزالة رمز تلو الآخر، بدءًا من أطول تسلسل في الزوج، إلى أن يصل الطول إلى القيمة المُحددة. + -قيمة `'only_second'`: اقطع إلى طول أقصى محدد بواسطة معامل `max_length` أو أقصى طول يقبله النموذج إذا لم يتم توفير `max_length` (`max_length=None`). هذا سيقلم فقط الجملة الثانية من الزوج إذا تم توفير زوج من التسلسلات (أو دُفعة من أزواج التسلسلات). + -قيمة `'only_first'`: تقليم الجملة الأولى فقط من الزوج عند تقديم زوج من التسلسلات (أو دُفعة من أزواج التسلسلات) إلى طول أقصى مُحدد بواسطة حجة `max_length`، أو أقصى طول يقبله النموذج في حال عدم تحديد طول مُحدد من قبل المستخدم (`max_length=None`). + -قيمة `False` أو `'do_not_truncate'`: لا يتم تطبيق أي تقليم. هذا هو السلوك الافتراضي. +`` + +يحكم معامل `max_length` طول الحشو والتقليم. يمكن أن يكون عدد صحيح أو `None`، وعندها يُحدد افتراضيًا إلى الطول الأقصى الذي يمكن أن يقبله النموذج. إذا لم يكن للنموذج طول إدخال أقصى محدد، يتم إلغاء تنشيط التقليم أو الحشو إلى `max_length`. + +يلخّص الجدول التالي الطريقة المُوصى بها لإعداد الحشو والتقليم. إذا كنت تستخدم أزواج تسلسلات الإدخال في أي من الأمثلة التالية، فيمكنك استبدال `truncation=True` بـ `STRATEGY` المحدد في `['only_first'، 'only_second'، 'longest_first']`، أي `truncation='only_second'` أو `truncation='longest_first'` للتحكم في كيفية تقليم كلا التسلسلين في الزوج كما هو موضّح سابقًا. + + +# حيل الترميز + +هناك العديد من الاستراتيجيات لترميز دفعات الجمل. فيما يلي بعض الأمثلة على ذلك. + +| الترميز | الحشو | التعليمات | +|--------------------------------------|-----------------------------------|---------------------------------------------------------------------------------------------| +| لا ترميز | لا حشو | `tokenizer(batch_sentences)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True)` أو | +| | | `tokenizer(batch_sentences, padding='longest')` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | `tokenizer(batch_sentences, padding='max_length')` | +| | الحشو إلى طول محدد | `tokenizer(batch_sentences, padding='max_length', max_length=42)` | +| | الحشو إلى مضاعف لقيمة معينة | `tokenizer(batch_sentences, padding=True, pad_to_multiple_of=8)` | +| الترميز إلى الحد الأقصى لطول إدخال النموذج | لا حشو | `tokenizer(batch_sentences, truncation=True)` أو | +| | | `tokenizer(batch_sentences, truncation=STRATEGY)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True, truncation=True)` أو | +| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY)` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | `tokenizer(batch_sentences, padding='max_length', truncation=True)` أو | +| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY)` | +| | الحشو إلى طول محدد | غير ممكن | +| الترميز إلى طول محدد | لا حشو | `tokenizer(batch_sentences, truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, truncation=STRATEGY, max_length=42)` | +| | الحشو إلى الحد الأقصى للتسلسل في الدفعة | `tokenizer(batch_sentences, padding=True, truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY, max_length=42)` | +| | الحشو إلى الحد الأقصى لطول إدخال النموذج | غير ممكن | +| | الحشو إلى طول محدد | `tokenizer(batch_sentences, padding='max_length', truncation=True, max_length=42)` أو | +| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY, max_length=42)` | \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/peft.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..f5f050ade427ca4355b79e51eae403c5c9ec1a96 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/peft.md @@ -0,0 +1,250 @@ +# تحميل المحوّلات باستخدام 🤗 PEFT + +[[open-in-colab]] + +تقنية "التدريب الدقيق ذو الكفاءة البارامتيرية" (PEFT)](https://huggingface.co/blog/peft) تقوم بتجميد معلمات النموذج المُدرب مسبقًا أثناء الضبط الدقيق وتضيف عدد صغير من المعلمات القابلة للتدريب (المحولات) فوقه. يتم تدريب المحوّلات لتعلم معلومات خاصة بالمهام. وقد ثبت أن هذا النهج فعال للغاية من حيث استخدام الذاكرة مع انخفاض استخدام الكمبيوتر أثناء إنتاج نتائج قمماثلة للنموذج مضبوط دقيقًا بالكامل. + +عادة ما تكون المحولات المدربة باستخدام PEFT أصغر بمقدار كبير من حيث الحجم من النموذج الكامل، مما يجعل من السهل مشاركتها وتخزينها وتحميلها. + +
+ +
تبلغ أوزان المحول لطراز OPTForCausalLM المخزن على Hub حوالي 6 ميجابايت مقارنة بالحجم الكامل لأوزان النموذج، والتي يمكن أن تكون حوالي 700 ميجابايت.
+
+ +إذا كنت مهتمًا بمعرفة المزيد عن مكتبة 🤗 PEFT، فراجع [الوثائق](https://huggingface.co/docs/peft/index). + +## الإعداد + +ابدأ بتثبيت 🤗 PEFT: + +```bash +pip install peft +``` + +إذا كنت تريد تجربة الميزات الجديدة تمامًا، فقد تكون مهتمًا بتثبيت المكتبة من المصدر: + +```bash +pip install git+https://github.com/huggingface/peft.git +``` + +## نماذج PEFT المدعومة + +يدعم 🤗 Transformers بشكلٍ أصلي بعض طرق PEFT، مما يعني أنه يمكنك تحميل أوزان المحول المخزنة محليًا أو على Hub وتشغيلها أو تدريبها ببضع سطور من التعليمات البرمجية. الطرق المدعومة هي: + +- [محولات الرتبة المنخفضة](https://huggingface.co/docs/peft/conceptual_guides/lora) +- [IA3](https://huggingface.co/docs/peft/conceptual_guides/ia3) +- [AdaLoRA](https://arxiv.org/abs/2303.10512) + +إذا كنت تريد استخدام طرق PEFT الأخرى، مثل تعلم المحث أو ضبط المحث، أو حول مكتبة 🤗 PEFT بشكل عام، يرجى الرجوع إلى [الوثائق](https://huggingface.co/docs/peft/index). + +## تحميل محول PEFT + +لتحميل نموذج محول PEFT واستخدامه من 🤗 Transformers، تأكد من أن مستودع Hub أو الدليل المحلي يحتوي على ملف `adapter_config.json` وأوزان المحوّل، كما هو موضح في صورة المثال أعلاه. بعد ذلك، يمكنك تحميل نموذج محوّل PEFT باستخدام فئة `AutoModelFor`. على سبيل المثال، لتحميل نموذج محول PEFT للنمذجة اللغوية السببية: + +1. حدد معرف النموذج لPEFT +2. مرره إلى فئة [`AutoModelForCausalLM`] + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id) +``` + + + +يمكنك تحميل محول PEFT باستخدام فئة `AutoModelFor` أو فئة النموذج الأساسي مثل `OPTForCausalLM` أو `LlamaForCausalLM`. + + + +يمكنك أيضًا تحميل محول PEFT عن طريق استدعاء طريقة `load_adapter`: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "facebook/opt-350m" +peft_model_id = "ybelkada/opt-350m-lora" + +model = AutoModelForCausalLM.from_pretrained(model_id) +model.load_adapter(peft_model_id) +``` + +راجع قسم [وثائق API](#transformers.integrations.PeftAdapterMixin) أدناه لمزيد من التفاصيل. + +## التحميل في 8 بت أو 4 بت + +راجع قسم [وثائق API](#transformers.integrations.PeftAdapterMixin) أدناه لمزيد من التفاصيل. + +## التحميل في 8 بت أو 4 بت + +يدعم تكامل `bitsandbytes` أنواع بيانات الدقة 8 بت و4 بت، والتي تكون مفيدة لتحميل النماذج الكبيرة لأنها توفر مساحة في الذاكرة (راجع دليل تكامل `bitsandbytes` [guide](./quantization#bitsandbytes-integration) لمعرفة المزيد). أضف المعلمات`load_in_8bit` أو `load_in_4bit` إلى [`~PreTrainedModel.from_pretrained`] وقم بتعيين `device_map="auto"` لتوزيع النموذج بشكل فعال على الأجهزة لديك: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True)) +``` + +## إضافة محول جديد + +يمكنك استخدام الدالة [`~peft.PeftModel.add_adapter`] لإضافة محوّل جديد إلى نموذج يحتوي بالفعل على محوّل آخر طالما أن المحول الجديد مطابقًا للنوع الحالي. على سبيل المثال، إذا كان لديك محول LoRA موجود مرتبط بنموذج: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import LoraConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + init_lora_weights=False +) + +model.add_adapter(lora_config, adapter_name="adapter_1") +``` + +لإضافة محول جديد: + +```py +# قم بتعليق محول جديد بنفس التكوين +model.add_adapter(lora_config, adapter_name="adapter_2") +``` + +الآن يمكنك استخدام [`~peft.PeftModel.set_adapter`] لتعيين المحول الذي سيتم استخدامه: + +```py +# استخدم adapter_1 +model.set_adapter("adapter_1") +output = model.generate(**inputs) +print(tokenizer.decode(output_disabled[0], skip_special_tokens=True)) + +# استخدم adapter_2 +model.set_adapter("adapter_2") +output_enabled = model.generate(**inputs) +print(tokenizer.decode(output_enabled[0], skip_special_tokens=True)) +``` + +## تمكين وتعطيل المحولات + +بمجرد إضافة محول إلى نموذج، يمكنك تمكين أو تعطيل وحدة المحول. لتمكين وحدة المحول: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +adapter_model_id = "ybelkada/opt-350m-lora" +tokenizer = AutoTokenizer.from_pretrained(model_id) +text = "Hello" +inputs = tokenizer(text, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(model_id) +peft_config = PeftConfig.from_pretrained(adapter_model_id) + +# لبدء تشغيله بأوزان عشوائية +peft_config.init_lora_weights = False + +model.add_adapter(peft_config) +model.enable_adapters() +output = model.generate(**inputs) +``` + +لإيقاف تشغيل وحدة المحول: + +```py +model.disable_adapters() +output = model.generate(**inputs) +``` + +## تدريب محول PEFT + +يدعم محول PEFT فئة [`Trainer`] بحيث يمكنك تدريب محول لحالتك الاستخدام المحددة. فهو يتطلب فقط إضافة بضع سطور أخرى من التعليمات البرمجية. على سبيل المثال، لتدريب محول LoRA: + + + +إذا لم تكن معتادًا على ضبط نموذج دقيق باستخدام [`Trainer`، فراجع البرنامج التعليمي](training) لضبط نموذج مُدرب مسبقًا. + + + +1. حدد تكوين المحول باستخدام نوع المهمة والمعاملات الزائدة (راجع [`~peft.LoraConfig`] لمزيد من التفاصيل حول وظيفة هذه المعلمات). + +```py +from peft import LoraConfig + +peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=64, + bias="none", + task_type="CAUSAL_LM"، +) +``` + +2. أضف المحول إلى النموذج. + +```py +model.add_adapter(peft_config) +``` + +3. الآن يمكنك تمرير النموذج إلى [`Trainer`]! + +```py +trainer = Trainer(model=model, ...) +trainer.train() +``` + +لحفظ محول المدرب وتحميله مرة أخرى: + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + +## إضافة طبقات قابلة للتدريب إضافية إلى محول PEFT + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + +## إضافة طبقات قابلة للتدريب إضافية إلى محول PEFT + +يمكنك أيضًا إجراء تدريب دقيق لمحوّلات قابلة للتدريب إضافية فوق نموذج يحتوي بالفعل على محوّلات عن طريق تمرير معلم `modules_to_save` في تكوين PEFT الخاص بك. على سبيل المثال، إذا كنت تريد أيضًا ضبط دقيق لرأس النموذج اللغوي`lm_head` فوق نموذج بمحوّل LoRA: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import LoraConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + modules_to_save=["lm_head"]، +) + +model.add_adapter(lora_config) +``` + +## وثائق API + +[[autodoc]] integrations.PeftAdapterMixin + - load_adapter + - add_adapter + - set_adapter + - disable_adapters + - enable_adapters + - active_adapters + - get_adapter_state_dict + + + + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/perplexity.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/perplexity.md new file mode 100644 index 0000000000000000000000000000000000000000..e7d2a19d2c837fb4ae2f161b78e125f39db40721 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/perplexity.md @@ -0,0 +1,94 @@ +# التعقيد اللغوي للنماذج ذات الطول الثابت + +[[open-in-colab]] + + التعقيد اللغوي (PPL) هي واحدة من أكثر المقاييس شيوعًا لتقييم نماذج اللغة. قبل الخوض في التفاصيل، يجب أن نلاحظ أن المقياس ينطبق تحديدًا على نماذج اللغة الكلاسيكية (يُطلق عليها أحيانًا نماذج اللغة التلقائية المرجعية أو السببية) وهي غير محددة جيدًا لنماذج اللغة المقنعة مثل BERT (راجع [ملخص النماذج](model_summary)). + +تُعرَّف التعقيد اللغوي على أنها الأس المُرفوع لقيمة متوسط اللوغاريتم الاحتمالي لمتتالية. إذا كان لدينا تسلسل رمزي \\(X = (x_0, x_1, \dots, x_t)\\)، فإن حيرة \\(X\\) هي، + +$$\text{PPL}(X) = \exp \left\{ {-\frac{1}{t}\sum_i^t \log p_\theta (x_i|x_{ + +لكن عند التعامل مع النماذج التقريبية، نواجه عادةً قيدًا على عدد الرموز التي يمكن للنموذج معالجتها. على سبيل المثال، تحتوي أكبر نسخة من [GPT-2](model_doc/gpt2) على طول ثابت يبلغ 1024 رمزًا، لذا لا يمكننا حساب \\(p_\theta(x_t|x_{ + +تتميز هذه الطريقة بسرعة حسابها نظرًا لإمكانية حساب درجة التعقيد اللغوي لكل جزء بمسح واحد للأمام، إلا أنها تُعدّ تقريبًا ضعيفًا لدرجة التعقيد اللغوي المُحلّلة بشكل كامل، وعادةً ما تؤدي إلى درجة تعقيد لغوي أعلى (أسوأ) لأن النموذج سيكون لديه سياق أقل في معظم خطوات التنبؤ. + +بدلاً من ذلك، يجب تقييم درجة التعقيد اللغوي للنماذج ذات الطول الثابت باستخدام إستراتيجية النافذة المنزلقة. وينطوي هذا على تحريك نافذة السياق بشكل متكرر بحيث يكون للنموذج سياق أكبر عند إجراء كل تنبؤ. + +Sliding window PPL taking advantage of all available context + +هذا تقريب أقرب للتفكيك الحقيقي لاحتمالية التسلسل وسيؤدي عادةً إلى نتيجة أفضل.لكن الجانب السلبي هو أنه يتطلب تمريرًا للأمام لكل رمز في مجموعة البيانات. حل وسط عملي مناسب هو استخدام نافذة منزلقة بخطوة، بحيث يتم تحريك السياق بخطوات أكبر بدلاً من الانزلاق بمقدار 1 رمز في كل مرة. مما يسمح بإجراء الحساب بشكل أسرع مع إعطاء النموذج سياقًا كبيرًا للتنبؤات في كل خطوة. + +## مثال: حساب التعقيد اللغوي مع GPT-2 في 🤗 Transformers + +دعونا نوضح هذه العملية مع GPT-2. + +```python +from transformers import GPT2LMHeadModel, GPT2TokenizerFast + +device = "cuda" +model_id = "openai-community/gpt2-large" +model = GPT2LMHeadModel.from_pretrained(model_id).to(device) +tokenizer = GPT2TokenizerFast.from_pretrained(model_id) +``` + +سنقوم بتحميل مجموعة بيانات WikiText-2 وتقييم التعقيد اللغوي باستخدام بعض إستراتيجيات مختلفة النافذة المنزلقة. نظرًا لأن هذه المجموعة البيانات الصغيرة ونقوم فقط بمسح واحد فقط للمجموعة، فيمكننا ببساطة تحميل مجموعة البيانات وترميزها بالكامل في الذاكرة. + +```python +from datasets import load_dataset + +test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test") +encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt") +``` + +مع 🤗 Transformers، يمكننا ببساطة تمرير `input_ids` كـ `labels` إلى نموذجنا، وسيتم إرجاع متوسط احتمالية السجل السالب لكل رمز كخسارة. ومع ذلك، مع نهج النافذة المنزلقة، هناك تداخل في الرموز التي نمررها إلى النموذج في كل تكرار. لا نريد تضمين احتمالية السجل للرموز التي نتعامل معها كسياق فقط في خسارتنا، لذا يمكننا تعيين هذه الأهداف إلى `-100` بحيث يتم تجاهلها. فيما يلي هو مثال على كيفية القيام بذلك بخطوة تبلغ `512`. وهذا يعني أن النموذج سيكون لديه 512 رمزًا على الأقل للسياق عند حساب الاحتمالية الشرطية لأي رمز واحد (بشرط توفر 512 رمزًا سابقًا متاحًا للاشتقاق). + +```python +import torch +from tqdm import tqdm + +max_length = model.config.n_positions +stride = 512 +seq_len = encodings.input_ids.size(1) + +nlls = [] +prev_end_loc = 0 +for begin_loc in tqdm(range(0, seq_len, stride)): + end_loc = min(begin_loc + max_length, seq_len) + trg_len = end_loc - prev_end_loc # قد تكون مختلفة عن الخطوة في الحلقة الأخيرة + input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device) + target_ids = input_ids.clone() + target_ids[:, :-trg_len] = -100 + + with torch.no_grad(): + outputs = model(input_ids, labels=target_ids) + + # يتم حساب الخسارة باستخدام CrossEntropyLoss الذي يقوم بالمتوسط على التصنيفات الصحيحة + # لاحظ أن النموذج يحسب الخسارة على trg_len - 1 من التصنيفات فقط، لأنه يتحول داخليًا إلى اليسار بواسطة 1. + neg_log_likelihood = outputs.loss + + nlls.append(neg_log_likelihood) + + prev_end_loc = end_loc + if end_loc == seq_len: + break + +ppl = torch.exp(torch.stack(nlls).mean()) +``` + +يعد تشغيل هذا مع طول الخطوة مساويًا لطول الإدخال الأقصى يعادل لاستراتيجية النافذة غير المنزلقة وغير المثلى التي ناقشناها أعلاه. وكلما صغرت الخطوة، زاد السياق الذي سيحصل عليه النموذج في عمل كل تنبؤ، وكلما كانت التعقيد اللغوي المُبلغ عنها أفضل عادةً. + +عندما نقوم بتشغيل ما سبق باستخدام `stride = 1024`، أي بدون تداخل، تكون درجة التعقيد اللغوي الناتجة هي `19.44`، وهو ما يماثل `19.93` المبلغ عنها في ورقة GPT-2. من خلال استخدام `stride = 512` وبالتالي استخدام إستراتيجية النافذة المنزلقة، ينخفض هذا إلى `16.45`. هذه النتيجة ليست فقط أفضل، ولكنها محسوبة بطريقة أقرب إلى التحليل التلقائي الحقيقي لاحتمالية التسلسل. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/philosophy.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/philosophy.md new file mode 100644 index 0000000000000000000000000000000000000000..09de2991fba28d3e650aafc30bed104396c50894 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/philosophy.md @@ -0,0 +1,49 @@ +# الفلسفة + +تُعد 🤗 Transformers مكتبة برمجية ذات رؤية واضحة صُممت من أجل: + +- الباحثون والمُتعلّمون في مجال التعلم الآلي ممن يسعون لاستخدام أو دراسة أو تطوير نماذج Transformers واسعة النطاق. +- مُطبّقي تعلم الآلة الذين يرغبون في ضبط تلك النماذج أو تشغيلها في بيئة إنتاجية، أو كليهما. +- المهندسون الذين يريدون فقط تنزيل نموذج مُدرب مسبقًا واستخدامه لحل مهمة تعلم آلي معينة. + +تم تصميم المكتبة مع الأخذ في الاعتبار هدفين رئيسيين: + +1. سهولة وسرعة الاستخدام: + + - تمّ تقليل عدد المفاهيم المُجردة التي يتعامل معها المستخدم إلى أدنى حد والتي يجب تعلمها، وفي الواقع، لا توجد مفاهيم مُجردة تقريبًا، فقط ثلاث فئات أساسية مطلوبة لاستخدام كل نموذج: [الإعدادات](main_classes/configuration)، [نماذج](main_classes/model)، وفئة ما قبل المعالجة ([مُجزّئ لغوي](main_classes/tokenizer) لـ NLP، [معالج الصور](main_classes/image_processor) للرؤية، [مستخرج الميزات](main_classes/feature_extractor) للصوت، و [معالج](main_classes/processors) للمدخﻻت متعددة الوسائط). + - يمكن تهيئة جميع هذه الفئات بطريقة بسيطة وموحدة من خلال نماذج مُدربة مسبقًا باستخدام الدالة الموحدة `from_pretrained()` والتي تقوم بتنزيل (إذا لزم الأمر)، وتخزين وتحميل كل من: فئة النموذج المُراد استخدامه والبيانات المرتبطة ( مُعاملات الإعدادات، ومعجم للمُجزّئ اللغوي،وأوزان النماذج) من نقطة تدقيق مُحددة مُخزّنة على [Hugging Face Hub](https://huggingface.co/models) أو ن من نقطة تخزين خاصة بالمستخدم. + - بالإضافة إلى هذه الفئات الأساسية الثلاث، توفر المكتبة واجهتي برمجة تطبيقات: [`pipeline`] للاستخدام السريع لأحد النماذج لأداء استنتاجات على مهمة مُحددة، و [`Trainer`] للتدريب السريع أو الضبط الدقيق لنماذج PyTorch (جميع نماذج TensorFlow متوافقة مع `Keras.fit`). + - نتيجة لذلك، هذه المكتبة ليست صندوق أدوات متعدد الاستخدامات من الكتل الإنشائية للشبكات العصبية. إذا كنت تريد توسيع أو البناء على المكتبة، فما عليك سوى استخدام Python و PyTorch و TensorFlow و Keras العادية والوراثة من الفئات الأساسية للمكتبة لإعادة استخدام الوظائف مثل تحميل النموذج وحفظه. إذا كنت ترغب في معرفة المزيد عن فلسفة الترميز لدينا للنماذج، فراجع منشور المدونة الخاص بنا [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy). + +2. تقديم نماذج رائدة في مجالها مع أداء قريب قدر الإمكان من النماذج الأصلية: + + - نقدم مثالًا واحدًا على الأقل لكل بنية تقوم بإعادة إنتاج نتيجة مقدمة من المؤلفين الرسميين لتلك البنية. + - عادةً ما تكون الشفرة قريبة قدر الإمكان من قاعدة الشفرة الأصلية، مما يعني أن بعض شفرة PyTorch قد لا تكون "بأسلوب PyTorch" كما يمكن أن تكون نتيجة لكونها شفرة TensorFlow محولة والعكس صحيح. + +بعض الأهداف الأخرى: + +- كشف تفاصيل النماذج الداخلية بشكل متسق قدر الإمكان: + + -نتيح الوصول، باستخدام واجهة برمجة واحدة، إلى جميع الحالات المخفية (Hidden-States) وأوزان الانتباه (Attention Weights). + - تم توحيد واجهات برمجة التطبيقات الخاصة بفئات المعالجة المسبقة والنماذج الأساسية لتسهيل التبديل بين النماذج. + +- دمج مجموعة مختارة من الأدوات الواعدة لضبط النماذج بدقة (Fine-tuning) ودراستها: + + - طريقة بسيطة ومتسقة لإضافة رموز جديدة إلى مفردات التضمينات (Embeddings) لضبط النماذج بدقة. + - طرق سهلة لإخفاء (Masking) وتقليم (Pruning) رؤوس المحولات (Transformer Heads). + +- التبديل بسهولة بين PyTorch و TensorFlow 2.0 و Flax، مما يسمح بالتدريب باستخدام إطار واحد والاستدلال باستخدام إطار آخر. + +## المفاهيم الرئيسية + +تعتمد المكتبة على ثلاثة أنواع من الفئات لكل نموذج: + +- **فئات النماذج** يمكن أن تكون نماذج PyTorch ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module))، أو نماذج Keras ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model))، أو نماذج JAX/Flax ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) التي تعمل مع الأوزان المُدربة مسبقًا المقدمة في المكتبة. +- **فئات الإعداد** تخزن معلمات التهيئة المطلوبة لبناء نموذج (مثل عدد الطبقات وحجم الطبقة المخفية). أنت لست مضطرًا دائمًا إلى إنشاء مثيل لهذه الفئات بنفسك. على وجه الخصوص، إذا كنت تستخدم نموذجًا مُدربًا مسبقًا دون أي تعديل، فإن إنشاء النموذج سيهتم تلقائيًا تهيئة الإعدادات (والذي يعد جزءًا من النموذج). +- **فئات ما قبل المعالجة** تحويل البيانات الخام إلى تنسيق مقبول من قبل النموذج. يقوم [المعالج](main_classes/tokenizer) بتخزين المعجم لكل نموذج ويقدم طرقًا لتشفير وفك تشفير السلاسل في قائمة من مؤشرات تضمين الرموز ليتم إطعامها للنموذج. تقوم [معالجات الصور](main_classes/image_processor) بمعالجة إدخالات الرؤية، وتقوم [مستخلصات الميزات](main_classes/feature_extractor) بمعالجة إدخالات الصوت، ويقوم [المعالج](main_classes/processors) بمعالجة الإدخالات متعددة الوسائط. + +يمكن تهيئة جميع هذه الفئات من نسخ مُدربة مسبقًا، وحفظها محليًا، ومشاركتها على منصة Hub عبر ثلاث طرق: + +- تسمح لك الدالة `from_pretrained()` بتهيئة النموذج وتكويناته وفئة المعالجة المسبقة من إصدار مُدرب مسبقًا إما يتم توفيره بواسطة المكتبة نفسها (يمكن العثور على النماذج المدعومة على [Model Hub](https://huggingface.co/models)) أو مخزنة محليًا (أو على خادم) بواسطة المستخدم. +- تسمح لك الدالة `save_pretrained()` بحفظ النموذج، وتكويناته وفئة المعالجة المسبقة محليًا، بحيث يمكن إعادة تحميله باستخدام الدالة `from_pretrained()`. +- تسمح لك `push_to_hub()` بمشاركة نموذج وتكويناتهوفئة المعالجة المسبقة على Hub، بحيث يمكن الوصول إليها بسهولة من قبل الجميع. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..2dd713a6533f6e3831bdde6116f16bbdcf573f57 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_tutorial.md @@ -0,0 +1,315 @@ +# خطوط الأنابيب الاستدلال + +يجعل [`pipeline`] من السهل استخدام أي نموذج من [Hub](https://huggingface.co/models) للاستدلال لأي مهام خاصة باللغة أو الرؤية الحاسوبية أو الكلام أو المهام متعددة الوسائط. حتى إذا لم يكن لديك خبرة في طريقة معينة أو لم تكن على دراية بالرمز الأساسي وراء النماذج، يمكنك مع ذلك استخدامها للاستدلال باستخدام [`pipeline`]! سوف يُعلمك هذا البرنامج التعليمي ما يلي: + +* استخدام [`pipeline`] للاستدلال. +* استخدم مُجزّئ أو نموذجًا محددًا. +* استخدم [`pipeline`] للمهام الصوتية والبصرية والمتعددة الوسائط. + + + +اطلع على وثائق [`pipeline`] للحصول على القائمة كاملة بالمهام المدعومة والمعلمات المتاحة. + + + +## استخدام الأنابيب + +على الرغم من أن لكل مهمة أنبوب [`pipeline`] خاص بها، إلا أنه من الأبسط استخدام تجريد خط الأنابيب العام [`pipeline`] الذي يحتوي على جميع خطوط الأنابيب الخاصة بالمهمة. يقوم [`pipeline`] تلقائيًا بتحميل نموذج افتراضي وفئة معالجة مسبقة قادرة على الاستدلال لمهمتك. دعنا نأخذ مثال استخدام [`pipeline`] للتعرف التلقائي على الكلام (ASR)، أو تحويل الكلام إلى نص. + +1. ابدأ بإنشاء [`pipeline`] وحدد مهمة الاستدلال: + +```py +>>> from transformers import pipeline + +>>> transcriber = pipeline(task="automatic-speech-recognition") +``` + +2. مرر إدخالك إلى [`pipeline`]. في حالة التعرف على الكلام، يكون هذا ملف إدخال صوتي: + +```py +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'} +``` + +لم تحصل على النتيجة التي تريدها؟ تحقق من بعض [نماذج التعرف على الكلام الأكثر تنزيلًا](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) +على Hub لمعرفة ما إذا كان بإمكانك الحصول على نسخة منقحة أفضل. + +لنَجرب نموذج [Whisper large-v2](https://huggingface.co/openai/whisper-large) من OpenAI. تم إصدار Whisper بعد عامين من إصدار Wav2Vec2، وتم تدريبه على ما يقرب من 10 أضعاف كمية البيانات. وبهذه الصفة، فإنه يتفوق على Wav2Vec2 في معظم معظم المقاييس. كما أنه يمتلك ميزة إضافية وهي في التنبؤ بعلامات الترقيم وحالة الأحرف، والتي لا يمكن تحقيقها مع Wav2Vec2. + +دعونا نجربها هنا لنرى كيف تؤدي: + +```py +>>> transcriber = pipeline(model="openai/whisper-large-v2") +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +الآن تبدو هذه النتيجة أكثر دقة! لمقارنة عميقة حول Wav2Vec2 مقابل Whisper، راجع [دورة Audio Transformers](https://huggingface.co/learn/audio-course/chapter5/asr_models). +نشجعك بشدة على التحقق من Hub للحصول على نماذج بلغات مختلفة، ونماذج متخصصة في مجالك، وأكثر من ذلك. +يمكنك التحقق من نتائج النموذج ومقارنتها مباشرة من متصفحك على Hub لمعرفة ما إذا كان يناسبها +أو التعامل مع الحالات الخاصة بشكل أفضل من غيرها. +وإذا لم تجد نموذجًا لحالتك الاستخدام، فيمكنك دائمًا البدء في [التدريب](training) الخاص بك! + +إذا كان لديك عدة مدخلات، فيمكنك تمرير إدخالك كقائمة: + +```py +transcriber( + [ + "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", + "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac", + ] +) +``` + +تعد خطوط الأنابيب مثالية للتجريب نظرًا لأن التبديل من نموذج إلى آخر أمر بسيط للغاية؛ ومع ذلك، هناك بعض الطرق لتحسينها لأحمال عمل أكبر من التجريب. راجع الأدلة التالية التي تتعمق فى التكرار عبر مجموعات البيانات الكاملة أو استخدام خطوط الأنابيب في خادم ويب: +من الوثائق: +* [استخدام خطوط الأنابيب على مجموعة بيانات](#using-pipelines-on-a-dataset) +* [استخدام خطوط الأنابيب لخادم ويب](./pipeline_webserver) + +## المعلمات + +يدعم [`pipeline`] العديد من المعلمات؛ بعضها خاص بالمهمة، والبعض الآخر عام لجميع خطوط الأنابيب. +بشكل عام، يمكنك تحديد المعلمات في أي مكان تريده: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1) + +out = transcriber(...) # سيتم استخدام هذا `my_parameter=1`. +out = transcriber(..., my_parameter=2) # سيتم تجاوز هذا واستخدام `my_parameter=2`. +out = transcriber(...) # سيتم الرجوع إلى استخدام `my_parameter=1`. +``` + +دعونا نلقي نظرة على 3 مهمة: + +### الجهاز + +إذا كنت تستخدم `device=n`، فإن خط الأنابيب يضع النموذج تلقائيًا على الجهاز المحدد. +سيعمل هذا بغض النظر عما إذا كنت تستخدم PyTorch أو Tensorflow. + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device=0) +``` + +إذا كان النموذج كبيرًا جدًا بالنسبة لوحدة معالجة الرسومات (GPU) واحدة، وأنت تستخدم PyTorch، فيمكنك تعيين `torch_dtype='float16'` لتمكين الاستدلال بدقة FP16. عادةً ما لا يتسبب ذلك في حدوث انخفاضات كبيرة في الأداء، ولكن تأكد من تقييمه على نماذجك! + +بدلاً من ذلك، يمكنك تعيين `device_map="auto"` لتحديد كيفية تحميل مخزنات النموذج وتخزينها تلقائيًا. يتطلب استخدام معامل `device_map` مكتبه 🤗 [Accelerate](https://huggingface.co/docs/accelerate): + +```bash +pip install --upgrade accelerate +``` + +تقوم الشفرة التالية بتحميل مخزنات النموذج وتخزينها تلقائيًا عبر الأجهزة: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device_map="auto") +``` + +لاحظ أنه إذا تم تمرير `device_map="auto"`، فلا توجد حاجة لإضافة حجة `device=device` عند إنشاء خط الأنابيب الخاص بك، فقد تواجه بعض السلوكيات غير المتوقعة! + +### حجم الدفعة + +بشكل افتراضي، لن تقوم خطوط الأنابيب بتجميع الاستدلال لأسباب مفصلة [هنا](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). والسبب هو أن التجميع ليست أسرع بالضرورة، ويمكن أن تكون أبطأ في الواقع في بعض الحالات. + +ولكن إذا نجحت في حالتك الاستخدام، فيمكنك استخدام ما يلي: + +```py +transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2) +audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)] +texts = transcriber(audio_filenames) +``` + +هذا يشغل خط الأنابيب على ملفات الصوت الأربعة المتاحة، ولكنه سيمررها على دفعتين +إلى النموذج (الذي يوجد على وحدة معالجة الرسومات (GPU)، حيث من المرجح أن تساعد التجميع) دون الحاجة إلى أي رمز إضافي منك. +يجب أن تتطابق الإخراج دائمًا مع ما كنت ستحصل عليه دون التجميع. المقصود منه فقط كطريقة لمساعدتك في الحصول على سرعة أكبر من خط الأنابيب. + +يمكن لخطوط الأنابيب أيضًا تخفيف بعض تعقيدات التجميع لأنه، بالنسبة لبعض خطوط الأنابيب، يجب تقسيم عنصر واحد (مثل ملف صوتي طويل) إلى أجزاء متعددة لمعالجته بواسطة نموذج. يقوم خط الأنابيب بأداء هذه العملية التي تسمى تجميع الأجزاء [*batch batching*](./main_classes/pipelines#pipeline-chunk-batching) نيابة عنك. + +### معلمات خاصة بالمهمة + +توفر جميع المهام معلمات خاصة بالمهمة تتيح المرونة والخيارات الإضافية لمساعدتك في أداء عملك. +على سبيل المثال، تحتوي طريقة [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] على معلمة `return_timestamps` التي تبدو واعدة لترجمة مقاطع الفيديو: +```py +>>> transcriber = pipeline(model="openai/whisper-large-v2", return_timestamps=True) +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.', 'chunks': [{'timestamp': (0.0, 11.88), 'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its'}, {'timestamp': (11.88, 12.38), 'text': ' creed.'}]} +``` + +كما ترون، استنتج النموذج النص.وكذلك حدد **وقت** نطق الجمل المختلفة. + +تتوفر العديد من المعلمات لكل مهمة، لذا تحقق من مرجع API لكل مهمة لمعرفة ما يمكنك تعديله! +على سبيل المثال، تحتوي [`~transformers.AutomaticSpeechRecognitionPipeline`] على معلمة `chunk_length_s` مفيدة +للعمل على ملفات الصوت الطويلة جدًا (على سبيل المثال، ترجمة الأفلام أو مقاطع الفيديو التي تستغرق ساعة) والتي لا يمكن للنموذج التعامل معها بمفرده: + +```python +>>> transcriber = pipeline(model="openai/whisper-large-v2", chunk_length_s=30) +>>> transcriber("https://huggingface.co/datasets/reach-vb/random-audios/resolve/main/ted_60.wav") +{'text': " So in college, I was a government major, which means I had to write a lot of papers. Now, when a normal student writes a paper, they might spread the work out a little like this. So, you know. You get started maybe a little slowly, but you get enough done in the first week that with some heavier days later on, everything gets done and things stay civil. And I would want to do that like that. That would be the plan. I would have it all ready to go, but then actually the paper would come along, and then I would kind of do this. And that would happen every single paper. But then came my 90-page senior thesis, a paper you're supposed to spend a year on. I knew for a paper like that, my normal workflow was not an option, it was way too big a project. So I planned things out and I decided I kind of had to go something like this. This is how the year would go. So I'd start off light and I'd bump it up"} +``` + +إذا لم تتمكن من العثور على معلمة قد تساعدك حقًا، فلا تتردد في [طلبها](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)! + + +## استخدام خطوط الأنابيب على مجموعة بيانات + +يمكن أيضًا تشغيل خط الأنابيب للاستدلال على مجموعة بيانات كبيرة. أسهل طريقة نوصي بها للقيام بذلك هي باستخدام المتكرر (iterator).: + +```py +def data(): + for i in range(1000): + yield f"My example {i}" + + +pipe = pipeline(model="openai-community/gpt2", device=0) +generated_characters = 0 +for out in pipe(data()): + generated_characters += len(out[0]["generated_text"]) +``` + +يقوم المؤشر `data()` بإرجاع كل نتيجة، ويتعرف خط الأنابيب تلقائيًا +المدخل قابل للتحديد ويبدأ في جلب البيانات أثناء +يستمر في معالجتها على وحدة معالجة الرسومات (GPU) (يستخدم هذا [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) تحت الغطاء). +هذا أمر مهم لأنك لا تحتاج إلى تخصيص ذاكرة لمجموعة البيانات بأكملها +ويمكنك تغذية وحدة معالجة الرسومات (GPU) بأسرع ما يمكن. + +نظرًا لأن التجميع قد تسرع الأمور، فقد يكون من المفيد ضبط معلمة `batch_size` هنا. + +أبسط طريقة للتنقل خلال مجموعة بيانات هي فقط تحميل واحدة من 🤗 [Datasets](https://github.com/huggingface/datasets/): + +```py +# KeyDataset هي أداة مساعدة ستقوم فقط بإخراج العنصر الذي نهتم به. +from transformers.pipelines.pt_utils import KeyDataset +from datasets import load_dataset + +pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0) +dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]") + +for out in pipe(KeyDataset(dataset, "audio")): + print(out) +``` + +## استخدام خطوط الأنابيب لخادم ويب + + +إن إنشاء محرك استدلال هو موضوع معقد يستحق صفحته الخاصة. + + +[Link](./pipeline_webserver) + +## خط أنابيب الرؤية + +إن استخدام [`pipeline`] لمهام الرؤية مماثل تمامًا. + +حدد مهمتك ومرر صورتك إلى المصنف. يمكن أن تكون الصورة رابطًا أو مسارًا محليًا أو صورة مشفرة بتنسيق base64. على سبيل المثال، ما نوع القطط الموضح أدناه؟ + +![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) + +```py +>>> from transformers import pipeline + +>>> vision_classifier = pipeline(model="google/vit-base-patch16-224") +>>> preds = vision_classifier( +... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}] +``` + +## خط أنابيب النص + +إن استخدام [`pipeline`] لمهام NLP مماثل تمامًا. + +```py +>>> from transformers import pipeline + +>>> # هذا النموذج هو نموذج "zero-shot-classification". +>>> # سيصنف النص، ولكن يمكنك اختيار أي تسمية قد تتخيلها +>>> classifier = pipeline(model="facebook/bart-large-mnli") +>>> classifier( +... "I have a problem with my iphone that needs to be resolved asap!!", +... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"], +... ) +{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]} +``` + +## خط أنابيب متعدد الوسائط + +تدعم [`pipeline`] أكثر من طريقة واحدة. على سبيل المثال، تجمع مهمة الإجابة على الأسئلة المرئية (VQA) بين النص والصورة. لا تتردد في استخدام أي رابط صورة تريده وسؤال تريد طرحه حول الصورة. يمكن أن تكون الصورة عنوان URL أو مسارًا محليًا للصورة. + +على سبيل المثال، إذا كنت تستخدم هذه [صورة الفاتورة](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png): + +```py +>>> from transformers import pipeline + +>>> vqa = pipeline(model="impira/layoutlm-document-qa") +>>> output = vqa( +... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", +... question="What is the invoice number?", +... ) +>>> output[0]["score"] = round(output[0]["score"], 3) +>>> output +[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}] +``` + + + +لتشغيل المثال أعلاه، تحتاج إلى تثبيت [`pytesseract`](https://pypi.org/project/pytesseract/) بالإضافة إلى 🤗 Transformers: + +```bash +sudo apt install -y tesseract-ocr +pip install pytesseract +``` + + + +## استخدام `pipeline` على نماذج كبيرة مع 🤗 `accelerate`: + +يمكنك بسهولة تشغيل `pipeline` على نماذج كبيرة باستخدام 🤗 `accelerate`! أولاً، تأكد من تثبيت `accelerate` باستخدام `pip install accelerate`. + +قم أولاً بتحميل نموذجك باستخدام `device_map="auto"`! سنستخدم `facebook/opt-1.3b` كمثال لنا. + +```py +# pip install accelerate +import torch +from transformers import pipeline + +pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto") +output = pipe("This is a cool example!", do_sample=True, top_p=0.95) +``` + +يمكنك أيضًا تمرير نماذج محملة بـ 8 بت إذا قمت بتثبيت `bitsandbytes` وإضافة الحجة `load_in_8bit=True` + +```py +# pip install accelerate bitsandbytes +import torch +from transformers import pipeline + +pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True}) +output = pipe("This is a cool example!", do_sample=True, top_p=0.95) +``` + +لاحظ أنه يمكنك استبدال نقطة التفتيش بأي نموذج من Hugging Face يدعم تحميل النماذج الكبيرة، مثل BLOOM. + +## إنشاء عروض توضيحية ويب من خطوط الأنابيب باستخدام `gradio` + +يتم دعم خطوط الأنابيب تلقائيًا في [Gradio](https://github.com/gradio-app/gradio/)، وهي مكتبة تجعل إنشاء تطبيقات تعليم الآلة الجميلة والسهلة الاستخدام على الويب أمرًا سهلاً. أولاً، تأكد من تثبيت Gradio: + +``` +pip install gradio +``` + +بعد ذلك، يمكنك إنشاء عرض توضيحي ويب حول خط أنابيب تصنيف الصور (أو أي خط أنابيب آخر) في سطر واحد من التعليمات البرمجية عن طريق استدعاء وظيفة [`Interface.from_pipeline`](https://www.gradio.app/docs/interface#interface-from-pipeline) في Gradio لإطلاق خط الأنابيب. يقوم هذا بإنشاء واجهة بديهية للسحب والإفلات في مستعرضك: + +```py +from transformers import pipeline +import gradio as gr + +pipe = pipeline("image-classification", model="google/vit-base-patch16-224") + +gr.Interface.from_pipeline(pipe).launch() +``` + + +![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/panda-classification.png) + +بشكل افتراضي، يعمل العرض التوضيحي على خادم محلي. إذا كنت تريد مشاركتها مع الآخرين، فيمكنك إنشاء رابط عام مؤقت عن طريق تعيين `share=True` في `launch()`. يمكنك أيضًا استضافة عرضك التوضيحي على [Hugging Face Spaces](https://huggingface.co/spaces) للحصول على رابط دائم. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_webserver.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_webserver.md new file mode 100644 index 0000000000000000000000000000000000000000..2a19e84d1632413557790626fd116de0ca5048f3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/pipeline_webserver.md @@ -0,0 +1,126 @@ +# استخدام قنوات المعالجة لخادم ويب + + + +يُعدّ إنشاء محرك استدلال أمرًا معقدًا، ويعتمد الحل "الأفضل" على مساحة مشكلتك. هل تستخدم وحدة المعالجة المركزية أم وحدة معالجة الرسومات؟ هل تريد أقل زمن وصول، أم أعلى معدل نقل، أم دعمًا للعديد من النماذج، أم مجرد تحقيق أقصى تحسين نموذج محدد؟ +توجد طرق عديدة لمعالجة هذا الموضوع، لذلك ما سنقدمه هو إعداد افتراضي جيد للبدء به قد لا يكون بالضرورة هو الحل الأمثل لك.``` + + + +الشيء الرئيسي الذي يجب فهمه هو أننا يمكن أن نستخدم مؤشرًا، تمامًا كما تفعل [على مجموعة بيانات](pipeline_tutorial#using-pipelines-on-a-dataset)، نظرًا لأن خادم الويب هو أساسًا نظام ينتظر الطلبات ويعالجها عند استلامها. + +عادةً ما تكون خوادم الويب متعددة الإرسال (متعددة مؤشرات الترابط، وغير متزامنة، إلخ) للتعامل مع الطلبات المختلفة بشكل متزامن. من ناحية أخرى، فإن قنوات المعالجة (وبشكل رئيسي النماذج الأساسية) ليست رائعة للتوازي؛ حيث تستهلك الكثير من ذاكرة الوصول العشوائي، لذا من الأفضل منحها جميع الموارد المتاحة عند تشغيلها أو إذا كانت مهمة تطلب حسابات مكثفة. + +سنحل ذلك من خلال جعل خادم الويب يتعامل مع الحمل الخفيف لاستقبال الطلبات وإرسالها،وجعل مؤشر ترابط واحد يتعامل مع العمل الفعلي. سيستخدم هذا المثال `starlette`. ولكن قد تضطر إلى ضبط الكود أو تغييره إذا كنت تستخدم كودًا آخر لتحقيق التأثير نفسه. + +أنشئ `server.py`: + +```py +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.routing import Route +from transformers import pipeline +import asyncio + + +async def homepage(request): + payload = await request.body() + string = payload.decode("utf-8") + response_q = asyncio.Queue() + await request.app.model_queue.put((string, response_q)) + output = await response_q.get() + return JSONResponse(output) + + +async def server_loop(q): + pipe = pipeline(model="google-bert/bert-base-uncased") + while True: + (string, response_q) = await q.get() + out = pipe(string) + await response_q.put(out) + + +app = Starlette( + routes=[ + Route("/", homepage, methods=["POST"]), + ], +) + + +@app.on_event("startup") +async def startup_event(): + q = asyncio.Queue() + app.model_queue = q + asyncio.create_task(server_loop(q)) +``` + +الآن يمكنك تشغيله باستخدام: + +```bash +uvicorn server:app +``` + +ويمكنك الاستعلام عنه: + +```bash +curl -X POST -d "test [MASK]" http://localhost:8000/ +#[{"score":0.7742936015129089,"token":1012,"token_str":".","sequence":"test."},...] +``` + +وهكذا، لديك الآن فكرة جيدة عن كيفية إنشاء خادم ويب! + +المهم حقًا هو أننا نقوم بتحميل النموذج **مرة واحدة** فقط، لذلك لا توجد نسخ من النموذج على خادم الويب. بهذه الطريقة، لا يتم استخدام ذاكرة الوصول العشوائي غير الضرورية. تسمح آلية وضع قائمة الانتظار بالقيام بأشياء متقدمة مثل تجميع بعض العناصر قبل الاستدلال لاستخدام معالجة الدفعات الديناميكية: + + + +تم كتابة نموذج الكود البرمجى أدناه بشكل مقصود مثل كود وهمي للقراءة. لا تقم بتشغيله دون التحقق مما إذا كان منطقيًا لموارد النظام الخاص بك! + + + +```py +(string, rq) = await q.get() +strings = [] +queues = [] +while True: + try: + (string, rq) = await asyncio.wait_for(q.get(), timeout=0.001) # 1ms + except asyncio.exceptions.TimeoutError: + break + strings.append(string) + queues.append(rq) +strings +outs = pipe(strings, batch_size=len(strings)) +for rq, out in zip(queues, outs): + await rq.put(out) +``` + +مرة أخرى، تم تحسين الرمز المقترح لسهولة القراءة، وليس ليكون أفضل كود. بادئ ذي بدء، لا يوجد حد لحجم الدفعة، والذي عادةً ما لا يكون فكرة عظيمة. بعد ذلك، يتم إعادة ضبط الفترة في كل عملية جلب لقائمة الانتظار، مما يعني أنه قد يتعين عليك الانتظار لفترة أطول بكثير من 1 مللي ثانية قبل تشغيل الاستدلال (تأخير الطلب الأول بهذا القدر). + +سيكون من الأفضل تحديد مهلة واحدة مدتها 1 مللي ثانية. + +سيظل هذا ينتظر دائمًا لمدة 1 مللي ثانية حتى إذا كانت قائمة الانتظار فارغًا، والذي قد لا يكون الأفضل نظرًا لأنك تريد على الأرجح البدء في إجراء الاستدلال إذا لم يكن هناك شيء في قائمة الانتظا. ولكن ربما يكون منطقيًا إذا كانت المعالجة الديناميكية للدفعات مهمة حقًا لحالة الاستخدام لديك. مرة أخرى، لا يوجد حل واحد هو الأفضل. + +## بعض الأشياء التي قد ترغب في مراعاتها + +### التحقق من الأخطاء + +هناك الكثير مما قد يحدث بشكل خاطئ في عند اتاحة النموذج للجمهور: نفاد الذاكرة، أو نفاد المساحة، أو فشل تحميل النموذج، أو قد يكون الاستعلام خاطئًا، أو قد يكون الاستعلام صحيحًا ولكن لا يزال يفشل في التشغيل بسبب خطأ في إعداد النموذج، وما إلى ذلك. + +بشكل عام، من الجيد أن يُخرِج الخادم الأخطاء للمستخدم، لذلك يُعدّ إضافة الكثير من عبارات `try..except` لعرض هذه الأخطاء فكرة +جيدة. لكن ضع في اعتبارك أنه قد يمثل أيضًا مخاطرة أمنية الكشف عن جميع تلك الأخطاء اعتمادًا على سياق الأمان لديك. + +### قطع الدائرة (Circuit breaking) + +عادةً ما تبدو خوادم الويب أفضل عندما تقوم بقطع الدائرة. وهذا يعني أنها ترجع أخطاء صحيحة عندما تكون مثقلة بشكل زائد بدلاً من الانتظار إلى أجل غير مسمى. قم بإرجاع خطأ 503 بدلاً من الانتظار لفترة طويلة جدًا أو 504 بعد فترة طويلة. + +من السهل نسبيًا تنفيذ ذلك في الكود المقترح نظرًا لوجود قائمة انتظار واحد. إن النظر في حجم قائمة الانتظار هو طريقة أساسية لبدء إرجاع الأخطاء قبل فشل خادم الويب بسبب الحمل الزائد. + +### حجب عمل خيط التنفيذ الرئيسي (Main thread) + +حاليًا، لا تدعم PyTorch العمليات غير المتزامنة، وسيؤدي الحساب إلى حجب عمل الخيط الرئيسي أثناء تشغيله. وهذا يعني أنه سيكون من الأفضل إذا تم إجبار PyTorch على أن تعمل على الخيط/العملية الخاصة به. لم يتم ذلك هنا لأن الكود أكثر تعقيدًا (في الغالب لأن خيوط التنفيذ والعمليات غير المتزامنة وقوائم الانتظار لا تتوافق معًا). ولكن في النهاية، فإنه سيؤدي نفس الوظيفة. + +سيكون هذا مهمًا إذا كان الاستدلال للعناصر الفردية طويلاً (> 1 ثانية) لأنه في هذه الحالة، فهذا يعني أنه سيتعين أثناء الاستدلال على كل استعلام الانتظار لمدة ثانية واحدة قبل حتى يلقي خطأ. + +### المعالجة الديناميكية + +بشكل عام، لا تُعدّ المعالجة بالضرورة تحسينًا مقارنةً بتمرير عنصر واحد في كل مرة (راجع [تفاصيل المعالجة بالدفعات](./main_classes/pipelines#pipeline-batching) لمزيد من المعلومات). ولكن يمكن أن تكون فعالة للغاية عند استخدامها بالإعداد الصحيح. في واجهة برمجة التطبيقات، لا توجد معالجة ديناميكية بشكل افتراضي (فرصة كبيرة جدًا للتباطؤ). ولكن بالنسبة لاستدلال BLOOM - وهو نموذج كبير جدًا - تُعدّ المعالجة الديناميكية **ضرورية** لتوفير تجربة جيدة للجميع. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/preprocessing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/preprocessing.md new file mode 100644 index 0000000000000000000000000000000000000000..8c1f68934d2052a5baf6d30488be968725a5be9b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/preprocessing.md @@ -0,0 +1,521 @@ +# المعالجة المسبقة Preprocessing + +[[open-in-colab]] + +قبل تدريب نموذج على مجموعة بيانات، يجب معالجتها مسبقًا وفقًا تنسيق المتوقع لمدخلات النموذج. سواء كانت بياناتك نصية أو صورًا أو صوتًا، فيجب تحويلها وتجميعها في دفعات من الموترات. يوفر 🤗 Transformers مجموعة من فئات المعالجة المسبقة للمساعدة في إعداد بياناتك للنموذج. في هذا البرنامج التعليمي، ستتعلم أنه بالنسبة لـ: + +* للنص، استخدم [مُجزّئ الرموز](./main_classes/tokenizer) لتحويل النص إلى تسلسل من الرموز، وإنشاء تمثيل رقمي للرموز، وتجميعها في موترات(tensors). +* للكلام والصوت، استخدم [مستخرج الميزات](./main_classes/feature_extractor) لاستخراج ميزات متسلسلة من أشكال موجات الصوت وتحويلها إلى موترات. +* تستخدم مدخلات الصورة [ImageProcessor](./main_classes/image_processor) لتحويل الصور إلى موترات. +* تستخدم مدخلات متعددة الوسائط [معالجًا](./main_classes/processors) لدمج مُجزّئ الرموز ومستخرج الميزات أو معالج الصور. + + + +`AutoProcessor` **يعمل دائمًا** ويختار تلقائيًا الفئة الصحيحة للنموذج الذي تستخدمه، سواء كنت تستخدم مُجزّئ رموز أو معالج صور أو مستخرج ميزات أو معالجًا. + + + +قبل البدء، قم بتثبيت 🤗 Datasets حتى تتمكن من تحميل بعض مجموعات البيانات لتجربتها: + +```bash +pip install datasets +``` + +## معالجة اللغة الطبيعية (Natural Language Processing (NLP + + + +أداة المعالجة المسبقة الرئيسية للبيانات النصية هي [مُجزّئ اللغوي](main_classes/tokenizer). يقوم مُجزّئ اللغوي بتقسيم النص إلى "أجزاء لغوية" (tokens) وفقًا لمجموعة من القواعد. يتم تحويل الأجزاء اللغوية إلى أرقام ثم إلى منسوجات، والتي تصبح مدخلات للنموذج. يقوم المجزئ اللغوي بإضافة أي مدخلات إضافية يحتاجها النموذج. + + + +إذا كنت تخطط لاستخدام نموذج مُدرب مسبقًا، فمن المهم استخدامالمجزئ اللغوي المقترن بنفس ذلك النموذج. يضمن ذلك تقسيم النص بنفس الطريقة التي تم بها تقسيم النصوص ما قبل التدريب، واستخدام نفس القاموس الذي يربط بين الأجزاء اللغوية وأرقامها ( يُشار إليها عادةً باسم المفردات *vocab*) أثناء التدريب المسبق. + + + +ابدأ بتحميل المُجزّئ اللغوي مُدرب مسبقًا باستخدام طريقة [`AutoTokenizer.from_pretrained`]. يقوم هذا بتنزيل المفردات *vocab* الذي تم تدريب النموذج عليه: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +``` + +ثم مرر نصك إلى المُجزّئ اللغوي: + +```py +>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.") +>>> print(encoded_input) +{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +يعيد المُجزّئ اللغوي قاموسًا يحتوي على ثلاثة عناصر مهمة: + +* [input_ids](glossary#input-ids) هي الفهارس المقابلة لكل رمز في الجملة. +* [attention_mask](glossary#attention-mask) يشير إلى ما إذا كان يجب الانتباه بالرمز أم لا. +* [token_type_ids](glossary#token-type-ids) يحدد التسلسل الذي ينتمي إليه الرمز عندما يكون هناك أكثر من تسلسل واحد. + +أعد إدخالك الأصلي عن طريق فك ترميز `input_ids`: + +```py +>>> tokenizer.decode(encoded_input["input_ids"]) +'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]' +``` + +كما ترى، أضاف المُجزّئ اللغوي رمزين خاصين - `CLS` و`SEP` (مصنف وفاصل) - إلى الجملة. لا تحتاج جميع النماذج إلى +رموز خاصة، ولكن إذا فعلوا ذلك، فإن المُجزّئ اللغوي يضيفها تلقائيًا لك. + +إذا كان هناك عدة جمل تريد معالجتها مسبقًا، فقم بتمريرها كقائمة إلى مُجزّئ اللغوي: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_inputs = tokenizer(batch_sentences) +>>> print(encoded_inputs) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]]} +``` + +### الحشو Padding + +لا تكون الجمل دائمًا بنفس الطول، وهذا يمكن أن يمثل مشكلة لأن الموترات،وهي مدخلات النموذج، تحتاج إلى شكل موحد. الحشو هو استراتيجية لضمان أن تكون الموترات مستطيلة عن طريق إضافة رمز حشو *padding* خاص إلى الجمل الأقصر. + +قم بتعيين معلمة الحشو `padding` إلى `True` لحشو التسلسلات الأقصر في الدفعة لتطابق أطول تسلسل: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0، 0، 0، 0، 0، 0، 0، 0]]} +``` + +تم الآن حشو الجملتين الأولى والثالثة بـ `0` لأنهما أقصر. + +### البتر Truncation + +وعلى صعيد أخر، قد يكون التسلسل طويلًا جدًا بالنسبة للنموذج للتعامل معه. في هذه الحالة، ستحتاج إلى بتر التسلسل إلى طول أقصر. + +قم بتعيين معلمة `truncation` إلى `True` لتقليم تسلسل إلى الطول الأقصى الذي يقبله النموذج: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0، 0، 0، 0، 0]]، + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0، 0، 0، 0], + [1, 1, 1, 1, 1, 1, 1، 1، 1، 1، 1، 1، 1، 1، 1، 1], + [1، 1، 1، 1، 1، 1، 1، 0، 0، 0، 0، 0، 0، 0، 0، 0]]} +``` + + + +تحقق من دليل المفاهيم [Padding and truncation](./pad_truncation) لمعرفة المزيد حول معامﻻت الحشو و البتر المختلفة. + + + +### بناء الموترات Build tensors + +أخيرًا، تريد أن يقوم المجزئ اللغوي بإرجاع موترات (tensors) الفعلية التي ستُغذي النموذج. + +قم بتعيين معلمة `return_tensors` إلى إما `pt` لـ PyTorch، أو `tf` لـ TensorFlow: + + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt") +>>> print(encoded_input) +{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])} +``` + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf") +>>> print(encoded_input) +{'input_ids': , + 'token_type_ids': , + 'attention_mask': } +``` + + + + + +تدعم خطوط الأنابيب المختلفة معامل مُجزِّئ الرموز(tokenizer) بشكل مختلف في طريقة `()__call__` الخاصة بها. +و خطوط الأنابيب `text-2-text-generation` تدعم فقط `truncation`. +و خطوط الأنابيب `text-generation` تدعم `max_length` و`truncation` و`padding` و`add_special_tokens`. +أما في خطوط الأنابيب `fill-mask`، يمكن تمرير معامل مُجزِّئ الرموز (tokenizer) في المتغير `tokenizer_kwargs` (قاموس). + + + +## الصوت Audio + +بالنسبة للمهام الصوتية، ستحتاج إلى [مستخرج الميزات](main_classes/feature_extractor) لإعداد مجموعة البيانات الخاصة بك للنماذج. تم تصميم مستخرج الميزات لاستخراج الميزات من بيانات الصوت الخام، وتحويلها إلى موتورات. + +قم بتحميل مجموعة بيانات [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) (راجع البرنامج التعليمي لـ 🤗 [Datasets](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيفية استخدام مستخرج الميزات مع مجموعات البيانات الصوتية: + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +``` + +الوصول إلى العنصر الأول من عمود `audio` لمعرفة المدخلات. يؤدي استدعاء عمود `audio` إلى تحميل ملف الصوت وإعادة أخذ العينات تلقائيًا: + +```py +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +يعيد هذا ثلاثة عناصر: + +* `array` هو إشارة الكلام المحملة - وإعادة أخذ العينات المحتملة - كصفيف 1D. +* `path` يشير إلى موقع ملف الصوت. +* `sampling_rate` يشير إلى عدد نقاط البيانات في إشارة الكلام المقاسة في الثانية. + +بالنسبة لهذا البرنامج التعليمي، ستستخدم نموذج [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base). الق نظرة على بطاقة النموذج، وستتعلم أن Wav2Vec2 مُدرب مسبقًا على صوت الكلام الذي تم أخذ عينات منه بمعدل 16 كيلو هرتز. من المهم أن يتطابق معدل أخذ العينات لبيانات الصوت مع معدل أخذ العينات لمجموعة البيانات المستخدمة لتدريب النموذج مسبقًا. إذا لم يكن معدل أخذ العينات لبياناتك هو نفسه، فيجب إعادة أخذ العينات من بياناتك. + +1. استخدم طريقة [`~datasets.Dataset.cast_column`] في 🤗 Datasets لإعادة أخذ العينات بمعدل أخذ العينات 16 كيلو هرتز: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +2. استدعاء عمود `audio` مرة أخرى لأخذ عينات من ملف الصوت: + +```py +>>> dataset[0]["audio"] +{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., + 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 16000} +``` + +بعد ذلك، قم بتحميل مستخرج الميزات لتطبيع وحشو المدخلات. عند إضافة حشو للبيانات النصية، تتم إضافة "0" للتسلسلات الأقصر. تنطبق نفس الفكرة على بيانات الصوت. يضيف مستخرج الميزات "0" - الذي يتم تفسيره على أنه صمت - إلى "array". + +قم بتحميل مستخرج الميزات باستخدام [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +مرر صفيف الصوت إلى مستخرج الميزات. كما نوصي بإضافة معامل `sampling_rate` في مستخرج الميزات من أجل تصحيح الأخطاء الصامتة التي قد تحدث بشكل أفضل. + +```py +>>> audio_input = [dataset[0]["audio"]["array"]] +>>> feature_extractor(audio_input, sampling_rate=16000) +{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ..., + 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]} +``` + +تمامًا مثل مُجزِّئ الرموز، يمكنك تطبيق الحشو أو البتر للتعامل مع التسلسلات المتغيرة في دفعة. الق نظرة على طول التسلسل لهاتين العينتين الصوتيتين: + +```py +>>> dataset[0]["audio"]["array"].shape +(173398,) + +>>> dataset[1]["audio"]["array"].shape +(106496,) +``` + +قم بإنشاء دالة لمعالجة مجموعة البيانات بحيث يكون للنماذج الصوتية نفس الأطوال. حدد أقصى طول للعينة ، وسيقوم مستخرج الميزات إما بإضافة حشو أو بتر التسلسلات لمطابقتها: + +```py +>>> def preprocess_function(examples): +... audio_arrays = [x["array"] for x in examples["audio"]] +... inputs = feature_extractor( +... audio_arrays, +... sampling_rate=16000, +... padding=True, +... max_length=100000, +... truncation=True, +... ) +... return inputs +``` + +قم بتطبيق `preprocess_function` على أول بضع أمثلة في مجموعة البيانات: + +```py +>>> processed_dataset = preprocess_function(dataset[:5]) +``` + +أطوال العينات الآن متساوية وتطابق الطول الأقصى المحدد. يمكنك الآن تمرير مجموعة البيانات المعالجة إلى النموذج! + +```py +>>> processed_dataset["input_values"][0].shape +(100000,) + +>>> processed_dataset["input_values"][1].shape +(100000,) +``` + +## رؤية الكمبيوتر Computer vision + +بالنسبة لمهام رؤية الحاسوبية، ستحتاج إلى معالج صور [image processor](main_classes/image_processor) لإعداد مجموعة البيانات الخاصة بك لتناسب النموذج. تتكون معالجة الصور المسبقة من عدة خطوات لتحويل الصور إلى الشكل الذي يتوقعه النموذج. وتشمل هذه الخطوات، على سبيل المثال لا الحصر، تغيير الحجم والتطبيع وتصحيح قناة الألوان وتحويل الصور إلى موترات(tensors). + + + +عادة ما تتبع معالجة الصور المسبقة شكلاً من أشكال زيادة البيانات (التضخيم). كلا العمليتين، معالجة الصور المسبقة وزيادة الصور تغيران بيانات الصورة، ولكنها تخدم أغراضًا مختلفة: + +*زيادة البيانات: تغيير الصور عن طريق زيادة الصور بطريقة يمكن أن تساعد في منع الإفراط في التعميم وزيادة متانة النموذج. يمكنك أن تكون مبدعًا في كيفية زيادة بياناتك - ضبط السطوع والألوان، واالقص، والدوران، تغيير الحجم، التكبير، إلخ. ومع ذلك، كن حذرًا من عدم تغيير معنى الصور بزياداتك. +*معالجة الصور المسبقة: تضمن معالجة الصور اتتطابق الصور مع تنسيق الإدخال المتوقع للنموذج. عند ضبط نموذج رؤية حاسوبية بدقة، يجب معالجة الصور بالضبط كما كانت عند تدريب النموذج في البداية. + +يمكنك استخدام أي مكتبة تريدها لزيادة بيانات الصور. لمعالجة الصور المسبقة، استخدم `ImageProcessor` المرتبط بالنموذج. + + + +قم بتحميل مجموعة بيانات [food101](https://huggingface.co/datasets/food101) (راجع دليل 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيف يمكنك استخدام معالج الصور مع مجموعات بيانات رؤية الحاسب: + + + +استخدم معامل `split` من 🤗 Datasets لتحميل عينة صغيرة فقط من مجموعة التدريب نظرًا لحجم البيانات كبيرة جدًا! + + + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("food101", split="train[:100]") +``` + +بعد ذلك، الق نظرة على الصورة مع ميزة 🤗 Datasets [`Image`](https://huggingface.co/docs/datasets/package_reference/main_classes?highlight=image#datasets.Image): + +```py +>>> dataset[0]["image"] +``` + +
+ +
+ +قم بتحميل معالج الصور باستخدام [`AutoImageProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +أولاً، دعنا نضيف بعض الزيادات إلى الصور. يمكنك استخدام أي مكتبة تفضلها، ولكن في هذا الدليل، سنستخدم وحدة [`transforms`](https://pytorch.org/vision/stable/transforms.html) من torchvision. إذا كنت مهتمًا باستخدام مكتبة زيادة بيانات أخرى، فتعرف على كيفية القيام بذلك في [دفاتر Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) أو [دفاتر Kornia](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb). + +1. هنا نستخدم [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) لربط بعض التحولات معًا - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) و [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html). +لاحظ بالنسبة لتغيير الحجم، يمكننا الحصول على متطلبات حجم الصورة من `image_processor`. بالنسبة لبعض النماذج، يُتوقع ارتفاع وعرض دقيقين، بينما بالنسبة للنماذج الأخرى، يتم تحديد الحافة الأقصر`shortest_edge` فقط. + +```py +>>> from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose + +>>> size = ( +... image_processor.size["shortest_edge"] +... if "shortest_edge" in image_processor.size +... else (image_processor.size["height"], image_processor.size["width"]) +... ) + +>>> _transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)]) +``` + +2. يقبل النموذج [`pixel_values`](model_doc/vision-encoder-decoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) +كإدخال له. يمكن لـ `ImageProcessor` التعامل مع تطبيع الصور، وتوليد موترات(tensors) مناسبة. +قم بإنشاء دالة تجمع بين تضخيم بيانات الصور ومعالجة الصور المسبقة لمجموعة من الصور وتوليد `pixel_values`: + +```py +>>> def transforms(examples): +... images = [_transforms(img.convert("RGB")) for img in examples["image"]] +... examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"] +... return examples +``` + + + +في المثال أعلاه، قمنا بتعيين `do_resize=False` لأننا قمنا بالفعل بتغيير حجم الصور في تحويل زيادة الصور، +واستفدنا من خاصية `size` من `image_processor` المناسب. إذا لم تقم بتغيير حجم الصور أثناء زيادة الصور، +فاترك هذا المعلمة. بشكل افتراضي، ستتعامل `ImageProcessor` مع تغيير الحجم. + +إذا كنت ترغب في تطبيع الصور كجزء من تحويل زيادة الصور، فاستخدم قيم `image_processor.image_mean`، +و `image_processor.image_std`. + + +3. ثم استخدم 🤗 Datasets[`~datasets.Dataset.set_transform`] لتطبيق التحولات أثناء التنقل: +```py +>>> dataset.set_transform(transforms) +``` + +4. الآن عند الوصول إلى الصورة، ستلاحظ أن معالج الصور قد أضاف `pixel_values`. يمكنك تمرير مجموعة البيانات المعالجة إلى النموذج الآن! + +```py +>>> dataset[0].keys() +``` + +هكذا تبدو الصورة بعد تطبيق التحولات. تم اقتصاص الصورة بشكل عشوائي وتختلف خصائص الألوان بها. + +```py +>>> import numpy as np +>>> import matplotlib.pyplot as plt + +>>> img = dataset[0]["pixel_values"] +>>> plt.imshow(img.permute(1, 2, 0)) +``` + +
+ +
+ + + +بالنسبة للمهام مثل الكشف عن الأشياء، والتجزئة الدلالية، والتجزئة المثالية، والتجزئة الشاملة، يوفر `ImageProcessor` +تقوم هذه الطرق بتحويل النواتج الأولية للنموذج إلى تنبؤات ذات معنى مثل مربعات الحدود، +أو خرائط التجزئة. + + + +### الحشو Pad + +في بعض الحالات، على سبيل المثال، عند ضبط نموذج [DETR](./model_doc/detr) بدقة، يقوم النموذج بتطبيق زيادة المقياس أثناء التدريب. قد يتسبب ذلك في اختلاف أحجام الصور في دفعة واحدة. يمكنك استخدام [`DetrImageProcessor.pad`] +من [`DetrImageProcessor`] وتحديد دالة `collate_fn` مخصصة لتجميع الصور معًا. + +```py +>>> def collate_fn(batch): +... pixel_values = [item["pixel_values"] for item in batch] +... encoding = image_processor.pad(pixel_values, return_tensors="pt") +... labels = [item["labels"] for item in batch] +... batch = {} +... batch["pixel_values"] = encoding["pixel_values"] +... batch["pixel_mask"] = encoding["pixel_mask"] +... batch["labels"] = labels +... return batch +``` + +## متعدد الوسائط Mulimodal + +بالنسبة للمهام التي تتطلب مدخلات متعددة الوسائط، ستحتاج إلى معالج [processor](main_classes/processors) لإعداد مجموعة البيانات الخاصة بك لتناسب النموذج. يقترن المعالج بين بمعالجين آخرين مثل محول النص إلى رمز ومستخرج الميزات. + +قم بتحميل مجموعة بيانات [LJ Speech](https://huggingface.co/datasets/lj_speech) (راجع دليل 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub) لمزيد من التفاصيل حول كيفية تحميل مجموعة بيانات) لمعرفة كيف يمكنك استخدام معالج للتعرف التلقائي على الكلام (ASR): + +```py +>>> from datasets import load_dataset + +>>> lj_speech = load_dataset("lj_speech", split="train") +``` + +بالنسبة لـ ASR، فأنت تركز بشكل أساسي على `audio` و `text` لذا يمكنك إزالة الأعمدة الأخرى: + +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +الآن الق نظرة على أعمدة `audio` و `text`: +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +الآن الق نظرة على أعمدة `audio` و `text`: + +```py +>>> lj_speech[0]["audio"] +{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ..., + 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav', + 'sampling_rate': 22050} + +>>> lj_speech[0]["text"] +'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition' +``` + +تذكر أنه يجب عليك دائمًا [إعادة أخذ العينات](preprocessing#audio) لمعدل أخذ العينات في مجموعة البيانات الصوتية الخاصة بك لمطابقة معدل أخذ العينات في مجموعة البيانات المستخدمة لتدريب النموذج مسبقًا! + +```py +>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +قم بتحميل معالج باستخدام [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") +``` + +1. قم بإنشاء دالة لمعالجة بيانات الصوت الموجودة في `array` إلى `input_values`، ورموز `text` إلى `labels`. هذه هي المدخلات للنموذج: + +```py +>>> def prepare_dataset(example): +... audio = example["audio"] + +... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000)) + +... return example +``` + +2. قم بتطبيق دالة `prepare_dataset` على عينة: + +```py +>>> prepare_dataset(lj_speech[0]) +``` + +لقد أضاف المعالج الآن `input_values` و `labels`، وتم أيضًا إعادة أخذ العينات لمعدل أخذ العينات بشكل صحيح إلى 16 كيلو هرتز. يمكنك تمرير مجموعة البيانات المعالجة إلى النموذج الآن! diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/quicktour.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/quicktour.md new file mode 100644 index 0000000000000000000000000000000000000000..1795c3a5d74fcc36ce97b05fcf46b004ebc1202f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/quicktour.md @@ -0,0 +1,543 @@ +# جولة سريعة + +[[open-in-colab]] + +ابدأ رحلتك مع مكتبة 🤗 Transformers! سواء كنت مطورًا أو مستخدمًا عاديًا، ستساعدك هذه الجولة السريعة على البدء وستُظهر لك كيفية استخدام [`pipeline`] للاستنتاج، وتحميل نموذج مُدرب مسبقًا ومعالج مُسبق مع [AutoClass](./model_doc/auto)، وتدريب نموذج بسرعة باستخدام PyTorch أو TensorFlow. إذا كنت مبتدئًا، نوصي بالاطلاع على دروسنا أو [الدورة](https://huggingface.co/course/chapter1/1) للحصول على شرح أكثر تعمقًا للمفاهيم المقدمة هنا. + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +!pip install transformers datasets evaluate accelerate +``` + +ستحتاج أيضًا إلى تثبيت إطار عمل التعلم الآلي المفضل لديك: + + + + +```bash +pip install torch +``` + + + +```bash +pip install tensorflow +``` + + + +## خط الأنابيب + + + +يمثل [`pipeline`] أسهل وأسرع طريقة لاستخدام نموذج مُدرب مسبقًا للاستنتاج. يمكنك استخدام [`pipeline`] جاهزًا للعديد من المهام عبر طرق مختلفة، والتي يظهر بعضها في الجدول أدناه: + + + +للاطلاع على القائمة الكاملة للمهام المتاحة، راجع [مرجع واجهة برمجة التطبيقات الخاصة بخط الأنابيب](./main_classes/pipelines). + + + +
+ +| **المهمة** | **الوصف** | **الطريقة** | **معرف خط الأنابيب** | +|------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|-----------------------------------------------| +| تصنيف النص | تعيين تسمية إلى تسلسل نص معين | NLP | pipeline(task=“sentiment-analysis”) | +| توليد النص | توليد نص بناءً على موجه معين | NLP | pipeline(task=“text-generation”) | +| تلخيص | توليد ملخص لتسلسل نص أو مستند | NLP | pipeline(task=“summarization”) | +| تصنيف الصور | تعيين تسمية لصورة معينة | رؤية حاسوبية | pipeline(task=“image-classification”) | +| تجزئة الصورة | تعيين تسمية لكل بكسل فردي في الصورة (يدعم التجزئة الدلالية، والمجملة، وتجزئة مثيلات) | رؤية حاسوبية | pipeline(task=“image-segmentation”) | +| اكتشاف الأشياء | التنبؤ بحدود الأشياء وفئاتها في صورة معينة | رؤية حاسوبية | pipeline(task=“object-detection”) | +| تصنيف الصوت | تعيين تسمية لبيانات صوتية معينة | صوتي | pipeline(task=“audio-classification”) | +| التعرف على الكلام التلقائي | نسخ الكلام إلى نص | صوتي | pipeline(task=“automatic-speech-recognition”) | +| الإجابة على الأسئلة البصرية | الإجابة على سؤال حول الصورة، مع إعطاء صورة وسؤال | متعدد الوسائط | pipeline(task=“vqa”) | +| الإجابة على أسئلة المستندات | الإجابة على سؤال حول المستند، مع إعطاء مستند وسؤال | متعدد الوسائط | pipeline(task="document-question-answering") | +| كتابة تعليق على الصورة | إنشاء تعليق على صورة معينة | متعدد الوسائط | pipeline(task="image-to-text") | + +
+ابدأ بإنشاء مثيل من [`pipeline`] وتحديد المهمة التي تريد استخدامه لها. في هذا الدليل، ستستخدم خط الأنابيب للتحليل النصي كنموذج: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis") +``` + +يقوم [`pipeline`] بتنزيل وتخزين نسخة احتياطية من نموذج افتراضي [مُدرب مسبقًا](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) ومعالج للتحليل النصي. الآن يمكنك استخدام `classifier` على النص المستهدف: + +```py +>>> classifier("We are very happy to show you the 🤗 Transformers library.") +[{'label': 'POSITIVE', 'score': 0.9998}] +``` + +إذا كان لديك أكثر من إدخال واحد، قم بتمرير إدخالاتك كقائمة إلى [`pipeline`] لإرجاع قائمة من القواميس: + +```py +>>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."]) +>>> for result in results: +... print(f"label: {result['label']}, with score: {round(result['score'], 4)}") +label: POSITIVE, with score: 0.9998 +label: NEGATIVE, with score: 0.5309 +``` +يمكن لخط الأنابيب أيضًا أن يتنقل خلال مجموعة بيانات كاملة لأي مهمة تريدها. كمثال على ذلك، دعنا نختار التعرف على الكلام التلقائي كمهمة لنا: + +```py +>>> import torch +>>> from transformers import pipeline + +>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h") +``` + +قم بتحميل مجموعة بيانات صوتية (راجع دليل البدء السريع لـ 🤗 Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart#audio) للحصول على مزيد من التفاصيل) التي تريد التنقل خلالها. على سبيل المثال، قم بتحميل مجموعة بيانات [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14): + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT +``` + +يجب التأكد من أن نفس الجودة الصوتية (معدل أخذ العينات) لمجموعة البيانات يتطابق مع معدل أخذ العينات الذي تم تدريب [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) عليه: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate)) +``` + +يتم تحميل الملفات الصوتية وإعادة تشكيلها تلقائيًا عند استدعاء العمود "audio". +استخرج المصفوفات الموجية الخام من أول 4 عينات ومررها كقائمة إلى خط الأنابيب: + +```py +>>> result = speech_recognizer(dataset[:4]["audio"]) +>>> print([d["text"] for d in result]) +['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FONDERING HOW I'D SET UP A JOIN TO HELL T WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE APSO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AN I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I FURN A JOINA COUT'] +``` + +بالنسبة لمجموعات البيانات الكبيرة التي تحتوي على مدخلات ضخمة (كما هو الحال في البيانات الصوتية أو المرئية)، يفضل تمرير مولد (generator) بدلاً من قائمة لتحميل جميع المدخلات في الذاكرة دفعة واحدة. راجع [مرجع واجهة برمجة التطبيقات الخاصة بخط الأنابيب](./main_classes/pipelines) للحصول على مزيد من المعلومات. + +### ااستخدم نموذجًا ومجزئًا آخرين في خط الأنابيب + +يمكن لخط الأنابيب [`pipeline`] استيعاب أي نموذج من [Hub](https://huggingface.co/models)، مما يسهل التكيف مع حالات الاستخدام الأخرى. على سبيل المثال، إذا كنت تريد نموذجًا قادرًا على التعامل مع النص الفرنسي، فاستخدم العلامات على Hub لفلتره نموذج مناسب. تعيد النتيجة الأولى المرشحة نموذج BERT متعدد اللغات [BERT model](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment) الذي تم ضبطه مسبقًا للتحليل المشاعر والذي يمكنك استخدامه للنص الفرنسي: + +```py +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +``` + + + +استخدم [`AutoModelForSequenceClassification`] و [`AutoTokenizer`] لتحميل النموذج المُدرب مسبقًا ومعالجته المرتبط به (مزيد من المعلومات حول `AutoClass` في القسم التالي): + +```py +>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + +استخدم [`TFAutoModelForSequenceClassification`] و [`AutoTokenizer`] لتحميل النموذج المُدرب مسبقًا ومعالجته المرتبط به (مزيد من المعلومات حول `TFAutoClass` في القسم التالي): + +```py +>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + + +حدد النموذج والمعالج في [`pipeline`]. الآن يمكنك تطبيق `classifier` على النص الفرنسي: + +```py +>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) +>>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.") +[{'label': '5 stars', 'score': 0.7273}] +``` +إذا لم تجد نموذجًا جاهزًا يناسب مهمتك، فستحتاج إلى ضبط نموذج مُدرب مسبقًا على بياناتك. اطلع على [دليل الضبط الدقيق](./training) للتعرف على كيفية القيام بذلك. وبعد ضبط نموذجك المُدرب مسبقًا، يرجى مراعاة [المشاركة](./model_sharing) النموذج مع المجتمع على Hub لمساعدة الجميع في مجال التعلم الآلي! 🤗 + +## AutoClass + + + +في الخلفية، تعمل فئتا [`AutoModelForSequenceClassification`] و [`AutoTokenizer`] معًا لتشغيل دالة pipeline() الذي استخدمتها أعلاه. تعتبر [AutoClass](./model_doc/auto) اختصارًا يقوم تلقائيًا باسترداد بنية نموذج مُدرب مسبقًا من اسمه أو مساره. كل ما عليك فعله هو تحديد فئة `AutoClass` المناسبة لمهمتك وفئة المعالجة المرتبطة بها. + +لنعد إلى المثال من القسم السابق ولنرى كيف يمكنك استخدام `AutoClass` لتكرار نتائج خط الأنابيب. + +### المجزئ التلقائي (AutoTokenizer) + +يتولى المجزئ مسؤولية تحويل النص إلى مصفوفة من الأرقام (رموز) يمكن للنموذج فهمها ومعالجتها. هناك قواعد متعددة تحكم عملية التجزئة، بما في ذلك كيفية تقسيم كلمة وما هو المستوى الذي يجب أن تقسيم الكلمات عنده (تعرف على المزيد حول المعالجة في [ملخص المجزئ](./tokenizer_summary)). أهم شيء يجب تذكره هو أنك تحتاج إلى إنشاء مثيل للمجزئ بنفس اسم النموذج لضمان استخدامك لقواعد التجزئة نفسها التي تم تدريب النموذج عليها. + +قم بتحميل المجزئ باستخدام [`AutoTokenizer`]: + +```py +>>> from transformers import AutoTokenizer + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + +مرر نصك إلى المجزئ: + +```py +>>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.") +>>> print(encoding) +{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +يعيد المجزئ قاموسًا يحتوي على: + +* [input_ids](./glossary#input-ids): التمثيلات الرقمية لرموزك. +* [attention_mask](./glossary#attention-mask): تشير إلى الرموز التي يجب الانتباه بها. + +يمكن المجزئ أيضًا قبول قائمة من المدخلات، ويقوم بـ "حشو" و"تقصير" النص لإرجاع كدفعة بطول موحد: + + + + +```py +>>> pt_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="pt", +... ) +``` + + + +```py +>>> tf_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="tf", +... ) +``` + + + + + +اطلع على [الدليل التمهيدي للمعالجة المسبقة](./preprocessing) للحصول على مزيد من التفاصيل حول المعالجة، وكيفية استخدام [`AutoImageProcessor`] و [`AutoFeatureExtractor`] و [`AutoProcessor`] لمعالجة الصور والصوت والإدخالات متعددة الوسائط. + + + +### AutoModel + + + +تقدم مكتبة 🤗 Transformers طريقة بسيطة وموحدة لتحميل نماذج مدربة مسبقًا. وهذا يعني أنه يمكنك تحميل [`AutoModel`] كما لو كنت تقوم بتحميل [`AutoTokenizer`]. الفرق الوحيد هو اختيار فئة [`AutoModel`] المناسبة للمهمة. بالنسبة لتصنيف النص (أو التسلسل)، يجب عليك تحميل [`AutoModelForSequenceClassification`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +راجع [ملخص المهمة](./task_summary) للاطلاع على المهام التي تدعمها فئة [`AutoModel`]. + + + +الآن قم بتمرير دفعة المدخلات المُعالجة مسبقًا مباشرة إلى النموذج. عليك فقط فك تعبئة القاموس عن طريق إضافة `**`: + +# تدريب النموذج + +الآن، مرر دفعة المدخلات المعالجة مسبقًا مباشرة إلى النموذج. ما عليك سوى فك تعبئة القاموس عن طريق إضافة `**`: + +```py +>>> pt_outputs = pt_model(**pt_batch) +``` + +يُخرج النموذج التنشيطات النهائية في سمة `logits`. طبق دالة softmax على `logits` للحصول على الاحتمالات: + +```py +>>> from torch import nn + +>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1) +>>> print(pt_predictions) +tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725], + [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=) +``` + + +يوفر 🤗 Transformers طريقة بسيطة وموحدة لتحميل مثيلات مُدربة مسبقًا. وهذا يعني أنه يمكنك تحميل [`TFAutoModel`] مثل تحميل [`AutoTokenizer`]. والفرق الوحيد هو تحديد [`TFAutoModel`] الصحيح للمهمة. للتصنيف النصي (أو التسلسلي)، يجب تحميل [`TFAutoModelForSequenceClassification`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +راجع [ملخص المهام](./task_summary) للمهام المدعومة بواسطة فئة [`AutoModel`]. + + + +الآن، مرر دفعة المدخلات المعالجة مسبقًا مباشرة إلى النموذج. يمكنك تمرير المصفوفات كما هي: + +```py +>>> tf_outputs = tf_model(tf_batch) +``` + +يقوم النموذج بإخراج التنشيطات النهائية في سمة `logits`. طبق دالة softmax على `logits` لاسترداد الاحتمالات: + +```py +>>> import tensorflow as tf + +>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1) +>>> tf_predictions # doctest: +IGNORE_RESULT +``` + + + + + +تخرج جميع نماذج 🤗 Transformers (PyTorch أو TensorFlow) المصفوفات *قبل* دالة التنشيط النهائية (مثل softmax) لأن دالة التنشيط النهائية غالبًا ما تكون مدمجة مع دالة الخسارة. نواتج النموذج عبارة عن فئات بيانات خاصة، لذلك يتم استكمال سماتها تلقائيًا في IDE. وتتصرف مخرجات النموذج مثل زوج مرتب أو قاموس (يمكنك الفهرسة باستخدام عدد صحيح ، شريحة، أو سلسلة)، وفي هذه الحالة، يتم تجاهل السمات التي تساوي None. + + + +### حفظ النموذج + + + +بمجرد ضبط نموذجك، يمكنك حفظه مع برنامج الترميز الخاص به باستخدام [`PreTrainedModel.save_pretrained`]: + +```py +>>> pt_save_directory = "./pt_save_pretrained" +>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT +>>> pt_model.save_pretrained(pt_save_directory) +``` + +عندما تكون مستعدًا لاستخدام النموذج مرة أخرى، أعد تحميله باستخدام [`PreTrainedModel.from_pretrained`]: + +```py +>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained") +``` + + +بمجرد ضبط نموذجك، يمكنك حفظه مع برنامج الترميز الخاص به باستخدام [`TFPreTrainedModel.save_pretrained`]: + +```py +>>> tf_save_directory = "./tf_save_pretrained" +>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT +>>> tf_model.save_pretrained(tf_save_directory) +``` + +عندما تكون مستعدًا لاستخدام النموذج مرة أخرى، أعد تحميله باستخدام [`TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained") +``` + + + +من الميزات الرائعة في 🤗 Transformers القدرة على حفظ نموذج وإعادة تحميله كنموذج PyTorch أو TensorFlow. يمكن أن يحول معامل `from_pt` أو `from_tf` النموذج من إطار عمل إلى آخر: + + + + +```py +>>> from transformers import AutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory) +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True) +``` + + + +```py +>>> from transformers import TFAutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory) +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True) +``` + + + + +## إنشاء نماذج مخصصة + +يمكنك تعديل فئة تكوين النموذج لتغيير كيفية بناء النموذج. يحدد التكوين سمات النموذج، مثل عدد الطبقات المخفية أو رؤوس الاهتمام. تبدأ من الصفر عند تهيئة نموذج من فئة تكوين مخصصة. يتم تهيئة سمات النموذج بشكل عشوائي، ويجب تدريب النموذج قبل استخدامه للحصول على نتائج ذات معنى. + +ابدأ باستيراد [`AutoConfig`]. ثم قم بتحميل النموذج المُدرب مسبقًا الذي تريد تعديله. ضمن [`AutoConfig.from_pretrained`]. يمكنك تحديد السمة التي تريد تغييرها، مثل عدد رؤوس الاهتمام: + +```py +>>> from transformers import AutoConfig + +>>> my_config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased", n_heads=12) +``` + + + +قم بإنشاء نموذج من تكوينك المخصص باستخدام [`AutoModel.from_config`]: + +```py +>>> from transformers import AutoModel + +>>> my_model = AutoModel.from_config(my_config) +``` + + +قم بإنشاء نموذج من تكوينك المخصص باستخدام [`TFAutoModel.from_config`]: + +```py +>>> from transformers import TFAutoModel + +>>> my_model = TFAutoModel.from_config(my_config) +``` + + + +الق نظرة على دليل [إنشاء بنية مخصصة](./create_a_model) لمزيد من المعلومات حول بناء التكوينات المخصصة. + +## المدرب - حلقة تدريب محسنة لـ PyTorch + +جميع النماذج عبارة عن [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) قياسية، لذا يمكنك استخدامها في أي حلقة تدريب نموذجية. في حين يمكنك كتابة حلقة التدريب الخاصة بك، يوفر 🤗 Transformers فئة [`Trainer`] لـ PyTorch، والتي تحتوي على حلقة التدريب الأساسية وتضيف وظائف إضافية لميزات مثل التدريب الموزع، والدقة المختلطة، والمزيد. + +وفقًا لمهمتك، ستقوم عادةً بتمرير المعلمات التالية إلى [`Trainer`]: + +1. ستبدأ بـ [`PreTrainedModel`] أو [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module): + + ```py + >>> from transformers import AutoModelForSequenceClassification + + >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +2. تحتوي [`TrainingArguments`] على فرط معلمات النموذج التي يمكنك تغييرها مثل معدل التعلم، وحجم الدفعة، وعدد العصور التي يجب التدريب عليها. يتم استخدام القيم الافتراضية إذا لم تحدد أي حجج تدريب: + + ```py + >>> from transformers import TrainingArguments + + >>> training_args = TrainingArguments( + ... output_dir="path/to/save/folder/", + ... learning_rate=2e-5, + ... per_device_train_batch_size=8, + ... per_device_eval_batch_size=8, + ... num_train_epochs=2, + ... ) + ``` + +3. قم بتحميل فئة معالجة مسبقة مثل برنامج الترميز، أو معالج الصور، أو مستخرج الميزات، أو المعالج: + + ```py + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +4. قم بتحميل مجموعة بيانات: + + ```py + >>> from datasets import load_dataset + + >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT + ``` + +5. قم بإنشاء دالة لترميز مجموعة البيانات: + + ```py + >>> def tokenize_dataset(dataset): + ... return tokenizer(dataset["text"]) + ``` + + ثم قم بتطبيقه على مجموعة البيانات بأكملها باستخدام [`~datasets.Dataset.map`]: + + ```py + >>> dataset = dataset.map(tokenize_dataset, batched=True) + ``` + +6. [`DataCollatorWithPadding`] لإنشاء دفعة من الأمثلة من مجموعة البيانات الخاصة بك: + + ```py + >>> from transformers import DataCollatorWithPadding + + >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer) + ``` + +الآن قم بتجميع جميع هذه الفئات في [`Trainer`]: + +```py +>>> from transformers import Trainer + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=dataset["train"], +... eval_dataset=dataset["test"], +... tokenizer=tokenizer, +... data_collator=data_collator, +... ) # doctest: +SKIP +``` +عندما تكون مستعدًا، استدعِ [`~Trainer.train`] لبدء التدريب: + +```py +>>> trainer.train() # doctest: +SKIP +``` + + + +بالنسبة للمهام - مثل الترجمة أو التلخيص - التي تستخدم نموذج تسلسل إلى تسلسل، استخدم فئات [`Seq2SeqTrainer`] و [`Seq2SeqTrainingArguments`] بدلاً من ذلك. + + + +يمكنك تخصيص سلوك حلقة التدريب عن طريق إنشاء فئة فرعية من الطرق داخل [`Trainer`]. يسمح لك ذلك بتخصيص ميزات مثل دالة الخسارة، والمحسن، والمجدول. راجع مرجع [`Trainer`] للتعرف على الطرق التي يمكن إنشاء فئات فرعية منها. + +والطريقة الأخرى لتخصيص حلقة التدريب هي باستخدام [المستدعيات](./main_classes/callback). يمكنك استخدام المستدعيات للتكامل مع المكتبات الأخرى ومراقبة حلقة التدريب للإبلاغ عن التقدم أو إيقاف التدريب مبكرًا. لا تعدل المستدعيات أي شيء في حلقة التدريب نفسها. لتخصيص شيء مثل دالة الخسارة، تحتاج إلى إنشاء فئة فرعية من [`Trainer`] بدلاً من ذلك. + +## التدريب باستخدام TensorFlow + +جميع النماذج عبارة عن [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) قياسية، لذا يمكن تدريبها في TensorFlow باستخدام واجهة برمجة تطبيقات Keras. يوفر 🤗 Transformers طريقة [`~TFPreTrainedModel.prepare_tf_dataset`] لتحميل مجموعة البيانات الخاصة بك بسهولة كـ `tf.data.Dataset` حتى تتمكن من البدء في التدريب على الفور باستخدام دالتي `compile` و`fit` في Keras. + +1. ستبدأ بـ [`TFPreTrainedModel`] أو [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model): + + ```py + >>> from transformers import TFAutoModelForSequenceClassification + + >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +2. قم بتحميل فئة معالجة مسبقة مثل برنامج الترميز، أو معالج الصور، أو مستخرج الميزات، أو المعالج: + + ```py + >>> from transformers import AutoTokenizer + + >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") + ``` + +3. قم بإنشاء دالة لترميز مجموعة البيانات: + + ```py + >>> def tokenize_dataset(dataset): + ... return tokenizer(dataset["text"]) # doctest: +SKIP + ``` + +4. قم بتطبيق برنامج الترميز على مجموعة البيانات بأكملها باستخدام [`~datasets.Dataset.map`] ثم مرر مجموعة البيانات وبرنامج الترميز إلى [`~TFPreTrainedModel.prepare_tf_dataset`]. يمكنك أيضًا تغيير حجم الدفعة وخلط مجموعة البيانات هنا إذا أردت: + + ```py + >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP + >>> tf_dataset = model.prepare_tf_dataset( + ... dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer + ... ) # doctest: +SKIP + ``` + +5. عندما تكون مستعدًا، يمكنك استدعاء `compile` و`fit` لبدء التدريب. لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذا فأنت لست بحاجة إلى تحديد واحدة ما لم ترغب في ذلك: + + ```py + >>> from tensorflow.keras.optimizers import Adam + + >>> model.compile(optimizer='adam') # لا توجد وسيطة دالة الخسارة! + >>> model.fit(tf_dataset) # doctest: +SKIP + ``` + +## ماذا بعد؟ + +الآن بعد أن أكملت الجولة السريعة في 🤗 Transformers، راجع أدلتنا لمعرفة كيفية القيام بأشياء أكثر تحديدًا مثل كتابة نموذج مخصص، وضبط نموذج مسبق التدريب لمهمة معينة، وكيفية تدريب نموذج باستخدام نص برمجي. إذا كنت مهتمًا بمعرفة المزيد عن المفاهيم الأساسية لـ 🤗 Transformers، فاحصل على فنجان من القهوة واطلع على أدلة المفاهيم الخاصة بنا! diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/run_scripts.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/run_scripts.md new file mode 100644 index 0000000000000000000000000000000000000000..c7aea4eb9611b0a6a7c83baf539d46cf12295caf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/run_scripts.md @@ -0,0 +1,351 @@ +# التدريب باستخدام نص برمجى + +بالإضافة إلى دفاتر الملاحظات [notebooks](./notebooks) الخاصة بـ 🤗 Transformers، هناك أيضًا نصوص برمجية توضيحية تُظهر كيفية تدريب نموذج لمهمة باستخدام [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch) أو [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow) أو [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax). + +كما ستجد النصوص البرمجية التي استخدمناها في [مشاريع الأبحاث](https://github.com/huggingface/transformers-research-projects/) و [الأمثلة القديمة](https://github.com/huggingface/transformers/tree/main/examples/legacy) والتي ساهم بها المجتمع بشكل أساسي. هذه النصوص البرمجية غير مدعومة بشكل نشط وقد تتطلب إصدارًا محددًا من مكتبة 🤗 Transformers والذي من المحتمل أن يكون غير متوافق مع الإصدار الأحدث من المكتبة. + +لا يُتوقع أن تعمل النصوص البرمجية التوضيحية بشكل مباشر على كل مشكلة، وقد تحتاج إلى تكييف النص البرمجي مع المشكلة التي تحاول حلها. ولمساعدتك في ذلك، تعرض معظم النصوص البرمجية كيفية معالجة البيانات قبل التدريب بشكل كامل، مما يتيح لك تحريرها حسب الحاجة لحالتك الاستخدام. + +بالنسبة لأي ميزة ترغب في تنفيذها في نص برمجي توضيحي، يرجى مناقشتها في [المنتدى](https://discuss.huggingface.co/) أو في [قضية](https://github.com/huggingface/transformers/issues) قبل إرسال طلب سحب. وفي حين أننا نرحب بإصلاح الأخطاء، فمن غير المرجح أن نقوم بدمج طلب سحب الذي يضيف المزيد من الوظائف على حساب قابلية القراءة. + +سيوضح هذا الدليل كيفية تشغيل نص برمجي توضيحي للتدريب على التلخيص في [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) و [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization). يُتوقع أن تعمل جميع الأمثلة مع كلا الإطارين ما لم يُنص على خلاف ذلك. + +## الإعداد + +لتشغيل الإصدار الأحدث من النصوص البرمجية التوضيحية بنجاح، يجب عليك **تثبيت 🤗 Transformers من المصدر** في بيئة افتراضية جديدة: + +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +بالنسبة للإصدارات الأقدم من النصوص البرمجية التوضيحية، انقر فوق الزر أدناه: +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +بالنسبة للإصدارات الأقدم من النصوص البرمجية التوضيحية، انقر فوق الزر أدناه: + +
+ أمثلة للإصدارات الأقدم من 🤗 Transformers + +
+ +ثم قم بالتبديل إلى النسخة الحالية من 🤗 Transformers إلى إصدار محدد، مثل v3.5.1 على سبيل المثال: + +```bash +git checkout tags/v3.5.1 +``` + +بعد إعداد إصدار المكتبة الصحيح، انتقل إلى مجلد الأمثلة الذي تختاره وقم بتثبيت المتطلبات المحددة: + +```bash +pip install -r requirements.txt +``` + +## تشغيل نص برمجي + + + + +- يقوم النص البرمجي التوضيحي بتنزيل مجموعة بيانات ومعالجتها مسبقًا من مكتبة 🤗 [Datasets](https://huggingface.co/docs/datasets). +- ثم يقوم النص البرمجي بضبط نموذج بيانات دقيق باستخدام [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) على بنية تدعم الملخص. +- يوضح المثال التالي كيفية ضبط نموذج [T5-small](https://huggingface.co/google-t5/t5-small) على مجموعة بيانات [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). +- يتطلب نموذج T5 معامل `source_prefix` إضافية بسبب الطريقة التي تم تدريبه بها. يتيح هذا المطالبة لـ T5 معرفة أن هذه مهمة التلخيص. + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + + +- يقوم النص البرمجي التوضيحي بتنزيل مجموعة بيانات ومعالجتها مسبقًا من مكتبة 🤗 [Datasets](https://huggingface.co/docs/datasets/). +- ثم يقوم النص البرمجي بضبط نموذج بيانات دقيق باستخدام Keras على بنية تدعم الملخص. +- يوضح المثال التالي كيفية ضبط نموذج [T5-small](https://huggingface.co/google-t5/t5-small) على مجموعة بيانات [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). +- يتطلب نموذج T5 ماعمل `source_prefix` إضافية بسبب الطريقة التي تم تدريبه بها. يتيح هذا المطالبة لـ T5 معرفة أن هذه مهمة التلخيص. + +```bash +python examples/tensorflow/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## التدريب الموزع والدقة المختلطة + +يدعم [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) التدريب الموزع والدقة المختلطة، مما يعني أنه يمكنك أيضًا استخدامه في نص برمجي. لتمكين كلتا الميزتين: + +- أضف معامل `fp16` لتمكين الدقة المختلطة. +- قم بتعيين عدد وحدات معالجة الرسومات (GPUs) التي تريد استخدامها باستخدام حجة `nproc_per_node`. + +```bash +torchrun \ + --nproc_per_node 8 pytorch/summarization/run_summarization.py \ + --fp16 \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +تستخدم نصوص TensorFlow البرمجية استراتيجية [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) للتدريب الموزع، ولا تحتاج إلى إضافة أي معامﻻت إضافية إلى النص البرمجي التدريبي. سيستخدم نص TensorFlow البرمجي وحدات معالجة الرسومات (GPUs) متعددة بشكل افتراضي إذا كانت متوفرة. + +## تشغيل نص برمجي على وحدة معالجة الدقة الفائقة (TPU) + + + + +تُعد وحدات معالجة الدقة الفائقة (TPUs) مصممة خصيصًا لتسريع الأداء. يدعم PyTorch وحدات معالجة الدقة الفائقة (TPUs) مع [XLA](https://www.tensorflow.org/xla) مجمع الدقة الفائقة للتعلم العميق (راجع [هنا](https://github.com/pytorch/xla/blob/master/README.md) لمزيد من التفاصيل). لاستخدام وحدة معالجة الدقة الفائقة (TPU)، قم بتشغيل نص `xla_spawn.py` البرمجي واستخدم معامل `num_cores` لتعيين عدد وحدات معالجة الدقة الفائقة (TPU) التي تريد استخدامها. + +```bash +python xla_spawn.py --num_cores 8 \ + summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + + +تُعد وحدات معالجة الدقة الفائقة (TPUs) مصممة خصيصًا لتسريع الأداء. تستخدم نصوص TensorFlow البرمجية استراتيجية [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) للتدريب على وحدات معالجة الدقة الفائقة (TPUs). لاستخدام وحدة معالجة الدقة الفائقة (TPU)، قم بتمرير اسم مورد وحدة معالجة الدقة الفائقة (TPU) إلى حجة `tpu`. +```bash +python run_summarization.py \ + --tpu name_of_tpu_resource \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## تشغيل نص برمجي باستخدام 🤗 Accelerate + +🤗 [Accelerate](https://huggingface.co/docs/accelerate) هي مكتبة خاصة بـ PyTorch فقط توفر طريقة موحدة لتدريب نموذج على عدة أنواع من الإعدادات (الاعتماد على وحدة المعالجة المركزية (CPU) فقط، أو وحدات معالجة الرسومات (GPUs) المتعددة، أو وحدات معالجة الدقة الفائقة (TPUs)) مع الحفاظ على الرؤية الكاملة لحلقة تدريب PyTorch. تأكد من تثبيت 🤗 Accelerate إذا لم يكن لديك بالفعل: + +> ملاحظة: نظرًا لأن Accelerate في حالة تطوير سريع، يجب تثبيت إصدار Git من Accelerate لتشغيل النصوص البرمجية. +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +بدلاً من إستخدام النص البرمجي `run_summarization.py` يجب عليك استخدام النص البرمجي `run_summarization_no_trainer.py` . ستكون النصوص البرمجية المدعومة من 🤗 Accelerate لها ملف `task_no_trainer.py` في المجلد. ابدأ بتشغيل الأمر التالي لإنشاء وحفظ ملف تكوين: + +```bash +accelerate config +``` + +اختبر إعدادك للتأكد من أنه تم تكوينه بشكل صحيح: + +```bash +accelerate test +``` + +الآن أنت مستعد لبدء التدريب: + +```bash +accelerate launch run_summarization_no_trainer.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir ~/tmp/tst-summarization +``` + +## استخدام مجموعة بيانات مخصصة + +يدعم النص البرمجي للتلخيص مجموعة بيانات مخصصة طالما أنها ملف CSV أو JSON Line. عندما تستخدم مجموعة بياناتك الخاصة، تحتاج إلى تحديد العديد من المعلمات الإضافية: + +- `train_file` و`validation_file` يحددان مسار ملفات التدريب والتحقق الخاصة بك. +- `text_column` النص المدخل الذي سيتم تلخيصه. +- `summary_column` النص الملخص المستهدف الذي سيتم إخراجه. + +سيبدو النص البرمجي للتلخيص الذي يستخدم مجموعة بيانات مخصصة على النحو التالي: + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --train_file path_to_csv_or_jsonlines_file \ + --validation_file path_to_csv_or_jsonlines_file \ + --text_column text_column_name \ + --summary_column summary_column_name \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --overwrite_output_dir \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate +``` + +## اختبار البرنامج النصي + +من الجيد غالبًا تشغيل نصك البرمجي على عدد أقل من أمثلة مجموعة البيانات للتأكد من أن كل شيء يعمل كما هو متوقع قبل الالتزام بمجموعة بيانات كاملة والتي قد تستغرق ساعات لإكمالها. استخدم المعلمات التالية لتقليص مجموعة البيانات إلى عدد أقصى من العينات: + +- `max_train_samples` +- `max_eval_samples` +- `max_predict_samples` + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --max_train_samples 50 \ + --max_eval_samples 50 \ + --max_predict_samples 50 \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +لا تدعم جميع أمثلة النصوص البرمجية المعلمة `max_predict_samples`. إذا لم تكن متأكدًا مما إذا كان نصك البرمجي يدعم هذه المعلمة، فأضف معلمة `-h` للتحقق: + +```bash +examples/pytorch/summarization/run_summarization.py -h +``` + +## استئناف التدريب من نقطة تفتيش + +خيار آخر مفيد لتمكينه هو استئناف التدريب من نقطة تفتيش سابقة. سيضمن ذلك أنك تستطيع الاستمرار من حيث توقفت دون البدء من جديد إذا تم مقاطعة تدريبك. هناك طريقتان لاستئناف التدريب من نقطة تفتيش. + +تستخدم الطريقة الأولى المعلمة `output_dir previous_output_dir` لاستئناف التدريب من أحدث نقطة تفتيش مخزنة في `output_dir`. في هذه الحالة، يجب عليك إزالة `overwrite_output_dir`: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --output_dir previous_output_dir \ + --predict_with_generate +``` + +تستخدم الطريقة الثانية معلمة `resume_from_checkpoint path_to_specific_checkpoint` لاستئناف التدريب من مجلد نقطة تفتيش محددة. + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --resume_from_checkpoint path_to_specific_checkpoint \ + --predict_with_generate +``` + +## شارك نموذجك + +يمكن لجميع النصوص البرمجية رفع نموذجك النهائي إلى [مركز النماذج](https://huggingface.co/models). تأكد من تسجيل الدخول إلى Hugging Face قبل البدء: + +```bash +huggingface-cli login +``` + +ثم أضف المعلمة `push_to_hub` إلى النص البرمجي . ستقوم هذه المعلمة بإنشاء مستودع باستخدام اسم مستخدم Hugging Face واسم المجلد المحدد في `output_dir`. + +لإعطاء مستودعك اسمًا محددًا، استخدم المعلمة `push_to_hub_model_id` لإضافته. سيتم عرض المستودع تلقائيًا ضمن مساحة الاسم الخاصة بك. + +يوضح المثال التالي كيفية رفع نموذج باستخدام اسم مستودع محدد: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --push_to_hub \ + --push_to_hub_model_id finetuned-t5-cnn_dailymail \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/sagemaker.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/sagemaker.md new file mode 100644 index 0000000000000000000000000000000000000000..6bb53816baaaee483277076a54a530bfa2e9f278 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/sagemaker.md @@ -0,0 +1,8 @@ +# تشغيل التدريب على Amazon SageMaker + +تم نقل التوثيق إلى [hf.co/docs/sagemaker](https://huggingface.co/docs/sagemaker). وسيتم إزالة هذه الصفحة في الإصدار 5.0 من برنامج Transformers. + +### جدول المحتويات + +- [تدريب نماذج Hugging Face على Amazon SageMaker باستخدام SageMaker Python SDK](https://huggingface.co/docs/sagemaker/train) +- [نشر نماذج Hugging Face على Amazon SageMaker باستخدام SageMaker Python SDK](https://huggingface.co/docs/sagemaker/inference) \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/serialization.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/serialization.md new file mode 100644 index 0000000000000000000000000000000000000000..6f437dea0681ba787b3f62aafd0f5ee723388f63 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/serialization.md @@ -0,0 +1,170 @@ +# التصدير إلى ONNX + +غالباً ما يتطلب نشر نماذج 🤗 Transformers في بيئات الإنتاج أو يمكن أن يستفيد من تصدير النماذج إلى تنسيق تسلسلي يُمكن تحميله وتنفيذه على أجهزة وبرامج تشغيل مُتخصصة. + +🤗 Optimum هو امتداد لـ Transformers يمكّن من تصدير النماذج من PyTorch أو TensorFlow إلى تنسيقات مُتسلسلة مثل ONNX و TFLite من خلال وحدة `exporters` الخاصة به. يوفر 🤗 Optimum أيضًا مجموعة من أدوات تحسين الأداء لتدريب النماذج وتشغيلها على أجهزة مستهدفة بكفاءة قصوى. + +يوضح هذا الدليل كيفية تصدير نماذج 🤗 Transformers إلى ONNX باستخدام 🤗 Optimum، وللحصول على الدليل الخاص بتصدير النماذج إلى TFLite، يُرجى الرجوع إلى صفحة [التصدير إلى TFLite](tflite). + +## التصدير إلى ONNX + +مجمد [ONNX (Open Neural Network Exchange)](http://onnx.ai) هو معيار مفتوح يُحدد مجموعة مشتركة من العوامل وتنسيق ملف مشترك لتمثيل نماذج التعلم العميق في مجموعة متنوعة واسعة من الأطر، بما في ذلك PyTorch وTensorFlow. عندما يتم تصدير نموذج إلى تنسيق ONNX، يتم استخدام هذه المشغلات لبناء رسم بياني حاسوبي (يُطلق عليه غالبًا اسم _تمثيل وسيط_) والذي يمثل تدفق البيانات عبر الشبكة العصبية. + +من خلال عرض رسم بياني بعوامل وأنواع بيانات معيارية، يُسهّل ONNX التبديل بين الأطر. على سبيل المثال، يُمكن تصدير نموذج مدرب في PyTorch إلى تنسيق ONNX ثم استيراده في TensorFlow (والعكس صحيح). + +بمجرد التصدير إلى تنسيق ONNX، يُمكن: + +- تحسين النموذج للاستدلال عبر تقنيات مثل [تحسين الرسم البياني](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/optimization) و [التكميم](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/quantization). +- تشغيله باستخدام ONNX Runtime عبر فئات [`ORTModelForXXX`](https://huggingface.co/docs/optimum/onnxruntime/package_reference/modeling_ort)، والتي تتبع نفس واجهة برمجة التطبيقات (API) لـ `AutoModel` التي اعتدت عليها في 🤗 Transformers. +- تشغيله باستخدام [قنوات معالجة الاستدلال مُحسّنة](https://huggingface.co/docs/optimum/main/en/onnxruntime/usage_guides/pipelines)، والتي لها نفس واجهة برمجة التطبيقات (API) مثل وظيفة [`pipeline`] في 🤗 Transformers. + +يوفر 🤗 Optimum دعمًا لتصدير ONNX من خلال الاستفادة من كائنات التكوين. تأتي كائنات التكوين هذه جاهزة لعدد من معماريات النماذج، وقد تم تصميمها لتكون قابلة للتوسعة بسهولة إلى معماريات أخرى. + +للاطلاع على قائمة بالتكوينات الجاهزة، يُرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/overview). + +هناك طريقتان لتصدير نموذج 🤗 Transformers إلى ONNX، نعرض هنا كليهما: + +- التصدير باستخدام 🤗 Optimum عبر واجهة سطر الأوامر (CLI). +- التصدير باستخدام 🤗 Optimum مع `optimum.onnxruntime`. + +### تصدير نموذج 🤗 Transformers إلى ONNX باستخدام واجهة سطر الأوامر + +لتصدير نموذج 🤗 Transformers إلى ONNX، قم أولاً بتثبيت اعتماد إضافي: + +```bash +pip install optimum[exporters] +``` + +للاطلاع على جميع المعامﻻت المتاحة، يرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli)، أو عرض المساعدة في سطر الأوامر: + +```bash +optimum-cli export onnx --help +``` +```bash +optimum-cli export onnx --help +``` + +لتصدير نقطة تفتيش نموذج من 🤗 Hub، على سبيل المثال، `distilbert/distilbert-base-uncased-distilled-squad`، قم بتشغيل الأمر التالي: + +```bash +optimum-cli export onnx --model distilbert/distilbert-base-uncased-distilled-squad distilbert_base_uncased_squad_onnx/ +``` + +يجب أن تشاهد السجلات التي تشير إلى التقدم المحرز وتظهر المكان الذي تم فيه حفظ ملف `model.onnx` الناتج، مثل هذا: + +```bash +Validating ONNX model distilbert_base_uncased_squad_onnx/model.onnx... + -[✓] ONNX model output names match reference model (start_logits, end_logits) + - Validating ONNX Model output "start_logits": + -[✓] (2, 16) matches (2, 16) + -[✓] all values close (atol: 0.0001) + - Validating ONNX Model output "end_logits": + -[✓] (2, 16) matches (2, 16) + -[✓] all values close (atol: 0.0001) +The ONNX export succeeded and the exported model was saved at: distilbert_base_uncased_squad_onnx +``` + +يوضح المثال أعلاه تصدير نقطة تفتيش من 🤗 Hub. عند تصدير نموذج محلي، تأكد أولاً من حفظ ملفات أوزان النموذج ومحول الرموز في نفس الدليل (`local_path`). عند استخدام واجهة سطر الأوامر، قم بتمرير `local_path` إلى وسيط `model` بدلاً من اسم نقطة التفتيش على 🤗 Hub وقدم وسيط `--task`. يمكنك مراجعة قائمة المهام المدعومة في [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/task_manager). إذا لم يتم توفير وسيط `task`، فسيتم تعيينه افتراضيًا إلى هندسة النموذج دون أي رأس محدد للمهمة. + +```bash +optimum-cli export onnx --model local_path --task question-answering distilbert_base_uncased_squad_onnx/ +``` + +يمكن بعد ذلك تشغيل ملف `model.onnx` الناتج على أحد [المسرعات](https://onnx.ai/supported-tools.html#deployModel) العديدة التي تدعم معيار ONNX. على سبيل المثال، يمكننا تحميل النموذج وتشغيله باستخدام [ONNX Runtime](https://onnxruntime.ai/) كما يلي: + +```python +>>> from transformers import AutoTokenizer +>>> from optimum.onnxruntime import ORTModelForQuestionAnswering + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert_base_uncased_squad_onnx") +>>> model = ORTModelForQuestionAnswering.from_pretrained("distilbert_base_uncased_squad_onnx") +>>> inputs = tokenizer("What am I using?", "Using DistilBERT with ONNX Runtime!", return_tensors="pt") +>>> outputs = model(**inputs) +``` + +تكون العملية مماثلة بالنسبة إلى نقاط تفتيش TensorFlow على Hub. على سبيل المثال، إليك كيفية تصدير نقطة تفتيش TensorFlow نقية من [منظمة Keras](https://huggingface.co/keras-io): + +```bash +optimum-cli export onnx --model keras-io/transformers-qa distilbert_base_cased_squad_onnx/ +``` + +### تصدير نموذج 🤗 Transformers إلى ONNX باستخدام `optimum.onnxruntime` + +كبديل لواجهة سطر الأوامر، يُمكنك تصدير نموذج 🤗 Transformers إلى ONNX برمجيًا كما يلي: + +```python +>>> from optimum.onnxruntime import ORTModelForSequenceClassification +>>> from transformers import AutoTokenizer + +>>> model_checkpoint = "distilbert_base_uncased_squad" +>>> save_directory = "onnx/" + +>>> # تحميل نموذج من transformers وتصديره إلى ONNX +>>> ort_model = ORTModelForSequenceClassification.from_pretrained(model_checkpoint, export=True) +>>> tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) + +>>> # حفظ نموذج onnx ومجزىء النصوص +>>> ort_model.save_pretrained(save_directory) +>>> tokenizer.save_pretrained(save_directory) +``` + +### تصدير نموذج لهندسة غير مدعومة + +إذا كنت ترغب في المساهمة من خلال إضافة دعم لنموذج لا يُمكن تصديره حاليًا، فيجب عليك أولاً التحقق مما إذا كان مدعومًا في [`optimum.exporters.onnx`](https://huggingface.co/docs/optimum/exporters/onnx/overview)، وإذا لم يكن مدعومًا، [فيمكنك المساهمة في 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/contribute) مُباشرةً. + +### تصدير نموذج باستخدام `transformers.onnx` + + + +لم يعد يتم دعم `transformers.onnx` يُرجى تصدير النماذج باستخدام 🤗 Optimum كما هو موضح أعلاه. سيتم إزالة هذا القسم في الإصدارات القادمة. + + + +لتصدير نموذج 🤗 Transformers إلى ONNX باستخدام `transformers.onnx`، ثبّت التبعيات الإضافية: + +```bash +pip install transformers[onnx] +``` + +استخدم حزمة `transformers.onnx` كنموذج Python لتصدير نقطة حفظ باستخدام تكوين جاهز: + +```bash +python -m transformers.onnx --model=distilbert/distilbert-base-uncased onnx/ +``` + +يُصدّر هذا رسمًا بيانيًا ONNX لنقطة الحفظ المُحددة بواسطة وسيطة `--model`. مرر أي نقطة حفظ على 🤗 Hub أو نقطة حفظ مُخزنة محليًا. +يُمكن بعد ذلك تشغيل ملف `model.onnx` الناتج على أحد المُسرعات العديدة التي تدعم معيار ONNX. على سبيل المثال، قم بتحميل وتشغيل النموذج باستخدام ONNX Runtime كما يلي: + +```python +>>> from transformers import AutoTokenizer +>>> from onnxruntime import InferenceSession + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +>>> session = InferenceSession("onnx/model.onnx") +>>> # يتوقع ONNX Runtime مصفوفات NumPy كمدخلات +>>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np") +>>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs)) +``` + +يُمكن الحصول على أسماء المخرجات المطلوبة (مثل `["last_hidden_state"]`) من خلال إلقاء نظرة على تكوين ONNX لكل نموذج. على سبيل المثال، بالنسبة لـ DistilBERT، لدينا: + +```python +>>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig + +>>> config = DistilBertConfig() +>>> onnx_config = DistilBertOnnxConfig(config) +>>> print(list(onnx_config.outputs.keys())) +["last_hidden_state"] +``` + +العمليات مُتطابقة لنقاط الحفظ TensorFlow على Hub. على سبيل المثال، صدّر نقطة حفظ TensorFlow خالصة كما يلي: + +```bash +python -m transformers.onnx --model=keras-io/transformers-qa onnx/ +``` + +لتصدير نموذج مُخزن محليًا، احفظ أوزان النموذج ومجزىء اللغوى في نفس الدليل (على سبيل المثال `local-pt-checkpoint`)، ثم قم بتصديره إلى ONNX عن طريق توجيه وسيط `--model` لحزمة `transformers.onnx` إلى الدليل المطلوب: + +```bash +python -m transformers.onnx --model=local-pt-checkpoint onnx/ +``` \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/task_summary.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/task_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..d6a9d1477e10fce12c5bcf2bda9c92635b4cd985 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/task_summary.md @@ -0,0 +1,323 @@ +# ما الذي تستطيع مكتبة 🤗 Transformers القيام به؟ + +مكتبة 🤗 Transformers هي مجموعة من النماذج المُدرّبة مسبقًا الأفضل في فئتها لمهام معالجة اللغة الطبيعية (NLP)، ورؤية الحاسوب، ومعالجة الصوت والكلام. لا تحتوي المكتبة فقط على نماذج المحولات (Transformer) فحسب، بل تشمل أيضًا نماذج أخرى لا تعتمد على المحولات مثل الشبكات العصبية التلافيفية الحديثة لمهام رؤية الحاسوب. إذا نظرت إلى بعض المنتجات الاستهلاكية الأكثر شيوعًا اليوم، مثل الهواتف الذكية والتطبيقات وأجهزة التلفاز، فمن المحتمل أن تقف وراءها تقنية ما من تقنيات التعلم العميق. هل تريد إزالة جسم من خلفية صورة التقطتها بهاتفك الذكي؟ هذا مثال على مهمة التجزئة البانورامية (Panoptic Segmentation) ( لا تقلق إذا لم تفهم معناها بعد، فسوف نشرحها في الأقسام التالية!). + +توفر هذه الصفحة نظرة عامة على مختلف مهام الكلام والصوت ورؤية الحاسوب ومعالجة اللغات الطبيعية المختلفة التي يمكن حلها باستخدام مكتبة 🤗 Transformers في ثلاثة أسطر فقط من التعليمات البرمجية! + +## الصوت + +تختلف مهام معالجة الصوت والكلام قليلاً عن باقي الوسائط، ويرجع ذلك ببشكل أساسي لأن الصوت كمدخل هو إشارة متصلة. على عكس النص، لا يمكن تقسيم الموجة الصوتية الخام بشكل مرتب في أجزاء منفصلة بالطريقة التي يمكن بها تقسيم الجملة إلى كلمات. وللتغلب على هذا، يتم عادةً أخذ عينات من الإشارة الصوتية الخام على فترات زمنية منتظمة. كلما زاد عدد العينات التي تؤخذ في فترة زمنية معينة، ارتفع معدل أخذ العينات (معدل التردد)، وصار الصوت أقرب إلى مصدر الصوت الأصلي. + +قامت الطرق السابقة بمعالجة الصوت لاستخراج الميزات المفيدة منه. أصبح من الشائع الآن البدء بمهام معالجة الصوت والكلام عن طريق تغذية شكل الموجة الصوتية الخام مباشرة في مشفر الميزات (Feature Encoder) لاستخراج تمثيل صوتي له. وهذا يبسط خطوة المعالجة المسبقة ويسمح للنموذج بتعلم أهم الميزات. + +### تصنيف الصوت + +تصنيف الصوت (Audio Classification) هو مهمة يتم فيها تصنيف بيانات الصوت الصوت من مجموعة محددة مسبقًا من الفئات. إنه فئة واسعة تضم العديد من التطبيقات المحددة، والتي تشمل: + +* تصنيف المشهد الصوتي: وضع علامة على الصوت باستخدام تسمية المشهد ("المكتب"، "الشاطئ"، "الملعب") +* اكتشاف الأحداث الصوتية: وضع علامة على الصوت باستخدام تسمية حدث صوتي ("بوق السيارة"، "صوت الحوت"، "كسر زجاج") +* الوسم: وصنيف صوت يحتوي على أصوات متعددة (أصوات الطيور، وتحديد هوية المتحدث في اجتماع) +* تصنيف الموسيقى: وضع علامة على الموسيقى بتسمية النوع ("ميتال"، "هيب هوب"، "كانتري") + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="audio-classification", model="superb/hubert-base-superb-er") +>>> preds = classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4532, 'label': 'hap'}, + {'score': 0.3622, 'label': 'sad'}, + {'score': 0.0943, 'label': 'neu'}, + {'score': 0.0903, 'label': 'ang'}] +``` + +### التعرف التلقائي على الكلام + +يقوم التعرف التلقائي على الكلام (ASR) هو عملية تحويل الكلام إلى نص. إنه أحد أكثر المهام الصوتية شيوعًا ويرجع ذلك جزئيًا إلى أن الكلام وسيلة طبيعية للتواصل البشري. واليوم، يتم تضمين أنظمة ASR في منتجات التقنية "الذكية" مثل مكبرات الصوت والهواتف والسيارات. يمكننا أن نطلب من مساعدينا الافتراضيين تشغيل الموسيقى، وضبط التذكيرات، وإخبارنا بأحوال الطقس. +ولكن أحد التحديات الرئيسية التي ساعدت نماذج المحولات (Transformer) في التغلب عليها هو التعامل مع اللغات منخفضة الموارد. فمن خلال التدريب المسبق على كميات كبيرة من بيانات الصوتية، يُمكن ضبط النموذج بدقة (Fine-tuning) باستخدام ساعة واحدة فقط من بيانات الكلام المُوسم في لغة منخفضة الموارد إلى نتائج عالية الجودة مقارنة بأنظمة ASR السابقة التي تم تدريبها على بيانات موسومة أكثر بـ 100 مرة. + +```py +>>> from transformers import pipeline + +>>> transcriber = pipeline(task="automatic-speech-recognition", model="openai/whisper-small") +>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac") +{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'} +``` + +## رؤية الحاسب + +كانت إحدى أوائل مهام رؤية الحاسب وأنجحها هى التعرف على صور أرقام الرموز البريدية باستخدام [شبكة عصبية تلافيفية (CNN)](glossary#convolution). تتكون الصورة من وحدات بيكسل، ولكل بكسل قيمة رقمية. وهذا يجعل من السهل تمثيل صورة كمصفوفة من قيم البكسل. يصف كل مزيج معين من قيم البكسل ألوان الصورة. + +هناك طريقتان عامتان يمكن من خلالهما حل مهام رؤية الحاسب: + +1. استخدام الالتفافات (Convolutions) لتعلم الميزات الهرمية للصورة بدءًا من الميزات منخفضة المستوى وصولًا إلى الأشياء المجردة عالية المستوى. +2. تقسيم الصورة إلى أجزاء واستخدام نموذج المحولات (Transformer) ليتعلم تدريجياً كيف ترتبط كل جزء صورة ببعضها البعض لتشكيل صورة. على عكس النهج ا التصاعدي (Bottom-Up) الذي تفضله الشبكات العصبية التلافيفية CNN، هذا يشبه إلى حد ما البدء بصورة ضبابية ثم جعلها أوضح تدريجيًا. + +### تصنيف الصور + +يقوم تصنيف الصور (Image Classification) بوضع علامة على صورة كاملة من مجموعة محددة مسبقًا من الفئات. مثل معظم مهام التصنيف، هناك العديد من التطبيقات العملية لتصنيف الصور، والتي تشمل: + +* الرعاية الصحية: تصنيف الصور الطبية للكشف عن الأمراض أو مراقبة صحة المريض +* البيئة: تصنيف صور الأقمار الصناعية لرصد إزالة الغابات، أو إبلاغ إدارة الأراضي البرية أو اكتشاف حرائق الغابات +* الزراعة: تصنيفر المحاصيل لمراقبة صحة النبات أو صور الأقمار الصناعية لمراقبة استخدام الأراضي +* علم البيئة: تصنيف صور الأنواع الحيوانية أو النباتية لرصد أعداد الكائنات الحية أو تتبع الأنواع المهددة بالانقراض + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="image-classification") +>>> preds = classifier( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> print(*preds, sep="\n") +{'score': 0.4335, 'label': 'lynx, catamount'} +{'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'} +{'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'} +{'score': 0.0239, 'label': 'Egyptian cat'} +{'score': 0.0229, 'label': 'tiger cat'} +``` + +### كشف الأجسام + +على عكس تصنيف الصور، يقوم كشف الأجسام (Object Detection) بتحديد عدة أجسام داخل صورة ومواضع هذه الأجسام في صورة (يحددها مربع الإحاطة). بعض تطبيقات كشف الأجسام تشمل: + +* المركبات ذاتية القيادة: اكتشاف أجسام المرورية اليومية مثل المركبات الأخرى والمشاة وإشارات المرور +* الاستشعار عن بُعد: مراقبة الكوارث، والتخطيط الحضري، والتنبؤ بالطقس +* اكتشاف العيوب: اكتشاف الشقوق أو الأضرار الهيكلية في المباني، وعيوب التصنيع + +```py +>>> from transformers import pipeline + +>>> detector = pipeline(task="object-detection") +>>> preds = detector( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"], "box": pred["box"]} for pred in preds] +>>> preds +[{'score': 0.9865, + 'label': 'cat', + 'box': {'xmin': 178, 'ymin': 154, 'xmax': 882, 'ymax': 598}}] +``` + +### تجزئة الصور + +تجزئة الصورة (Image Segmentation) هي مهمة على مستوى البكسل تقوم بتخصيص كل بكسل في صورة لفئة معينة. إنه يختلف عن كشف الأجسام، والذي يستخدم مربعات الإحاطة (Bounding Boxes) لتصنيف والتنبؤ بالأجسام في الصورة لأن التجزئة أكثر دقة. يمكن لتجزئة الصور اكتشاف الأجسام على مستوى البكسل. هناك عدة أنواع من تجزئة الصور: + +* تجزئة مثيلات (Instance Segmentation): بالإضافة إلى تصنيف فئة كائن، فإنها تُصنّف أيضًا كل مثيل (Instance) مميز لكائن ("الكلب-1"، "الكلب-2") +* التجزئة البانورامية (Panoptic Segmentation): مزيج من التجزئة الدلالية (Semantic Segmentation) وتجزئة المثيلات؛ فهو تُصنّف كل بكسل مع فئة دلالية **و** كل مثيل مميز لكائن + +تُعد مهام تجزئة الصور مفيدة في المركبات ذاتية القيادة على إنشاء خريطة على مستوى البكسل للعالم من حولها حتى تتمكن من التنقل بأمان حول المشاة والمركبات الأخرى. كما أنها مفيدة للتصوير الطبي، حيث يمكن للدقة العالية لهذ المهمة أن تساعد في تحديد الخلايا غير الطبيعية أو خصائص الأعضاء. يمكن أيضًا استخدام تجزئة الصور في التجارة الإلكترونية لتجربة الملابس افتراضيًا أو إنشاء تجارب الواقع المُعزز من خلال تراكب الأجسام في العالم الحقيقي من خلال الكاميرا الهاتف الخاصة بك. + +```py +>>> from transformers import pipeline + +>>> segmenter = pipeline(task="image-segmentation") +>>> preds = segmenter( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> print(*preds, sep="\n") +{'score': 0.9879, 'label': 'LABEL_184'} +{'score': 0.9973, 'label': 'snow'} +{'score': 0.9972, 'label': 'cat'} +``` + +### تقدير العمق + +يقوم تقدير العمق (Depth Estimation) بالتنبؤ بمسافة كل بكسل في صورة من الكاميرا. تُعد هذه المهمة لرؤية الحاسب هذه مهمة بشكل خاص لفهم وإعادة بناء المشهد. فعلى سبيل المثال، في السيارات ذاتية القيادة، تحتاج المركبات إلى فهم مدى بُعد الأجسام مثل المشاة ولافتات المرور والمركبات الأخرى لتجنب العقبات والاصطدامات. تساعد معلومات العمق أيضًا في بناء التمثيلات ثلاثية الأبعاد من الصور ثنائية الأبعاد ويمكن استخدامها لإنشاء تمثيلات ثلاثية الأبعاد عالية الجودة للهياكل البيولوجية أو المباني. + +هناك نهجان لتقدير العمق: + +* التصوير المجسم (Stereo): يتم تقدير العمق عن طريق مقارنة صورتين لنفس الصورة من زوايا مختلفة قليلاً. +* التصوير الأحادي (Monocular): يتم تقدير العمق من صورة واحدة. + +```py +>>> from transformers import pipeline + +>>> depth_estimator = pipeline(task="depth-estimation") +>>> preds = depth_estimator( +... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +``` + +## معالجة اللغات الطبيعية + +تُعد مهام معالجة اللغة الطبيعية (NLP) من بين أكثر أنواع المهام شيوعًا نظرًا لأن النص هو وسيلة طبيعية لنا للتواصل. ولكي يتمكن النموذج من فهم النص، يجب أولًا تحويله إلى صيغة رقمية. وهذا يعني تقسيم سلسلة النص إلى كلمات أو مقاطع كلمات منفصلة (رموز - Tokens)، ثم تحويل هذه الرموز إلى أرقام. ونتيجة لذلك، يمكنك تمثيل سلسلة من النص كتسلسل من الأرقام، وبمجرد حصولك على تسلسل من الأرقام، يمكن إدخاله إلى نموذج لحل جميع أنواع مهام معالجة اللغة الطبيعية! + +### تصنيف النصوص + +تمامًا مثل مهام التصنيف في أي مجال آخر، يقوم تصنيف النصوص (Text Classification) بتصنيف سلسلة نصية يمكن أن تكون جملة أو فقرة أو مستند) إلى فئة محددة مسبقًا. هناك العديد من التطبيقات العملية لتصنيف النصوص، والتي تشمل: + +* تحليل المشاعر (Sentiment Analysis): تصنيف النص وفقًا لمعيار معين مثل `الإيجابية` أو `السلبية` والتي يمكن أن تُعلم وتدعم عملية صنع القرار في مجالات مثل السياسة والتمويل والتسويق +* تصنيف المحتوى (Content Classification): تصنيف النص وفقًا لبعض الموضوعات للمساعدة في تنظيم وتصفية المعلومات في الأخبار وموجزات الوسائط الاجتماعية (`الطقس`، `الرياضة`، `التمويل`، إلخ). + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="sentiment-analysis") +>>> preds = classifier("Hugging Face is the best thing since sliced bread!") +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.9991, 'label': 'POSITIVE'}] +``` + +### تصنيف الرموز + +في أي مهمة من مهام معالجة اللغة الطبيعية NLP، تتم معالجة النص مسبقًا عن طريق تقسيمه إلى كلمات أو مقاطع كلمات فردية تُعرف باسم [الرموز](glossary#token). يقوم تصنيف الرموز (Token Classification) بتخصيص تصنيف لكل رمز من مجموعة محددة مسبقًا من التصنيفات. + +هناك نوعان شائعان من تصنيف الرموز: + +* التعرف على الكيانات المسماة (NER): تصنيف الرموز وفقًا لفئة الكيان مثل المنظمة أو الشخص أو الموقع أو التاريخ. يعد NER شائعًا بشكل خاص في الإعدادات الطبية الحيوية، حيث يُمكنه تصنيف الجينات والبروتينات وأسماء الأدوية. +* ترميز الأجزاء اللغوية (POS): تصنيف الرموز وفقًا للدورها النحوي مثل الاسم أو الفعل أو الصفة. POS مفيد لمساعدة أنظمة الترجمة على فهم كيفية اختلاف كلمتين متطابقتين نحويًا (مثل كلمة "عَلَمَ" كاسم و "عَلِمَ" كفعل). + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline(task="ner") +>>> preds = classifier("Hugging Face is a French company based in New York City.") +>>> preds = [ +... { +... "entity": pred["entity"], +... "score": round(pred["score"], 4), +... "index": pred["index"], +... "word": pred["word"], +... "start": pred["start"], +... "end": pred["end"], +... } +... for pred in preds +... ] +>>> print(*preds, sep="\n") +{'entity': 'I-ORG', 'score': 0.9968, 'index': 1, 'word': 'Hu', 'start': 0, 'end': 2} +{'entity': 'I-ORG', 'score': 0.9293, 'index': 2, 'word': '##gging', 'start': 2, 'end': 7} +{'entity': 'I-ORG', 'score': 0.9763, 'index': 3, 'word': 'Face', 'start': 8, 'end': 12} +{'entity': 'I-MISC', 'score': 0.9983, 'index': 6, 'word': 'French', 'start': 18, 'end': 24} +{'entity': 'I-LOC', 'score': 0.999, 'index': 10, 'word': 'New', 'start': 42, 'end': 45} +{'entity': 'I-LOC', 'score': 0.9987, 'index': 11, 'word': 'York', 'start': 46, 'end': 50} +{'entity': 'I-LOC', 'score': 0.9992, 'index': 12, 'word': 'City', 'start': 51, 'end': 55} +``` +### الإجابة على الأسئلة + +تُعدّ مهمة الإجابة عن الأسئلة (Question Answering) مهمة أخرى على مستوى الرموز (Token-Level) تُرجع إجابة لسؤال ما، وقد تعتمد هذه الإجابة على سياق (في النطاق المفتوح - Open-Domain) أو لا تعتمد على سياق (في النطاق المغلق - Closed-Domain). تحدث هذه المهمة عندما نسأل مساعدًا افتراضيًا عن شيء ما، مثل معرفة ما إذا كان مطعمٌ ما مفتوحًا. يمكن أن تُقدّم هذه المهمة أيضًا دعمًا للعملاء أو دعمًا تقنيًا، كما تُساعد محركات البحث في استرجاع المعلومات ذات الصلة التي نبحث عنها. + +هناك نوعان شائعان من الإجابة على الأسئلة: + +* الاستخراجية (Extractive): بالنظر إلى سؤال وسياق مُعيّن، فإن الإجابة هي مقطع نصيّ مُستخرج من السياق الذي يُحلّله النموذج. +* التجريدية (Abstractive): بالنظر إلى سؤال وسياق مُعيّن، يتم إنشاء الإجابة من السياق؛ يتعامل نهج [`Text2TextGenerationPipeline`] مع هذا النهج بدلاً من [`QuestionAnsweringPipeline`] الموضح أدناه + + +```py +>>> from transformers import pipeline + +>>> question_answerer = pipeline(task="question-answering") +>>> preds = question_answerer( +... question="What is the name of the repository?", +... context="The name of the repository is huggingface/transformers", +... ) +>>> print( +... f"score: {round(preds['score'], 4)}, start: {preds['start']}, end: {preds['end']}, answer: {preds['answer']}" +... ) +score: 0.9327, start: 30, end: 54, answer: huggingface/transformers +``` + +### التلخيص + +ينشئ التلخيص (Summarization) نسخة مختصرة من نص طويل مع محاولة الحفاظ على معظم معنى النص الأصلي. التلخيص هو مهمة تسلسل إلى تسلسل(Sequence-to-Sequence)؛؛ فهو تُنتج تسلسلًا نصيًا أقصر من النص المُدخل. هناك الكثير من المستندات الطويلة التي يمكن تلخيصها لمساعدة القراء على فهم النقاط الرئيسية بسرعة. مشاريع القوانين والوثائق القانونية والمالية وبراءات الاختراع والأوراق العلمية هي مجرد أمثلة قليلة للوثائق التي يمكن تلخيصها لتوفير وقت القراء وخدمة كمساعد للقراءة. + +مثل الإجابة على الأسئلة، هناك نوعان من التلخيص: + +* الاستخراجية (Extractive): تحديد واستخراج أهم الجمل من النص الأصلي +* التجريدي (Abstractive): إنشاء ملخص مستهدف (الذي قد يتضمن كلمات جديدة غير موجودة في النص الأصلي) انطلاقًا من النص الأصلي؛ يستخدم نهج التلخيص التجريدي [`SummarizationPipeline`] + +```py +>>> from transformers import pipeline + +>>> summarizer = pipeline(task="summarization") +>>> summarizer( +... "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention. For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles." +... ) +[{'summary_text': ' The Transformer is the first sequence transduction model based entirely on attention . It replaces the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention . For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers .'}] +``` + +### الترجمة + +تحوّل الترجمة تسلسل نص بلغة إلى لغة أخرى. من المهم مساعدة الأشخاص من خلفيات مختلفة على التواصل مع بعضهم البعض، ومساعدة المحتوى على الوصول إلى جمهور أوسع، وحتى أن يكون أداة تعليمية لمساعدة الأشخاص على تعلم لغة جديدة. إلى جانب التلخيص، تعد الترجمة مهمة من نوع تسلسل إلى تسلسل، حيث يتلقى النموذج تسلسلًا مُدخلًا ويُعيد تسلسلًا مُخرَجًا مُستهدفًا. + +في الأيام الأولى، كانت نماذج الترجمة في الغالب أحادية اللغة، ولكن مؤخرًا، كان هناك اهتمام متزايد بالنماذج متعددة اللغات التي يمكنها الترجمة بين العديد من أزواج اللغات. + +```py +>>> from transformers import pipeline + +>>> text = "translate English to French: Hugging Face is a community-based open-source platform for machine learning." +>>> translator = pipeline(task="translation", model="google-t5/t5-small") +>>> translator(text) +[{'translation_text': "Hugging Face est une tribune communautaire de l'apprentissage des machines."}] +``` + +### نمذجة اللغة + +نمذجة اللغة (Language Modeling) هي مهمة التنبؤ بالكلمة التالية في تسلسل نصي. لقد أصبح مهمة NLP شائعة للغاية لأن النموذج اللغوي المسبق التدريب يمكن أن يتم ضبطه بشكل دقيق للعديد من مهام الأخرى. في الآونة الأخيرة، كان هناك الكثير من الاهتمام بنماذج اللغة الكبيرة (LLMs) التي توضح التعلم من الصفر أو من عدد قليل من الأمثلة (Zero-shot or Few-shot Learning). وهذا يعني أن النموذج يمكنه حل المهام التي لم يتم تدريبه عليها بشكل صريح! يمكن استخدام نماذج اللغة لإنشاء نص سلس ومقنع، على الرغم من أنه يجب أن تكون حذرًا لأن النص قد لا يكون دائمًا دقيقًا. + +هناك نوعان من نمذجة اللغة: + +* السببية(Causal): هدف النموذج هو التنبؤ بالرمز (Token) التالي في التسلسل، ويتم إخفاء الرموز المستقبلية (Masking). + +```py +>>> from transformers import pipeline + +>>> prompt = "Hugging Face is a community-based open-source platform for machine learning." +>>> generator = pipeline(task="text-generation") +>>> generator(prompt) # doctest: +SKIP +``` + +* المقنّع (Masked): هدف النموذج هو التنبؤ برمز مُخفيّ ضمن التسلسل مع الوصول الكامل إلى الرموز الأخرى في التسلسل + +```py +>>> text = "Hugging Face is a community-based open-source for machine learning." +>>> fill_mask = pipeline(task="fill-mask") +>>> preds = fill_mask(text, top_k=1) +>>> preds = [ +... { +... "score": round(pred["score"], 4), +... "token": pred["token"], +... "token_str": pred["token_str"], +... "sequence": pred["sequence"], +... } +... for pred in preds +... ] +>>> preds +[{'score': 0.2236, + 'token': 1761, + 'token_str': ' platform', + 'sequence': 'Hugging Face is a community-based open-source platform for machine learning.'}] +``` + +## متعدد الوسائط: + +تتطلب المهام متعددة الوسائط (Multimodal) من النموذج معالجة وسائط بيانات متعددة (نص أو صورة أو صوت أو فيديو) لحل مشكلة معينة. يعد وصف الصورة (Image Captioning) مثالاً على مهمة متعددة الوسائط حيث يأخذ النموذج صورة كمدخل وينتج تسلسل نصيًا يصف الصورة أو بعض خصائصها. + +على الرغم من أن النماذج متعددة الوسائط تعمل مع أنواع أو وسائط بيانات مختلفة، إلا أن خطوات المعالجة المسبقة تساعد النموذج داخليًا على تحويل جميع أنواع البيانات إلى متجهات تضمين (Embeddings) (متجهات أو قوائم من الأرقام التي تحتوي على معلومات ذات معنى حول البيانات). بالنسبة لمهمة مثل وصف الصورة، يتعلم النموذج العلاقات بين متجهات تضمين الصور ومتجهات تضمين النص. + +### الإجابة على أسئلة المستندات: + +الإجابة على أسئلة المستندات (Document Question Answering) هي مهمة تقوم بالإجابة على أسئلة اللغة الطبيعية من مستند مُعطى. على عكس مهمة الإجابة على الأسئلة على مستوى الرموز (Token-Level) التي تأخذ نصًا كمدخل، فإن الإجابة على أسئلة المستندات تأخذ صورة لمستند كمدخل بالإضافة إلى سؤال هذا حول المستند وتعيد الإجابة. يمكن استخدام الإجابة على أسئلة المستندات لتفسير المستندات المُنسّقة واستخراج المعلومات الرئيسية منها. في المثال أدناه، يمكن استخراج المبلغ الإجمالي والمبلغ المُسترد من إيصال الدفع.. + +```py +>>> from transformers import pipeline +>>> from PIL import Image +>>> import requests + +>>> url = "https://huggingface.co/datasets/hf-internal-testing/example-documents/resolve/main/jpeg_images/2.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> doc_question_answerer = pipeline("document-question-answering", model="magorshunov/layoutlm-invoices") +>>> preds = doc_question_answerer( +... question="ما هو المبلغ الإجمالي؟", +... image=image, +... ) +>>> preds +[{'score': 0.8531, 'answer': '17,000', 'start': 4, 'end': 4}] +``` + +نأمل أن تكون هذه الصفحة قد زودتك ببعض المعلومات الأساسية حول جميع أنواع المهام في كل طريقة وأهمية كل منها العملية. في القسم التالي، ستتعلم كيف تعمل مكتبة 🤗 Transformers لحل هذه المهام. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/language_modeling.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/language_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..24f2db00a7a69a446895fbf3e5c915bece3bc0c1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/language_modeling.md @@ -0,0 +1,422 @@ + + +# نمذجة اللغة السببية (Causal language modeling) + +[[open-in-colab]] + +هناك نوعان من نمذجة اللغة، السببية والمقنعة. يوضح هذا الدليل نمذجة اللغة السببية. +تُستخدم نماذج اللغة السببية غالبًا لتوليد النص. يمكنك استخدام هذه النماذج للتطبيقات الإبداعية مثل +اختيار مغامرة النص الخاصة بك أو مساعد ترميز ذكي مثل Copilot أو CodeParrot. + + + +تتنبأ نمذجة اللغة السببية بالرمز التالي في تسلسل من الرموز، ولا يمكن للنموذج سوى الاهتمام بالرموز على +اليسار. هذا يعني أن النموذج لا يمكنه رؤية الرموز المستقبلية. GPT-2 هو مثال على نموذج اللغة السببية. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) على مجموعة فرعية [r/askscience](https://www.reddit.com/r/askscience/) من مجموعة بيانات [ELI5](https://huggingface.co/datasets/eli5). +2. استخدام النموذج المدرب الخاص بك للاستنتاج. + + + +لرؤية جميع العمارات ونقاط التحقق المتوافقة مع هذه المهمة، نوصي بالتحقق من [task-page](https://huggingface.co/tasks/text-generation) + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عند المطالبة، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات ELI5 + +ابدأ بتحميل أول 5000 مثال من [ELI5-Category](https://huggingface.co/datasets/eli5_category) مجموعة البيانات مع مكتبة 🤗 Datasets. سيعطيك هذا فرصة للتجربة والتأكد من أن كل شيء يعمل قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> eli5 = load_dataset("eli5_category", split="train[:5000]") +``` + +قم بتقسيم مجموعة بيانات `train` إلى مجموعتي تدريب واختبار باستخدام الخاصية [`~datasets.Dataset.train_test_split`]: + +```py +>>> eli5 = eli5.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'score': [21, 19, 5, 3], + 'text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]}, + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +على الرغم من أن هذا قد يبدو معقدًا، إلا أنك مهتم حقًا بحقل `text`. ما هو رائع حول مهام نمذجة اللغة +أنت لا تحتاج إلى تسميات (تُعرف أيضًا باسم المهمة غير الخاضعة للإشراف) لأن الكلمة التالية تعمل كتسمية. + +## معالجة مسبقة (Preprocess) + + + +الخطوة التالية هي تحميل مجزء النص DistilGPT2 لمعالجة حقل `text` الفرعي: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") +``` + +ستلاحظ من المثال أعلاه، الحقل `text` هو في الواقع متداخل داخل `answers`. هذا يعني أنك ستحتاج إلى +استخراج حقل `text` الفرعي من بنيته المتداخلة باستخدام الدالة [`flatten`](https://huggingface.co/docs/datasets/process#flatten): + +```py +>>> eli5 = eli5.flatten() +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'answers.text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'answers.score': [21, 19, 5, 3], + 'answers.text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']], + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +كل حقل فرعي هو الآن عموداً منفصلاً مسبوقاً بـ `answers`، وحقل `text` هو قائمة الآن. بدلاً من ذلك +من تجزائة نص كل جملة بشكل منفصل، قم بتحويل القائمة إلى سلسلة حتى تتمكن من تجزئة نصها بشكل مجمّع. + +هنا أول دالة معالجة مسبقة لدمج قائمة السلاسل لكل مثال ومجزىء النتيجة: + +```py +>>> def preprocess_function(examples): +... return tokenizer([" ".join(x) for x in examples["answers.text"]]) +``` + +لتطبيق دالة المعالجة المسبقة هذه على مجموعة البيانات بأكملها، استخدم الدالة 🤗 Datasets [`~datasets.Dataset.map`]. يمكنك تسريع هذه العملية `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد، وزيادة عدد العمليات مع `num_proc`. احذف أي أعمدة لا تحتاجها: + +```py +>>> tokenized_eli5 = eli5.map( +... preprocess_function, +... batched=True, +... num_proc=4, +... remove_columns=eli5["train"].column_names, +... ) +``` + +تحتوي هذه المجموعة من البيانات على تسلسلات الرموز، ولكن بعضها أطول من الطول الأقصى للمدخلات للنموذج. + +يمكنك الآن استخدام دالة ما قبل المعالجة ثانية لـ: + +- تجميع كل التسلسلات. +- تقسيم التسلسلات المجمّعة إلى أجزاء أقصر محددة، بحجم `block_size`، والتي يجب أن تكون أقصر من الطول الأقصى للمدخلات ومناسبة لذاكرة GPU. + +```py +>>> block_size = 128 + +>>> def group_texts(examples): +... # ربط جميع النصوص. +... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} +... total_length = len(concatenated_examples[list(examples.keys())[0]]) +... # نتجاهل الباقي الصغير، يمكننا إضافة الحشو إذا كان النموذج يدعمه بدلاً من هذا الإسقاط، يمكنك +... # تخصيص هذا الجزء حسب احتياجاتك. +... if total_length >= block_size: +... total_length = (total_length // block_size) * block_size +... # التقسيم إلى أجزاء بحجم block_size. +... result = { +... k: [t[i : i + block_size] for i in range(0, total_length, block_size)] +... for k, t in concatenated_examples.items() +... } +... result["labels"] = result["input_ids"].copy() +... return result +``` + +طبق دالة `group_texts` على كامل المجموعة من البيانات: + +```py +>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForLanguageModeling`]. من الأفضل أن تقوم بـ *الحشو الديناميكي* للجمل إلى الطول الأطول في الدفعة أثناء التجميع، بدلاً من حشو كامل المجموعة من البيانات إلى الطول الأقصى. + + + +استخدم رمز نهاية التسلسل كرمز للحشو، وحدد `mlm_probability` لحجب الرموز بشكل عشوائي عند كل تكرار للبيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> tokenizer.pad_token = tokenizer.eos_token +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) +``` + + + +استخدم رمز نهاية التسلسل كرمز للحشو، وحدد `mlm_probability` لحجب الرموز بشكل عشوائي عند كل تكرار للبيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False, return_tensors="tf") +``` + + + + +## التدريب (Train) + + + + + + +إذا لم تكن على دراية بتدريب نموذج باستخدام [`Trainer`], اطلع على [البرنامج التعليمي الأساسي](../training#train-with-pytorch-trainer)! + + + +أنت جاهز الآن لبدء تدريب نموذجك! قم بتحميل DistilGPT2 باستخدام [`AutoModelForCausalLM`]: + +```py +>>> from transformers import AutoModelForCausalLM, TrainingArguments, Trainer + +>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد أين سيتم حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub بتحديد `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). +2. قم بتمرير معاملات التدريب إلى [`Trainer`] إلى جانب النموذج، والمجموعات من البيانات، ومجمّع البيانات. +3. قم باستدعاء [`~Trainer.train`] لتدريب نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_eli5_clm-model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=lm_dataset["train"], +... eval_dataset=lm_dataset["test"], +... data_collator=data_collator, +... tokenizer=tokenizer, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، استخدم طريقة [`~transformers.Trainer.evaluate`] لتقييم نموذجك والحصول على احتمالية الارتباك: + +```py +>>> import math + +>>> eval_results = trainer.evaluate() +>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") +Perplexity: 49.61 +``` + +ثم شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتدريب نموذج باستخدام Keras، اطلع على [البرنامج التعليمي الأساسي](../training#train-a-tensorflow-model-with-keras)! + + +لتدريب نموذج في TensorFlow، ابدأ بإعداد دالة المحسن، وجدول معدل التعلم، وبعض معاملات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل DistilGPT2 باستخدام [`TFAutoModelForCausalLM`]: + +```py +>>> from transformers import TFAutoModelForCausalLM + +>>> model = TFAutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +حول مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... lm_dataset["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... lm_dataset["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة الافتراضية، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # لا يوجد حجة للخسارة! +``` + +يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومجمّع البيانات في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_eli5_clm-model", +... tokenizer=tokenizer, +... ) +``` + +أخيراً، أنت جاهز لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة، وعدد العصور، والتعليقات الخاصة بك لتدريب النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback]) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية تدريب نموذج للنمذجة اللغوية السببية، اطلع على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بتدريب نموذج، يمكنك استخدامه للاستدلال! + +قم بابتكار سؤال تود توليد نص منه: + +```py +>>> prompt = "Somatic hypermutation allows the immune system to" +``` + +أبسط طريقة لتجربة نموذجك المدرب للاستدلال هي استخدامه في [`pipeline`]. قم بتنفيذ `pipeline` لتوليد النص مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline("text-generation", model="username/my_awesome_eli5_clm-model") +>>> generator(prompt) +[{'generated_text': "Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\n\n\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks."}] +``` + + + +قسم النص وإرجع `input_ids` كتنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model") +>>> inputs = tokenizer(prompt, return_tensors="pt").input_ids +``` + +استخدم طريقة [`~generation.GenerationMixin.generate`] لتوليد النص. +للمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والبارامترات للتحكم في التوليد، راجع صفحة [استراتيجيات توليد النص](../generation_strategies). + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95) +``` + +فك ترميز الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) +["Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the University of Massachusetts-Boston have found that 'hypermutation' is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system"] +``` + + +قم بتقسيم النص وإرجاع `input_ids` كـ TensorFlow tensors: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_clm-model") +>>> inputs = tokenizer(prompt, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء الملخص. للمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والبارامترات للتحكم في التوليد، راجع صفحة [استراتيجيات توليد النص](../generation_strategies). + +```py +>>> from transformers import TFAutoModelForCausalLM + +>>> model = TFAutoModelForCausalLM.from_pretrained("username/my_awesome_eli5_clm-model") +>>> outputs = model.generate(input_ids=inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95) +``` + +فك ترميز الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) +['Somatic hypermutation allows the immune system to detect the presence of other viruses as they become more prevalent. Therefore, researchers have identified a high proportion of human viruses. The proportion of virus-associated viruses in our study increases with age. Therefore, we propose a simple algorithm to detect the presence of these new viruses in our samples as a sign of improved immunity. A first study based on this algorithm, which will be published in Science on Friday, aims to show that this finding could translate into the development of a better vaccine that is more effective for'] +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/masked_language_modeling.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/masked_language_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..e8382927d1e6004190ee66da843e41b684fc7971 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/masked_language_modeling.md @@ -0,0 +1,442 @@ + + +# نمذجة اللغة المقنعة (Masked language modeling) + +[[open-in-colab]] + + + +تتنبأ نمذجة اللغة المقنعة برمز مقنع في تسلسل، ويمكن للنموذج الانتباه إلى الرموز بشكل ثنائي الاتجاه. هذا +يعني أن النموذج لديه إمكانية الوصول الكاملة إلى الرموز الموجودة على اليسار واليمين. تعد نمذجة اللغة المقنعة ممتازة للمهام التي +تتطلب فهمًا سياقيًا جيدًا لتسلسل كامل. BERT هو مثال على نموذج لغة مقنع. + +سيوضح لك هذا الدليل كيفية: + +1. تكييف [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) على مجموعة فرعية [r/askscience](https://www.reddit.com/r/askscience/) من مجموعة بيانات [ELI5](https://huggingface.co/datasets/eli5). +2. استخدام نموذج المدرب الخاص بك للاستدلال. + + + +لمعرفة جميع البنى والنسخ المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/fill-mask) + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عندما تتم مطالبتك، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات ELI5 + +ابدأ بتحميل أول 5000 مثال من مجموعة بيانات [ELI5-Category](https://huggingface.co/datasets/eli5_category) باستخدام مكتبة 🤗 Datasets. سيعطيك هذا فرصة للتجربة والتأكد من أن كل شيء يعمل قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> eli5 = load_dataset("eli5_category", split="train[:5000]") +``` + +قم بتقسيم مجموعة البيانات `train` إلى مجموعتي تدريب واختبار باستخدام الدالة [`~datasets.Dataset.train_test_split`]: + +```py +>>> eli5 = eli5.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'score': [21, 19, 5, 3], + 'text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]}, + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +على الرغم من أن هذا قد يبدو كثيرًا، إلا أنك مهتم حقًا بحقل `text`. ما هو رائع حول مهام نمذجة اللغة هو أنك لا تحتاج إلى تسميات (تُعرف أيضًا باسم المهمة غير الخاضعة للإشراف) لأن الكلمة التالية *هي* التسمية. + +## معالجة مسبقة (Preprocess) + + + +بالنسبة لنمذجة اللغة المقنعة، فإن الخطوة التالية هي تحميل معالج DistilRoBERTa لمعالجة حقل `text` الفرعي: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilroberta-base") +``` + +ستلاحظ من المثال أعلاه، أن حقل `text` موجود بالفعل داخل `answers`. هذا يعني أنك ستحتاج إلى استخراج حقل `text` الفرعي من بنيته المضمنة باستخدام الدالة [`flatten`](https://huggingface.co/docs/datasets/process#flatten): + +```py +>>> eli5 = eli5.flatten() +>>> eli5["train"][0] +{'q_id': '7h191n', + 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?', + 'selftext': '', + 'category': 'Economics', + 'subreddit': 'explainlikeimfive', + 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'], + 'answers.text': ["The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.", + 'None yet. It has to be reconciled with a vastly different house bill and then passed again.', + 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?', + 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'], + 'answers.score': [21, 19, 5, 3], + 'answers.text_urls': [[], + [], + [], + ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']], + 'title_urls': ['url'], + 'selftext_urls': ['url']} +``` + +كل حقل فرعي هو الآن عمود منفصل كما هو موضح بواسطة بادئة `answers`، وحقل `text` هو قائمة الآن. بدلاً من +معالجة كل جملة بشكل منفصل، قم بتحويل القائمة إلى سلسلة حتى تتمكن من معالجتها بشكل مشترك. + +هنا أول دالة معالجة مسبقة لربط قائمة السلاسل لكل مثال ومعالجة النتيجة: + +```py +>>> def preprocess_function(examples): +... return tokenizer([" ".join(x) for x in examples["answers.text"]]) +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم الدالة 🤗 Datasets [`~datasets.Dataset.map`]. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عدة عناصر في وقت واحد، وزيادة عدد العمليات باستخدام `num_proc`. احذف أي أعمدة غير ضرورية: + +```py +>>> tokenized_eli5 = eli5.map( +... preprocess_function, +... batched=True, +... num_proc=4, +... remove_columns=eli5["train"].column_names, +... ) +``` + + +تحتوي مجموعة البيانات هذه على تسلسلات رمزية، ولكن بعضها أطول من الطول الأقصى للمدخلات للنموذج. + +يمكنك الآن استخدام دالة معالجة مسبقة ثانية لـ: +- تجميع جميع التسلسلات +- تقسيم التسلسلات المجمّعة إلى أجزاء أقصر محددة بـ `block_size`، والتي يجب أن تكون أقصر من الحد الأقصى لطول المدخلات ومناسبة لذاكرة GPU. + +```py +>>> block_size = 128 + +>>> def group_texts(examples): +... # تجميع جميع النصوص. +... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} +... total_length = len(concatenated_examples[list(examples.keys())[0]]) +... # نتجاهل الجزء المتبقي الصغير، يمكننا إضافة الحشو إذا كان النموذج يدعمه بدلاً من هذا الإسقاط، يمكنك +... # تخصيص هذا الجزء حسب احتياجاتك. +... if total_length >= block_size: +... total_length = (total_length // block_size) * block_size +... # تقسيمها إلى أجزاء بحجم block_size. +... result = { +... k: [t[i : i + block_size] for i in range(0, total_length, block_size)] +... for k, t in concatenated_examples.items() +... } +... return result +``` + +طبق دالة `group_texts` على مجموعة البيانات بأكملها: + +```py +>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) +``` + +الآن، قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForLanguageModeling`]. من الأكثر كفاءة أن تقوم بـ *الحشو الديناميكي* ليصل طولها إلى أطول جملة في الدفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الطول الأقصى. + + + + +استخدم رمز نهاية التسلسل كرمز الحشو وحدد `mlm_probability` لحجب الرموز عشوائياً كل مرة تكرر فيها البيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> tokenizer.pad_token = tokenizer.eos_token +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15) +``` + + + +استخدم رمز نهاية التسلسل كرمز الحشو وحدد `mlm_probability` لحجب الرموز عشوائياً كل مرة تكرر فيها البيانات: + +```py +>>> from transformers import DataCollatorForLanguageModeling + +>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15, return_tensors="tf") +``` + + + +## التدريب (Train) + + + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام [`Trainer`], ألق نظرة على الدليل الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilRoBERTa باستخدام [`AutoModelForMaskedLM`]: + +```py +>>> from transformers import AutoModelForMaskedLM + +>>> model = AutoModelForMaskedLM.from_pretrained("distilbert/distilroberta-base") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعلمة الوحيدة المطلوبة هي `output_dir` والتي تحدد مكان حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). +2. قم بتمرير معلمات التدريب إلى [`Trainer`] مع النموذج، ومجموعات البيانات، ومجمّع البيانات. +3. قم باستدعاء [`~Trainer.train`] لتعديل نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_eli5_mlm_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=lm_dataset["train"], +... eval_dataset=lm_dataset["test"], +... data_collator=data_collator, +... tokenizer=tokenizer, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، استخدم طريقة [`~transformers.Trainer.evaluate`] لتقييم النموذج والحصول على مقياس + الحيرة: + +```py +>>> import math + +>>> eval_results = trainer.evaluate() +>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") +Perplexity: 8.76 +``` + +ثم شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام Keras، ألق نظرة على الدليل الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لتعديل نموذج في TensorFlow، ابدأ بإعداد دالة محسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل DistilRoBERTa باستخدام [`TFAutoModelForMaskedLM`]: + +```py +>>> from transformers import TFAutoModelForMaskedLM + +>>> model = TFAutoModelForMaskedLM.from_pretrained("distilbert/distilroberta-base") +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... lm_dataset["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... lm_dataset["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن نماذج Transformers لديها جميعها دالة خسارة افتراضية ذات صلة بالمهمة، لذلك لا تحتاج إلى تحديد واحدة ما لم تكن تريد ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # لا توجد حجة للخسارة! +``` + +يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومعالج الرموز في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_eli5_mlm_model", +... tokenizer=tokenizer, +... ) +``` + +أخيراً، أنت مستعد لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق، وعدد العصور، والتعليقات الخاصة بك لتعديل النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback]) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائياً إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +لمثال أكثر تفصيلاً حول كيفية تعديل نموذج للنمذجة اللغوية المقنعة، ألق نظرة على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). + + + +## الاستدلال + +رائع، الآن بعد أن قمت بتعديل نموذج، يمكنك استخدامه للاستدلال! + +جهّز بعض النصوص التي تريد أن يملأ النموذج الفراغات فيها، واستخدم الرمز الخاص `` للإشارة إلى الفراغ: + +```py +>>> text = "The Milky Way is a galaxy." +``` + +أبسط طريقة لتجربة نموذجك المعدل للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء كائن `pipeline` لملء الفراغ مع نموذجك، ومرر نصك إليه. إذا أردت، يمكنك استخدام معلمة `top_k` لتحديد عدد التنبؤات التي تريد إرجاعها: + +```py +>>> from transformers import pipeline + +>>> mask_filler = pipeline("fill-mask", "username/my_awesome_eli5_mlm_model") +>>> mask_filler(text, top_k=3) +[{'score': 0.5150994658470154, + 'token': 21300, + 'token_str': ' spiral', + 'sequence': 'The Milky Way is a spiral galaxy.'}, + {'score': 0.07087188959121704, + 'token': 2232, + 'token_str': ' massive', + 'sequence': 'The Milky Way is a massive galaxy.'}, + {'score': 0.06434620916843414, + 'token': 650, + 'token_str': ' small', + 'sequence': 'The Milky Way is a small galaxy.'}] +``` + + + +قم بتجزئة النص وإرجاع `input_ids` كمتجهات PyTorch. ستحتاج أيضًا إلى تحديد موضع رمز ``: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> inputs = tokenizer(text, return_tensors="pt") +>>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1] +``` + +قم بتمرير المدخلات إلى النموذج وإرجاع `logits` للرمز المقنع: + +```py +>>> from transformers import AutoModelForMaskedLM + +>>> model = AutoModelForMaskedLM.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> logits = model(**inputs).logits +>>> mask_token_logits = logits[0, mask_token_index, :] +``` + +ثم قم بإرجاع الرموز الثلاثة المقنعة ذات الاحتمالية الأعلى وطباعتها: + +```py +>>> top_3_tokens = torch.topk(mask_token_logits, 3, dim=1).indices[0].tolist() + +>>> for token in top_3_tokens: +... print(text.replace(tokenizer.mask_token, tokenizer.decode([token]))) +The Milky Way is a spiral galaxy. +The Milky Way is a massive galaxy. +The Milky Way is a small galaxy. +``` + + +قم بتقسيم النص إلى رموز وإرجاع `input_ids` كـ TensorFlow tensors. ستحتاج أيضًا إلى تحديد موضع رمز ``: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> inputs = tokenizer(text, return_tensors="tf") +>>> mask_token_index = tf.where(inputs["input_ids"] == tokenizer.mask_token_id)[0, 1] +``` + +قم بتمرير المدخلات إلى النموذج وإرجاع `logits` للرمز المقنع: + +```py +>>> from transformers import TFAutoModelForMaskedLM + +>>> model = TFAutoModelForMaskedLM.from_pretrained("username/my_awesome_eli5_mlm_model") +>>> logits = model(**inputs).logits +>>> mask_token_logits = logits[0, mask_token_index, :] +``` + +ثم قم بإرجاع الرموز الثلاثة المقنعة ذات الاحتمالية الأعلى وطباعتها: + +```py +>>> top_3_tokens = tf.math.top_k(mask_token_logits, 3).indices.numpy() + +>>> for token in top_3_tokens: +... print(text.replace(tokenizer.mask_token, tokenizer.decode([token]))) +The Milky Way is a spiral galaxy. +The Milky Way is a massive galaxy. +The Milky Way is a small galaxy. +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/multiple_choice.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/multiple_choice.md new file mode 100644 index 0000000000000000000000000000000000000000..78f98560754f11d79394fb64881f676506a40db0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/multiple_choice.md @@ -0,0 +1,452 @@ + + +# الاختيار من متعدد (Multiple choice) + +[[open-in-colab]] + +مهمة الاختيار من متعدد مشابهة لمهمة الإجابة على الأسئلة، ولكن مع توفير عدة إجابات محتملة مع سياق، ويُدرّب النموذج على تحديد الإجابة الصحيحة. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط نموذج [BERT](https://huggingface.co/google-bert/bert-base-uncased) باستخدام الإعداد `regular` لمجموعة بيانات [SWAG](https://huggingface.co/datasets/swag) لاختيار الإجابة الأفضل من بين الخيارات المتعددة المتاحة مع السياق. +2. استخدام النموذج المضبوط للاستدلال. + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات SWAG + +ابدأ بتحميل تهيئة `regular` لمجموعة بيانات SWAG من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> swag = load_dataset("swag", "regular") +``` + +ثم ألق نظرة على مثال: + +```py +>>> swag["train"][0] +{'ending0': 'passes by walking down the street playing their instruments.', + 'ending1': 'has heard approaching them.', + 'ending2': "arrives and they're outside dancing and asleep.", + 'ending3': 'turns the lead singer watches the performance.', + 'fold-ind': '3416', + 'gold-source': 'gold', + 'label': 0, + 'sent1': 'Members of the procession walk down the street holding small horn brass instruments.', + 'sent2': 'A drum line', + 'startphrase': 'Members of the procession walk down the street holding small horn brass instruments. A drum line', + 'video-id': 'anetv_jkn6uvmqwh4'} +``` + +على الرغم من أن الحقول تبدو كثيرة، إلا أنها في الواقع بسيطة جداً: + +- `sent1` و `sent2`: يعرض هذان الحقلان بداية الجملة، وبدمجهما معًا، نحصل على حقل `startphrase`. +- `ending`: يقترح نهاية محتملة للجملة، واحدة منها فقط هي الصحيحة. +- `label`: يحدد نهاية الجملة الصحيحة. + +## المعالجة المسبقة (Preprocess) + +الخطوة التالية هي استدعاء مُجزئ BERT لمعالجة بدايات الجمل والنهايات الأربع المحتملة: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +``` + +تحتاج دالة المعالجة المسبقة التي تريد إنشاءها إلى: + +1. إنشاء أربع نسخ من حقل `sent1` ودمج كل منها مع `sent2` لإعادة إنشاء كيفية بدء الجملة. +2. دمج `sent2` مع كل من نهايات الجمل الأربع المحتملة. +3. تتجميع هاتين القائمتين لتتمكن من تجزئتهما، ثم إعادة ترتيبها بعد ذلك بحيث يكون لكل مثال حقول `input_ids` و `attention_mask` و `labels` مقابلة. + + +```py +>>> ending_names = ["ending0", "ending1", "ending2", "ending3"] + +>>> def preprocess_function(examples): +... first_sentences = [[context] * 4 for context in examples["sent1"]] +... question_headers = examples["sent2"] +... second_sentences = [ +... [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers) +... ] + +... first_sentences = sum(first_sentences, []) +... second_sentences = sum(second_sentences, []) + +... tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True) +... return {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()} +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] الخاصة بـ 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +tokenized_swag = swag.map(preprocess_function, batched=True) +``` + +لا يحتوي 🤗 Transformers على مجمع بيانات للاختيار من متعدد، لذلك ستحتاج إلى تكييف [`DataCollatorWithPadding`] لإنشاء دفعة من الأمثلة. من الأكفأ إضافة حشو (padding) ديناميكي للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + +يقوم `DataCollatorForMultipleChoice` بتجميع جميع مدخلات النموذج، ويطبق الحشو، ثم يعيد تجميع النتائج في شكلها الأصلي: + + + + +```py +>>> from dataclasses import dataclass +>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy +>>> from typing import Optional, Union +>>> import torch + +>>> @dataclass +... class DataCollatorForMultipleChoice: +... """ +... Data collator that will dynamically pad the inputs for multiple choice received. +... """ + +... tokenizer: PreTrainedTokenizerBase +... padding: Union[bool, str, PaddingStrategy] = True +... max_length: Optional[int] = None +... pad_to_multiple_of: Optional[int] = None + +... def __call__(self, features): +... label_name = "label" if "label" in features[0].keys() else "labels" +... labels = [feature.pop(label_name) for feature in features] +... batch_size = len(features) +... num_choices = len(features[0]["input_ids"]) +... flattened_features = [ +... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features +... ] +... flattened_features = sum(flattened_features, []) + +... batch = self.tokenizer.pad( +... flattened_features, +... padding=self.padding, +... max_length=self.max_length, +... pad_to_multiple_of=self.pad_to_multiple_of, +... return_tensors="pt", +... ) + +... batch = {k: v.view(batch_size, num_choices, -1) for k, v in batch.items()} +... batch["labels"] = torch.tensor(labels, dtype=torch.int64) +... return batch +``` + + + +```py +>>> from dataclasses import dataclass +>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy +>>> from typing import Optional, Union +>>> import tensorflow as tf + +>>> @dataclass +... class DataCollatorForMultipleChoice: +... """ +... Data collator that will dynamically pad the inputs for multiple choice received. +... """ + +... tokenizer: PreTrainedTokenizerBase +... padding: Union[bool, str, PaddingStrategy] = True +... max_length: Optional[int] = None +... pad_to_multiple_of: Optional[int] = None + +... def __call__(self, features): +... label_name = "label" if "label" in features[0].keys() else "labels" +... labels = [feature.pop(label_name) for feature in features] +... batch_size = len(features) +... num_choices = len(features[0]["input_ids"]) +... flattened_features = [ +... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features +... ] +... flattened_features = sum(flattened_features, []) + +... batch = self.tokenizer.pad( +... flattened_features, +... padding=self.padding, +... max_length=self.max_length, +... pad_to_multiple_of=self.pad_to_multiple_of, +... return_tensors="tf", +... ) + +... batch = {k: tf.reshape(v, (batch_size, num_choices, -1)) for k, v in batch.items()} +... batch["labels"] = tf.convert_to_tensor(labels, dtype=tf.int64) +... return batch +``` + + + +## التقييم (Evaluate) + +يُفضل غالبًا تضمين مقياس أثناء التدريب لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل مقياس [الدقة](https://huggingface.co/spaces/evaluate-metric/accuracy) (انظر إلى [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل المقياس وحسابه): + +```py +>>> import evaluate + +>>> accuracy = evaluate.load("accuracy") +``` + +ثم أنشئ دالة لتمرير التنبؤات والتسميات إلى [`~evaluate.EvaluationModule.compute`] لحساب الدقة: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... predictions = np.argmax(predictions, axis=1) +... return accuracy.compute(predictions=predictions, references=labels) +``` + +دالتك `compute_metrics` جاهزة الآن، وستعود إليها عند إعداد تدريبك. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`], فراجع الدرس الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل BERT باستخدام [`AutoModelForMultipleChoice`]: + +```py +>>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer + +>>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعلمة الوحيدة المطلوبة هي `output_dir` التي تحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم الدقة وحفظ نقطة فحص التدريب. +2. مرر معلمات التدريب إلى [`Trainer`] جنبًا إلى جنب مع النموذج ومُجمِّع البيانات والمعالج ودالة تجميع البيانات ودالة `compute_metrics`. +3. استدعي [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_swag_model", +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... learning_rate=5e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_swag["train"], +... eval_dataset=tokenized_swag["validation"], +... processing_class=tokenizer, +... data_collator=DataCollatorForMultipleChoice(tokenizer=tokenizer), +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فراجع الدرس الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل التعلم وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_train_epochs = 2 +>>> total_train_steps = (len(tokenized_swag["train"]) // batch_size) * num_train_epochs +>>> optimizer, schedule = create_optimizer(init_lr=5e-5, num_warmup_steps=0, num_train_steps=total_train_steps) +``` + +ثم يمكنك تحميل BERT باستخدام [`TFAutoModelForMultipleChoice`]: + +```py +>>> from transformers import TFAutoModelForMultipleChoice + +>>> model = TFAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-uncased") +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> data_collator = DataCollatorForMultipleChoice(tokenizer=tokenizer) +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_swag["train"], +... shuffle=True, +... batch_size=batch_size, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_swag["validation"], +... shuffle=False, +... batch_size=batch_size, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers تحتوي على دالة خسارة مناسبة للمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> model.compile(optimizer=optimizer) # لا توجد وسيطة خسارة! +``` + +الخطوتان الأخيرتان قبل بدء التدريب هما: حساب دقة التنبؤات، وتوفير طريقة لرفع النموذج إلى Hub. ويمكن تحقيق ذلك باستخدام [استدعاءات Keras](../main_classes/keras_callbacks) + +مرر دالتك `compute_metrics` إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك ومعالجك في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_model", +... tokenizer=tokenizer, +... ) +``` + +ثم قم بتضمين الاستدعاءات معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! استدعِ[`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب والاستدعاءات لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=2, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للاختيار من متعدد، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb) +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb) المقابل. + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +قم بإنشاء نص واقتراح إجابتين محتملتين: + +```py +>>> prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette." +>>> candidate1 = "The law does not apply to croissants and brioche." +>>> candidate2 = "The law applies to baguettes." +``` + + + +قم بتحليل كل مطالبة وزوج إجابة مرشح وأعد تنسورات PyTorch. يجب عليك أيضًا إنشاء بعض `العلامات`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_swag_model") +>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True) +>>> labels = torch.tensor(0).unsqueeze(0) +``` + +مرر مدخلاتك والعلامات إلى النموذج وأرجع`logits`: + +```py +>>> from transformers import AutoModelForMultipleChoice + +>>> model = AutoModelForMultipleChoice.from_pretrained("username/my_awesome_swag_model") +>>> outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels) +>>> logits = outputs.logits +``` + +استخرج الفئة ذات الاحتمالية الأكبر: + +```py +>>> predicted_class = logits.argmax().item() +>>> predicted_class +0 +``` + + +قم بتحليل كل مطالبة وزوج إجابة مرشح وأعد موترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_swag_model") +>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="tf", padding=True) +``` + +مرر مدخلاتك إلى النموذج وأعد القيم logits: + +```py +>>> from transformers import TFAutoModelForMultipleChoice + +>>> model = TFAutoModelForMultipleChoice.from_pretrained("username/my_awesome_swag_model") +>>> inputs = {k: tf.expand_dims(v, 0) for k, v in inputs.items()} +>>> outputs = model(inputs) +>>> logits = outputs.logits +``` + +استخرج الفئة ذات الاحتمالية الأكبر: + +```py +>>> predicted_class = int(tf.math.argmax(logits, axis=-1)[0]) +>>> predicted_class +0 +``` + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/question_answering.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/question_answering.md new file mode 100644 index 0000000000000000000000000000000000000000..0c4b66443d814aff4416221497ae409c7aa77655 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/question_answering.md @@ -0,0 +1,432 @@ + + +# الإجابة على الأسئلة (Question answering) + +[[open-in-colab]] + + + +تُقدّم مهام الإجابة على الأسئلة إجابةً بناءً على سؤال. إذا سبق لك أن سألت مساعدًا افتراضيًا مثل Alexa أو Siri أو Google عن حالة الطقس، فأنت قد استخدمت نموذج للإجابة على الأسئلة من قبل. هناك نوعان شائعان لمهام الإجابة على الأسئلة: + +- الاستخراجية: استخراج الإجابة من السياق المحدد. +- التلخيصية: إنشاء إجابة من السياق تجيب على السؤال بشكل صحيح. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [SQuAD](https://huggingface.co/datasets/squad) للإجابة على الأسئلة الاستخراجية. +2. استخدام النموذج المضبوط للاستدلال. + + + +لمشاهدة جميع الهياكل والنسخ المتوافقة مع هذه المهمة، نوصي بالرجوع إلى [صفحة المهمة](https://huggingface.co/tasks/question-answering) + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات SQuAD + +ابدأ بتحميل جزء أصغر من مجموعة بيانات SQuAD من مكتبة 🤗 Datasets. سيتيح لك ذلك فرصة للتجربة والتحقق من عمل كل شيء بشكل صحيح قبل قضاء المزيد من الوقت في التدريب على مجموعة البيانات الكاملة. + +```py +>>> from datasets import load_dataset + +>>> squad = load_dataset("squad", split="train[:5000]") +``` + +قم بتقسيم تقسيم `train` لمجموعة البيانات إلى مجموعة تدريب واختبار باستخدام طريقة [`~datasets.Dataset.train_test_split`]: + +```py +>>> squad = squad.train_test_split(test_size=0.2) +``` + +ثم ألق نظرة على مثال: + +```py +>>> squad["train"][0] +{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']}, + 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', + 'id': '5733be284776f41900661182', + 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', + 'title': 'University_of_Notre_Dame' +} +``` + +هناك العديد من الحقول المهمة هنا: + +- `answers`: موقع بداية الرمز المميز للإجابة ونص الإجابة. +- `context`: معلومات أساسية يحتاج النموذج إلى استخراج الإجابة منها. +- `question`: السؤال الذي يجب على النموذج الإجابة عليه. + +## المعالجة المسبقة (Preprocess) + + + +الخطوة التالية هي تحميل المحلل اللغوى DistilBERT لمعالجة حقلي `question` و `context`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +هناك بعض خطوات المعالجة المسبقة الخاصة بمهام الإجابة على الأسئلة التي يجب أن تكون على دراية بها: + +1. قد تحتوي بعض الأمثلة في مجموعة البيانات على `context` طويلًا يتجاوز الحد الأقصى لطول مدخل النموذج. للتعامل مع النصوص الأطول، يتم اقتطاع `context` فقط عن طريق تعيين `truncation="only_second"`. +2. بعد ذلك، يتم تحديد مواضع بداية ونهاية الإجابة في `context` الأصلي عن طريق تعيين + `return_offset_mapping=True`. +3. باستخدام التعيين، يمكن الآن تحديد رموز بداية ونهاية الإجابة. استخدم طريقة [`~tokenizers.Encoding.sequence_ids`] + لتحديد أجزاء الإزاحة التي تتوافق مع `question` و `context`. + +فيما يلي كيفية إنشاء دالة لقص وتعيين رموز البداية والنهاية لـ `answer` إلى `context`: + +```py +>>> def preprocess_function(examples): +... questions = [q.strip() for q in examples["question"]] +... inputs = tokenizer( +... questions, +... examples["context"], +... max_length=384, +... truncation="only_second", +... return_offsets_mapping=True, +... padding="max_length", +... ) + +... offset_mapping = inputs.pop("offset_mapping") +... answers = examples["answers"] +... start_positions = [] +... end_positions = [] + +... for i, offset in enumerate(offset_mapping): +... answer = answers[i] +... start_char = answer["answer_start"][0] +... end_char = answer["answer_start"][0] + len(answer["text"][0]) +... sequence_ids = inputs.sequence_ids(i) + +... # Find the start and end of the context +... idx = 0 +... while sequence_ids[idx] != 1: +... idx += 1 +... context_start = idx +... while sequence_ids[idx] == 1: +... idx += 1 +... context_end = idx - 1 + +... # If the answer is not fully inside the context, label it (0, 0) +... if offset[context_start][0] > end_char or offset[context_end][1] < start_char: +... start_positions.append(0) +... end_positions.append(0) +... else: +... # Otherwise it's the start and end token positions +... idx = context_start +... while idx <= context_end and offset[idx][0] <= start_char: +... idx += 1 +... start_positions.append(idx - 1) + +... idx = context_end +... while idx >= context_start and offset[idx][1] >= end_char: +... idx -= 1 +... end_positions.append(idx + 1) + +... inputs["start_positions"] = start_positions +... inputs["end_positions"] = end_positions +... return inputs +``` + +لتطبيق المعالجة المسبقة على كامل مجموعة البيانات، استخدم [`~datasets.Dataset.map`] من مكتبة 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات دفعة واحدة. قم بإزالة أي أعمدة لا تحتاجها: + +```py +>>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DefaultDataCollator`]. بخلاف مجمّعات البيانات الأخرى في 🤗 Transformers، لا يطبق [`DefaultDataCollator`] أي معالجة مسبقة إضافية مثل الحشو. + + + + +```py +>>> from transformers import DefaultDataCollator + +>>> data_collator = DefaultDataCollator() +``` + + + +```py +>>> from transformers import DefaultDataCollator + +>>> data_collator = DefaultDataCollator(return_tensors="tf") +``` + + + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`], ألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل DistilBERT باستخدام [`AutoModelForQuestionAnswering`]: + +```py +>>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer + +>>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد المعاملات الفائقة للتدريب في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). +2. مرر معاملات التدريب إلى [`Trainer`] جنبًا إلى جنب مع النموذج، ومجموعة البيانات، والمُحلّل النصي، ومُجمّع البيانات. +3. استدعِ ـ [`~Trainer.train`] لضبط النموذج. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_qa_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=3, +... weight_decay=0.01, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_squad["train"], +... eval_dataset=tokenized_squad["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك في Hub باستخدام الدالة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن، وجدول معدل التعلم، وبعض المعاملات الفائقة للتدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_epochs = 2 +>>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs +>>> optimizer, schedule = create_optimizer( +... init_lr=2e-5, +... num_warmup_steps=0, +... num_train_steps=total_train_steps, +... ) +``` + +ثم يمكنك تحميل DistilBERT باستخدام [`TFAutoModelForQuestionAnswering`]: + +```py +>>> from transformers import TFAutoModelForQuestionAnswering + +>>> model = TFAutoModelForQuestionAnswering.from_pretrained("distilbert/distilbert-base-uncased") +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_squad["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_squad["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method): + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) +``` + +آخر شيء يجب إعداده قبل بدء التدريب هو توفير طريقة لدفع نموذجك إلى Hub. يمكن القيام بذلك عن طريق تحديد مكان دفع نموذجك ومعالجك المعجمي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> callback = PushToHubCallback( +... output_dir="my_awesome_qa_model", +... tokenizer=tokenizer, +... ) +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة، وعدد العهود، ومعاودة الاتصال الخاصة بك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback]) +``` +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للإجابة على الأسئلة، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb) المقابل +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). + + + +## التقييم (Evaluate) + +يتطلب التقييم للإجابة على الأسئلة قدرًا كبيرًا من المعالجة اللاحقة. لتوفير وقتك، يتخطى هذا الدليل خطوة التقييم. لا يزال [`Trainer`] يحسب خسارة التقييم أثناء التدريب، مما يعني أنك لست تجهل تمامًا أداء نموذجك. + +إذا كان لديك المزيد من الوقت وتهتم بكيفية تقييم نموذجك للإجابة على الأسئلة، فألق نظرة على فصل [الإجابة على الأسئلة](https://huggingface.co/course/chapter7/7?fw=pt#post-processing) من دورة 🤗 Hugging Face! + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +حدد سؤالًا وسياقًا ليقوم النموذج بالتنبؤ بالإجابة عليه: + +```py +>>> question = "How many programming languages does BLOOM support?" +>>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages." +``` + +أبسط طريقة لتجربة نموذجك المُدرَّب للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء كائن لـ `pipeline` للإجابة على الأسئلة باستخدام نموذجك، ومرِّر النص إليه: + +```py +>>> from transformers import pipeline + +>>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model") +>>> question_answerer(question=question, context=context) +{'score': 0.2058267742395401, + 'start': 10, + 'end': 95, + 'answer': '176 مليار معامل ويمكنه إنشاء نصوص بـ 46 لغة طبيعية و 13'} +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + + + قسّم النص وأرجع تنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") +>>> inputs = tokenizer(question, context, return_tensors="pt") +``` + +مرر مدخلاتك إلى النموذج وأرجع `logits`: + +```py +>>> import torch +>>> from transformers import AutoModelForQuestionAnswering + +>>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") +>>> with torch.no_grad(): +... outputs = model(**inputs) +``` + +احصل على أعلى احتمال من مخرجات النموذج لموضعي البداية والنهاية: + +```py +>>> answer_start_index = outputs.start_logits.argmax() +>>> answer_end_index = outputs.end_logits.argmax() +``` + +استخلاص الإجابة من الرموز المتوقعة: + +```py +>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] +>>> tokenizer.decode(predict_answer_tokens) +'176 billion parameters and can generate text in 46 languages natural languages and 13' +``` + + +قم بتحليل النص المعجمي وأعد موترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") +>>> inputs = tokenizer(question, context, return_tensors="tf") +``` + +مرر مدخلاتك إلى النموذج وأعد `logits`: + +```py +>>> from transformers import TFAutoModelForQuestionAnswering + +>>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") +>>> outputs = model(**inputs) +``` + +احصل على أعلى احتمال من مخرجات النموذج لموضعي البداية والنهاية: + +```py +>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0]) +>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0]) +``` + +استخلاص الإجابة من الرموز المتوقعة: + +```py +>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] +>>> tokenizer.decode(predict_answer_tokens) +'176 billion parameters and can generate text in 46 languages natural languages and 13' +``` + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/sequence_classification.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/sequence_classification.md new file mode 100644 index 0000000000000000000000000000000000000000..a98964957b47c92bc4a43db701db99b650a2dfce --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/sequence_classification.md @@ -0,0 +1,387 @@ + + +# تصنيف النص(Text classification) + +[[open-in-colab]] + + + +تصنيف النص هو مهمة NLP شائعة حيث يُعيّن تصنيفًا أو فئة للنص. تستخدم بعض أكبر الشركات تصنيف النصوص في الإنتاج لمجموعة واسعة من التطبيقات العملية. أحد أكثر أشكال تصنيف النص شيوعًا هو تحليل المشاعر، والذي يقوم بتعيين تسمية مثل 🙂 إيجابية، 🙁 سلبية، أو 😐 محايدة لتسلسل نصي. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [IMDb](https://huggingface.co/datasets/imdb) لتحديد ما إذا كانت مراجعة الفيلم إيجابية أو سلبية. +2. استخدام نموذج الضبط الدقيق للتنبؤ. + + + +لرؤية جميع البنى ونقاط التحقق المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/text-classification). + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate accelerate +``` + +نحن نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عند المطالبة، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات IMDb + +ابدأ بتحميل مجموعة بيانات IMDb من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> imdb = load_dataset("imdb") +``` + +ثم ألق نظرة على مثال: + +```py +>>> imdb["test"][0] +{ + "label": 0, + "text": "I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clichéd and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \"Gene Roddenberry's Earth...\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.", +} +``` + +هناك حقولان في هذه المجموعة من البيانات: + +- `text`: نص مراجعة الفيلم. +- `label`: قيمة إما `0` لمراجعة سلبية أو `1` لمراجعة إيجابية. + +## المعالجة المسبقة(Preprocess) + +الخطوة التالية هي تحميل المُجزِّئ النص DistilBERT لتهيئة لحقل `text`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +أنشئ دالة لتهيئة حقل `text` وتقصير السلاسل النصية بحيث لا يتجاوز طولها الحد الأقصى لإدخالات DistilBERT: + +```py +>>> def preprocess_function(examples): +... return tokenizer(examples["text"], truncation=True) +``` + +لتطبيق دالة التهيئة على مجموعة البيانات بأكملها، استخدم دالة 🤗 Datasets [`~datasets.Dataset.map`] . يمكنك تسريع `map` باستخدام `batched=True` لمعالجة دفعات من البيانات: + +```py +tokenized_imdb = imdb.map(preprocess_function, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorWithPadding`]. الأكثر كفاءة هو استخدام الحشو الديناميكي لجعل الجمل متساوية في الطول داخل كل دفعة، بدلًا من حشو كامل البيانات إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorWithPadding + +>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer) +``` + + + +```py +>>> from transformers import DataCollatorWithPadding + +>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") +``` + + + +## التقييم(Evaluate) + +يُعدّ تضمين مقياس أثناء التدريب مفيدًا لتقييم أداء النموذج. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) . بالنسبة لهذه المهمة، قم بتحميل مقياس [الدقة](https://huggingface.co/spaces/evaluate-metric/accuracy) (راجع جولة 🤗 Evaluate [السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> accuracy = evaluate.load("accuracy") +``` + +ثم أنشئ دالة تقوم بتمرير تنبؤاتك وتصنيفاتك إلى [`~evaluate.EvaluationModule.compute`] لحساب الدقة: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... predictions = np.argmax(predictions, axis=1) +... return accuracy.compute(predictions=predictions, references=labels) +``` + +دالة `compute_metrics` جاهزة الآن، وستعود إليها عند إعداد التدريب. + +## التدريب(Train) + +قبل أن تبدأ في تدريب نموذجك، قم بإنشاء خريطة من المعرفات المتوقعة إلى تسمياتها باستخدام `id2label` و `label2id`: + +```py +>>> id2label = {0: "NEGATIVE", 1: "POSITIVE"} +>>> label2id = {"NEGATIVE": 0, "POSITIVE": 1} +``` + + + + + +إذا لم تكن على دراية بضبط نموذج دقيق باستخدام [`Trainer`], فالق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilBERT مع [`AutoModelForSequenceClassification`] جنبًا إلى جنب مع عدد التصنيفات المتوقعة، وتصنيفات الخرائط: + +```py +>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer + +>>> model = AutoModelForSequenceClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id +... ) +``` + +في هذه المرحلة، هناك ثلاث خطوات فقط متبقية: + +1. حدد مُعامِلات التدريب في [`TrainingArguments`]. المُعامل المطلوب الوحيد هو `output_dir`، لتحديد مكان حفظ النموذج. يمكنك رفع النموذج إلى Hub بتعيين `push_to_hub=True` (يجب تسجيل الدخول إلى Hugging Face لرفع النموذج). سيقوم `Trainer` بتقييم الدقة وحفظ نقاط التحقق في نهاية كل حقبة. +2. مرر مُعامِلات التدريب إلى `Trainer` مع النموذج، ومجموعة البيانات، والمحلل اللغوي، ومُجمِّع البيانات، ووظيفة `compute_metrics`. +3. استدعِ [`~Trainer.train`] لضبط النموذج. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_model", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=2, +... weight_decay=0.01, +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_imdb["train"], +... eval_dataset=tokenized_imdb["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + + + +يستخدم [`Trainer`] الحشو الديناميكي افتراضيًا عند تمرير `tokenizer` إليه. في هذه الحالة، لا تحتاج لتحديد مُجمِّع البيانات صراحةً. + + + +بعد اكتمال التدريب، شارك نموذجك على Hub باستخدام الطريقة [`~transformers.Trainer.push_to_hub`] ليستخدمه الجميع: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بضبط نموذج باستخدام Keras، قم بالاطلاع على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة المحسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer +>>> import tensorflow as tf + +>>> batch_size = 16 +>>> num_epochs = 5 +>>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size +>>> total_train_steps = int(batches_per_epoch * num_epochs) +>>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps) +``` + +ثم يمكنك تحميل DistilBERT مع [`TFAutoModelForSequenceClassification`] بالإضافة إلى عدد التصنيفات المتوقعة، وتعيينات التسميات: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id +... ) +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_imdb["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_imdb["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتهيئة النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر أمرين يجب إعدادهما قبل بدء التدريب هو حساب الدقة من التوقعات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم ذلك باستخدام [Keras callbacks](../main_classes/keras_callbacks). + +قم بتمرير دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك والمجزئ اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع الاستدعاءات معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت مستعد لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق، وعدد الحقبات، واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر عمقًا حول كيفية ضبط نموذج لتصنيف النصوص، قم بالاطلاع على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). + + + +## الاستدلال(Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +احصل على بعض النصوص التي ترغب في إجراء الاستدلال عليها: + +```py +>>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three." +``` + +أسهل طريقة لتجربة النموذج المضبوط للاستدلال هي استخدامه ضمن [`pipeline`]. قم بإنشاء `pipeline` لتحليل المشاعر مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model") +>>> classifier(text) +[{'label': 'POSITIVE', 'score': 0.9994940757751465}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قم يتجزئة النص وإرجاع تنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") +>>> inputs = tokenizer(text, return_tensors="pt") +``` + +مرر المدخلات إلى النموذج واسترجع `logits`: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") +>>> with torch.no_grad(): +... logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم `id2label` لتحويلها إلى تصنيف نصي: + +```py +>>> predicted_class_id = logits.argmax().item() +>>> model.config.id2label[predicted_class_id] +'POSITIVE' +``` + + +قم بتحليل النص وإرجاع تنسيقات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model") +>>> inputs = tokenizer(text, return_tensors="tf") +``` + +قم بتمرير مدخلاتك إلى النموذج وإرجاع `logits`: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") +>>> logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم `id2label` لتحويلها إلى تصنيف نصي: + +```py +>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0]) +>>> model.config.id2label[predicted_class_id] +'POSITIVE' +``` + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/summarization.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/summarization.md new file mode 100644 index 0000000000000000000000000000000000000000..17dbcb42e8374e6ed43b1ccb43d46afdbbb90635 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/summarization.md @@ -0,0 +1,397 @@ + + +# التلخيص (Summarization) + +[[open-in-colab]] + + + +يقوم التلخيص بإنشاء نسخة مختصرة من مستند أو مقال، حيث يلتقط جميع المعلومات المهمة. بالإضافة إلى الترجمة، يعتبر التلخيص مثالاً آخر على مهمة يمكن صياغتها كتسلسل إلى تسلسل. يمكن أن يكون التلخيص: + +- استخراجي: استخراج أهم المعلومات من مستند. +- تجريدي: إنشاء نص جديد يلخص أهم المعلومات. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق [T5](https://huggingface.co/google-t5/t5-small) على مجموعة فرعية من مشاريع قوانين ولاية كاليفورنيا من مجموعة بيانات [BillSum](https://huggingface.co/datasets/billsum) للتلخيص التجريدي. +2. استخدام النموذج المضبوط بدقة للتنبؤ. + + + +لمشاهدة جميع البنى ونقاط التفتيش المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/summarization) + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate rouge_score +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند المطالبة، أدخل الرمز المميز لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات BillSum + +ابدأ بتحميل جزء صغير من بيانات مشاريع القوانين الخاصة بولاية كاليفورنيا من مجموعة بيانات BillSum في مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> billsum = load_dataset("billsum", split="ca_test") +``` + +قسّم مجموعة البيانات إلى مجموعتي تدريب واختبار باستخدام الدالة [`~datasets.Dataset.train_test_split`]: + +```py +>>> billsum = billsum.train_test_split(test_size=0.2) +``` + +ثم ألقِ نظرة على مثال: + +```py +>>> billsum["train"][0] +{'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\nThis bill would provide that no reimbursement is required by this act for a specified reason.', + 'text': 'The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n10295.35.\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee’s or dependent’s actual or perceived gender identity, including, but not limited to, the employee’s or dependent’s identification as transgender.\n(2) For purposes of this section, “contract” includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\n(4) The requirements of this section shall apply only to those portions of a contractor’s operations that occur under any of the following conditions:\n(A) Within the state.\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor’s presence at that location is connected to a contract with the state.\n(C) Elsewhere in the United States where work related to a state contract is being performed.\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.', + 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'} +``` + +هناك مُدخلان سترغب في استخدامهما: + +- `text`: نص القانون الذي سيكون مُدخلًا للنموذج. +- `summary`: نسخة مُختصرة من `text` والتي ستكون هدف النموذج. + +## المعالجة المسبقة (Preprocess) + +الخطوة التالية هي تحميل مجزء النصوص T5 لمعالجة `text` و `summary`: + +```py +>>> from transformers import AutoTokenizer + +>>> checkpoint = "google-t5/t5-small" +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` + +وظيفة المعالجة المسبقة التي تريد إنشاءها تحتاج إلى: + +1. إضافة بادئة للمُدخل باستخدام توجيه حتى يعرف T5 أن هذه مهمة تلخيص. تتطلب بعض النماذج القادرة على مهام البرمجة اللغوية العصبية المتعددة توجيهات لمهام مُحددة. +2. استخدام مُعامل الكلمة الرئيسية `text_target` عند ترميز التصنيفات. +3. قصّ التسلسلات بحيث لا يزيد طولها عن الحد الأقصى الذي تم تعيينه بواسطة مُعامل `max_length`. + +```py +>>> prefix = "summarize: " + +>>> def preprocess_function(examples): +... inputs = [prefix + doc for doc in examples["text"]] +... model_inputs = tokenizer(inputs, max_length=1024, truncation=True) + +... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True) + +... model_inputs["labels"] = labels["input_ids"] +... return model_inputs +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] الخاصة بـ 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_billsum = billsum.map(preprocess_function, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorForSeq2Seq`]. الأكثر كفاءة *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء عملية التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint) +``` + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf") +``` + + + +## التقييم (Evaluate) + +يُعد تضمين مقياس أثناء التدريب مفيدًا غالبًا لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل مقياس [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) (راجع [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) الخاصة بـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> rouge = evaluate.load("rouge") +``` + +ثم قم بإنشاء دالة تُمرر تنبؤاتك وتصنيفاتك إلى [`~evaluate.EvaluationModule.compute`] لحساب مقياس ROUGE: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True) +... labels = np.where(labels != -100, labels, tokenizer.pad_token_id) +... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) + +... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) + +... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions] +... result["gen_len"] = np.mean(prediction_lens) + +... return {k: round(v, 4) for k, v in result.items()} +``` + +دالة `compute_metrics` الخاصة بك جاهزة الآن، وستعود إليها عند إعداد التدريب الخاص بك. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام [`Trainer`]، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! قم بتحميل T5 باستخدام [`AutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +في هذه المرحلة، لم يتبق سوى ثلاث خطوات: + +1. حدد مُعامِلات التدريب الخاصة بك في [`Seq2SeqTrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يُحدد مكان حفظ نموذجك. ستدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (تحتاج إلى تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم مقياس ROUGE وحفظ نقطة تفتيش التدريب. +2. مرر مُعامِلات التدريب إلى [`Seq2SeqTrainer`] جنبًا إلى جنب مع النموذج ومجموعة البيانات والمُحلِّل اللغوي وجامع البيانات ودالة `compute_metrics`. +3. استدعِ [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = Seq2SeqTrainingArguments( +... output_dir="my_awesome_billsum_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... weight_decay=0.01, +... save_total_limit=3, +... num_train_epochs=4, +... predict_with_generate=True, +... fp16=True, #change to bf16=True for XPU +... push_to_hub=True, +... ) + +>>> trainer = Seq2SeqTrainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_billsum["train"], +... eval_dataset=tokenized_billsum["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل التعلم وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer, AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل T5 باستخدام [`TFAutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_billsum["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... tokenized_billsum["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers لديها دالة خسارة ذات صلة بالمهمة افتراضيًا، لذلك لست بحاجة إلى تحديد واحدة ما لم تكن ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر شيئين يجب إعدادهما قبل بدء التدريب هما حساب درجة ROUGE من التنبؤات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم كلاهما باستخدام [استدعاءات Keras](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_test_set) +``` + +حدد مكان دفع نموذجك ومُحلِّلك اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_billsum_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع استدعاءاتك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا حول كيفية ضبط نموذج للتجميع، ألقِ نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb) +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb) المقابل. + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +خدد بعض النصوص الذي ترغب في تلخيصها. بالنسبة لـ T5، تحتاج إلى إضافة بادئة إلى مُدخلاتك اعتمادًا على المهمة التي تعمل عليها. بالنسبة التلخيص، يجب عليك إضافة بادئة إلى مُدخلاتك كما هو موضح أدناه: + +```py +>>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes." +``` + +أبسط طريقة لتجربة نموذجك المضبوط للاستدلال هي استخدامه في [`pipeline`]. استخدم `pipeline` للتلخيص باستخدام نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> summarizer = pipeline("summarization", model="username/my_awesome_billsum_model") +>>> summarizer(text) +[{"summary_text": "The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country."}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قسم النص وإرجع `input_ids` كتنسورات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model") +>>> inputs = tokenizer(text, return_tensors="pt").input_ids +``` + +استخدم طريقة [`~generation.GenerationMixin.generate`] لإنشاء التلخيص. لمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والمعلمات للتحكم في التوليد، راجع واجهة برمجة تطبيقات [توليد النص](../main_classes/text_generation). + +```py +>>> from transformers import AutoModelForSeq2SeqLM + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.' +``` + + +قسم النص وإرجع `input_ids` كتنسورات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model") +>>> inputs = tokenizer(text, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء التلخيص. لمزيد من التفاصيل حول استراتيجيات توليد النص المختلفة والمعلمات للتحكم في التوليد، راجع واجهة برمجة تطبيقات [توليد النص](../main_classes/text_generation). + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model") +>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.' +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/token_classification.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/token_classification.md new file mode 100644 index 0000000000000000000000000000000000000000..e311482aeccb061a703144e2c7325b90971d883b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/token_classification.md @@ -0,0 +1,550 @@ + + +# تصنيف الرموز(Token classification) + +[[open-in-colab]] + + + +يهدف تصنيف الرموز إلى إعطاء تسمية لكل رمز على حدة في الجملة. من أكثر مهام تصنيف الرموز شيوعًا هو التعرف على الكيانات المسماة (NER). يحاول NER تحديد تسمية لكل كيان في الجملة، مثل شخص، أو مكان، أو منظمة. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) على مجموعة بيانات [WNUT 17](https://huggingface.co/datasets/wnut_17) للكشف عن كيانات جديدة. +2. استخدام نموذجك المضبوط بدقة للاستدلال. + + + +للاطلاع جميع البنى والنقاط المتوافقة مع هذه المهمة، نوصي بالرجوع من [صفحة المهمة](https://huggingface.co/tasks/token-classification). + + + +قبل أن تبدأ، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate seqeval +``` + +نحن نشجعك على تسجيل الدخول إلى حساب HuggingFace الخاص بك حتى تتمكن من تحميل ومشاركة نموذجك مع المجتمع. عندما يُطلب منك، أدخل رمزك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات WNUT 17 + +ابدأ بتحميل مجموعة بيانات WNUT 17 من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> wnut = load_dataset("wnut_17") +``` + +ثم ألق نظرة على مثال: + +```py +>>> wnut["train"][0] +{'id': '0', + 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], + 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.'] +} +``` + +يمثل كل رقم في `ner_tags` كياناً. حوّل الأرقام إلى أسماء التصنيفات لمعرفة ماهية الكيانات: + +```py +>>> label_list = wnut["train"].features[f"ner_tags"].feature.names +>>> label_list +[ + "O", + "B-corporation", + "I-corporation", + "B-creative-work", + "I-creative-work", + "B-group", + "I-group", + "B-location", + "I-location", + "B-person", + "I-person", + "B-product", + "I-product", +] +``` + +يشير الحرف الذي يسبق كل `ner_tag` إلى موضع الرمز للكيان: + +- `B-` يشير إلى بداية الكيان. +- `I-` يشير إلى أن الرمز يقع ضمن نفس الكيان (على سبيل المثال، الرمز `State` هو جزء من كيان مثل `Empire State Building`). +- `0` يشير إلى أن الرمز لا يمثل أي كيان. + +## المعالجة المسبقة(Preprocess) + + + +الخطوة التالية هي تحميل مُجزِّئ النصوص DistilBERT للمعالجة المسبقة لحقل `tokens`: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") +``` + +كما رأيت في حقل `tokens` المثال أعلاه، يبدو أن المدخل قد تم تحليله بالفعل. لكن المدخل لم يُجزأ بعد ويتعيّن عليك ضبط `is_split_into_words=True` لتقسيم الكلمات إلى كلمات فرعية. على سبيل المثال: + +```py +>>> example = wnut["train"][0] +>>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True) +>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"]) +>>> tokens +['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]'] +``` + +ومع ذلك، يضيف هذا بعض الرموز الخاصة `[CLS]` و`[SEP]` وتقسيم الكلمات إلى أجزاء يُنشئ عدم تطابق بين المُدخلات والتسميات. قد يتم تقسيم كلمة واحدة تقابل تسمية واحدة الآن إلى كلمتين فرعيتين. ستحتاج إلى إعادة محاذاة الرموز والتسميات عن طريق: + +1. ربط كل رمز بالكلمة الأصلية باستخدام الخاصية [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids). +2. تعيين التسمية `-100` للرموز الخاصة `[CLS]` و`[SEP]` بحيث يتم تجاهلها بواسطة دالة الخسارة PyTorch (انظر [CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)). +3. تسمية الرمز الأول فقط لكلمة معينة. قم بتعيين `-100` لأجزاء الكلمة الأخرى. + +هنا كيف يمكنك إنشاء وظيفة لإعادة محاذاة الرموز والتسميات، وقص الجمل لتتجاوز الحد الأقصى لطول مُدخلات DistilBERT: + +```py +>>> def tokenize_and_align_labels(examples): +... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True) + +... labels = [] +... for i, label in enumerate(examples[f"ner_tags"]): +... word_ids = tokenized_inputs.word_ids(batch_index=i) # تعيين الرموز إلى كلماتهم المقابلة. +... previous_word_idx = None +... label_ids = [] +... for word_idx in word_ids: # تعيين الرموز الخاصة إلى -100. +... if word_idx is None: +... label_ids.append(-100) +... elif word_idx != previous_word_idx: # تسمية الرمز الأول فقط لكلمة معينة. +... label_ids.append(label[word_idx]) +... else: +... label_ids.append(-100) +... previous_word_idx = word_idx +... labels.append(label_ids) + +... tokenized_inputs["labels"] = labels +... return tokenized_inputs +``` + +لتطبيق هذه العملية على كامل مجموعة البيانات، استخدم الدالة [`~datasets.Dataset.map`] لمجموعة بيانات 🤗. يمكنك تسريع الدالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True) +``` + +الآن قم بإنشاء دفعة من الأمثلة باستخدام [`DataCollatorWithPadding`].من الأفضل استخدام *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بالكامل إلى الطول الأقصى. + + + +```py +>>> from transformers import DataCollatorForTokenClassification + +>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer) +``` + + +```py +>>> from transformers import DataCollatorForTokenClassification + +>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf") +``` + + + +## التقييم(Evaluate) + +يُعدّ تضمين مقياس أثناء التدريب مفيدًا في تقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة مع مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، قم بتحميل إطار [seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) (انظر جولة 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) لمعرفة المزيد حول كيفية تحميل وحساب مقياس). يُخرج seqeval عدة نتائج: الدقة، والاستذكار، ومقياس F1، والدقة. + +```py +>>> import evaluate + +>>> seqeval = evaluate.load("seqeval") +``` + +احصل على تسميات الكيانات المسماة (NER) أولاً،ثم أنشئ دالة تُمرر تنبؤاتك وتسمياتك الصحيحة إلى [`~evaluate.EvaluationModule.compute`] لحساب النتائج: + +```py +>>> import numpy as np + +>>> labels = [label_list[i] for i in example[f"ner_tags"]] + +>>> def compute_metrics(p): +... predictions, labels = p +... predictions = np.argmax(predictions, axis=2) + +... true_predictions = [ +... [label_list[p] for (p, l) in zip(prediction, label) if l != -100] +... for prediction, label in zip(predictions, labels) +... ] +... true_labels = [ +... [label_list[l] for (p, l) in zip(prediction, label) if l != -100] +... for prediction, label in zip(predictions, labels) +... ] + +... results = seqeval.compute(predictions=true_predictions, references=true_labels) +... return { +... "precision": results["overall_precision"], +... "recall": results["overall_recall"], +... "f1": results["overall_f1"], +... "accuracy": results["overall_accuracy"], +... } +``` + +دالة `compute_metrics` جاهزة للاستخدام، وستحتاج إليها عند إعداد التدريب. + +## التدريب(Train) + +قبل تدريب النموذج، جهّز خريطة تربط بين المعرّفات المتوقعة وتسمياتها باستخدام `id2label` و `label2id`: + +```py +>>> id2label = { +... 0: "O", +... 1: "B-corporation", +... 2: "I-corporation", +... 3: "B-creative-work", +... 4: "I-creative-work", +... 5: "B-group", +... 6: "I-group", +... 7: "B-location", +... 8: "I-location", +... 9: "B-person", +... 10: "I-person", +... 11: "B-product", +... 12: "I-product", +... } +>>> label2id = { +... "O": 0, +... "B-corporation": 1, +... "I-corporation": 2, +... "B-creative-work": 3, +... "I-creative-work": 4, +... "B-group": 5, +... "I-group": 6, +... "B-location": 7, +... "I-location": 8, +... "B-person": 9, +... "I-person": 10, +... "B-product": 11, +... "I-product": 12, +... } +``` + + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام [`Trainer`], ألق نظرة على الدليل التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت مستعد الآن لبدء تدريب نموذجك! قم بتحميل DistilBERT مع [`AutoModelForTokenClassification`] إلى جانب عدد التصنيفات المتوقعة، وخريطة التسميات: + +```py +>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer + +>>> model = AutoModelForTokenClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id +... ) +``` + +في هذه المرحلة، هناك ثلاث خطوات فقط متبقية: + +1. حدد معلمات التدريب الخاصة بك في [`TrainingArguments`]. المعامل الوحيد المطلوب هو `output_dir` الذي يحدد مكان حفظ نموذجك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب أن تكون مسجلاً الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم درجات seqeval وحفظ تسخة التدريب. +2. قم بتمرير معاملات التدريب إلى [`Trainer`] إلى جانب النموذج، ومجموعة البيانات، والمُجزِّئ اللغوي، و`data collator`، ودالة `compute_metrics`. +3.استدعِ [`~Trainer.train`] لتدريب نموذجك. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_wnut_model", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... num_train_epochs=2, +... weight_decay=0.01, +... eval_strategy="epoch", +... save_strategy="epoch", +... load_best_model_at_end=True, +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_wnut["train"], +... eval_dataset=tokenized_wnut["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك على Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن على دراية بتعديل نموذج باستخدام Keras، ألق نظرة على الدليل التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +للتعديل على نموذج في TensorFlow، ابدأ بإعداد دالة محسن، وجدول معدل التعلم، وبعض معلمات التدريب: + +```py +>>> from transformers import create_optimizer + +>>> batch_size = 16 +>>> num_train_epochs = 3 +>>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs +>>> optimizer, lr_schedule = create_optimizer( +... init_lr=2e-5, +... num_train_steps=num_train_steps, +... weight_decay_rate=0.01, +... num_warmup_steps=0, +... ) +``` + +ثم يمكنك تحميل DistilBERT مع [`TFAutoModelForTokenClassification`] إلى جانب عدد التسميات المتوقعة، وتخطيطات التسميات: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained( +... "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id +... ) +``` + +قم بتحويل مجموعات بياناتك إلى تنسيق `tf.data.Dataset` مع [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_wnut["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_validation_set = model.prepare_tf_dataset( +... tokenized_wnut["validation"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +هيّئ النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن نماذج Transformers تتضمن دالة خسارة افتراضية مرتبطة بالمهمة، لذلك لا تحتاج إلى تحديد واحدة إلا إذا كنت ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر أمرين يجب إعدادهما قبل بدء التدريب هو حساب درجات seqeval من التنبؤات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم ذلك باستخدام [Keras callbacks](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set) +``` + +حدد مكان دفع نموذجك والمحلل اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_wnut_model", +... tokenizer=tokenizer, +... ) +``` + +ثم جمّع callbacks الخاصة بك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز الآن لبدء تدريب نموذجك! قم باستدعاء [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع بيانات التدريب والتحقق، وعدد الحقبات، وcallbacks لتعديل النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تفصيلاً حول كيفية تعديل نموذج لتصنيف الرموز، ألق نظرة على الدفتر المقابل +[دفتر PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb) +أو [دفتر TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). + + + +## الاستدلال(Inference) + +رائع، الآن بعد أن قمت بتعديل نموذج، يمكنك استخدامه للاستدلال! + +احصل على بعض النصوص التي تريد تشغيل الاستدلال عليها: + +```py +>>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco." +``` + +أبسط طريقة لتجربة نموذجك المُدرب مسبقًا للاستدلال هي استخدامه في [`pipeline`]. قم بتنفيذ `pipeline` لتصنيف الكيانات المسماة مع نموذجك، ومرر نصك إليه: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model") +>>> classifier(text) +[{'entity': 'B-location', + 'score': 0.42658573, + 'index': 2, + 'word': 'golden', + 'start': 4, + 'end': 10}, + {'entity': 'I-location', + 'score': 0.35856336, + 'index': 3, + 'word': 'state', + 'start': 11, + 'end': 16}, + {'entity': 'B-group', + 'score': 0.3064001, + 'index': 4, + 'word': 'warriors', + 'start': 17, + 'end': 25}, + {'entity': 'B-location', + 'score': 0.65523505, + 'index': 13, + 'word': 'san', + 'start': 80, + 'end': 83}, + {'entity': 'B-location', + 'score': 0.4668663, + 'index': 14, + 'word': 'francisco', + 'start': 84, + 'end': 93}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قسّم النص إلى رموز وأرجع المُوتّرات بلغة PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> inputs = tokenizer(text, return_tensors="pt") +``` + +مرر مدخلاتك إلى النموذج واحصل على `logits`: + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> with torch.no_grad(): +... logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم جدول `id2label` الخاصة بالنموذج لتحويلها إلى تسمية نصية: + +```py +>>> predictions = torch.argmax(logits, dim=2) +>>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]] +>>> predicted_token_class +['O', + 'O', + 'B-location', + 'I-location', + 'B-group', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'B-location', + 'B-location', + 'O', + 'O'] +``` + + +قسّم النص إلى رموز وأرجع المُوتّرات ب TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> inputs = tokenizer(text, return_tensors="tf") +``` + +مرر مدخلاتك إلى النموذج واحصل على `logits`: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model") +>>> logits = model(**inputs).logits +``` + +استخرج الفئة ذات الاحتمالية الأعلى، واستخدم جدول `id2label` الخاصة بالنموذج لتحويلها إلى تسمية نصية: + +```py +>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1) +>>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()] +>>> predicted_token_class +['O', + 'O', + 'B-location', + 'I-location', + 'B-group', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'O', + 'B-location', + 'B-location', + 'O', + 'O'] +``` + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/translation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/translation.md new file mode 100644 index 0000000000000000000000000000000000000000..6245b903c22d63ef295cff91a98bb505ef6ee2ca --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks/translation.md @@ -0,0 +1,407 @@ + + +# الترجمة(Translation) + +[[open-in-colab]] + + + +الترجمة هي عملية تحويل سلسلة نصية من لغة إلى أخرى. وهي إحدى المهام التي يمكن صياغتها كمسألة تسلسل إلى تسلسل، وهو إطار عمل قوي لإنتاج مخرجات من مدخلات، مثل الترجمة أو التلخيص. تُستخدم أنظمة الترجمة عادةً للترجمة بين نصوص لغات مختلفة، ويمكن استخدامها أيضًا لترجمة الكلام أو لمهام تجمع بين النصوص والكلام، مثل تحويل النص إلى كلام أو تحويل الكلام إلى نص. + +سيوضح لك هذا الدليل كيفية: + +1. ضبط دقيق لنموذج [T5](https://huggingface.co/google-t5/t5-small) على المجموعة الفرعية الإنجليزية-الفرنسية من مجموعة بيانات [OPUS Books](https://huggingface.co/datasets/opus_books) لترجمة النص الإنجليزي إلى الفرنسية. +2. استخدام النموذج المضبوط بدقة للاستدلال. + + + +لمشاهدة جميع البنى والنسخ المتوافقة مع هذه المهمة، نوصي بالتحقق من [صفحة المهمة](https://huggingface.co/tasks/translation). + + + +قبل البدء، تأكد من تثبيت جميع المكتبات الضرورية: + +```bash +pip install transformers datasets evaluate sacrebleu +``` + +نشجعك على تسجيل الدخول إلى حساب Hugging Face الخاص بك حتى تتمكن من تحميل نموذجك ومشاركته مع المجتمع. عند الطلب، أدخل الرمز المميز الخاص بك لتسجيل الدخول: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## تحميل مجموعة بيانات OPUS Books + +ابدأ بتحميل المجموعة الفرعية الإنجليزية-الفرنسية من مجموعة بيانات [OPUS Books](https://huggingface.co/datasets/opus_books) من مكتبة 🤗 Datasets: + +```py +>>> from datasets import load_dataset + +>>> books = load_dataset("opus_books", "en-fr") +``` + +قسّم مجموعة البيانات إلى مجموعة تدريب ومجموعة اختبار باستخدام طريقة [`~datasets.Dataset.train_test_split`]: + +```py +>>> books = books["train"].train_test_split(test_size=0.2) +``` + +ثم ألقِ نظرة على مثال: + +```py +>>> books["train"][0] +{'id': '90560', + 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.', + 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientôt nous fûmes rentrés dans notre élément.'}} +``` + +`translation`: ترجمة إنجليزية وفرنسية للنص. + +## المعالجة المسبقة(Preprocess) + + + +الخطوة التالية هي تحميل مُجزئ T5 لمعالجة أزواج اللغة الإنجليزية-الفرنسية: + +```py +>>> from transformers import AutoTokenizer + +>>> checkpoint = "google-t5/t5-small" +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) +``` + +يجب أن تقوم دالة المعالجة المسبقة التي تُريد إنشاءها بما يلي: + +1. إضافة بادئة إلى المُدخل بمُوجه حتى يعرف T5 أن هذه مهمة ترجمة. تتطلب بعض النماذج القادرة على أداء مهام متعددة توجيهًا لمهام مُحددة. +2. تعيين اللغة الهدف (الفرنسية) في معامل `text_target` لضمان معالجة المُجزئ للنص بشكل صحيح. إذا لم تُعيّن `text_target`، فسيُعالج المُجزئ النص على أنه إنجليزي. +3. اقتطاع التسلسلات بحيث لا يزيد طولها عن الحد الأقصى الذي يحدده معامل `max_length`. + +```py +>>> source_lang = "en" +>>> target_lang = "fr" +>>> prefix = "translate English to French: " + +>>> def preprocess_function(examples): +... inputs = [prefix + example[source_lang] for example in examples["translation"]] +... targets = [example[target_lang] for example in examples["translation"]] +... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True) +... return model_inputs +``` + +لتطبيق دالة المعالجة المسبقة على مجموعة البيانات بأكملها، استخدم طريقة [`~datasets.Dataset.map`] من 🤗 Datasets. يمكنك تسريع دالة `map` عن طريق تعيين `batched=True` لمعالجة عناصر متعددة من مجموعة البيانات في وقت واحد: + +```py +>>> tokenized_books = books.map(preprocess_function, batched=True) +``` + +الآن أنشئ دفعة من الأمثلة باستخدام [`DataCollatorForSeq2Seq`]. من الأكثر كفاءة *الحشو الديناميكي* للجمل إلى أطول طول في دفعة أثناء التجميع، بدلاً من حشو مجموعة البيانات بأكملها إلى الحد الأقصى للطول. + + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint) +``` + + + +```py +>>> from transformers import DataCollatorForSeq2Seq + +>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf") +``` + + + +## التقييم (Evaluate) + +غالباً ما يكون تضمين مقياس أثناء التدريب مفيداً لتقييم أداء نموذجك. يمكنك تحميل طريقة تقييم بسرعة باستخدام مكتبة 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index). لهذه المهمة، حمّل مقياس [SacreBLEU](https://huggingface.co/spaces/evaluate-metric/sacrebleu) (راجع [الجولة السريعة](https://huggingface.co/docs/evaluate/a_quick_tour) لـ 🤗 Evaluate لمعرفة المزيد حول كيفية تحميل وحساب مقياس): + +```py +>>> import evaluate + +>>> metric = evaluate.load("sacrebleu") +``` + +ثم أنشئ دالة تُمرر تنبؤاتك وتسمياتك إلى [`~evaluate.EvaluationModule.compute`] لحساب درجة SacreBLEU: + +```py +>>> import numpy as np + +>>> def postprocess_text(preds, labels): +... preds = [pred.strip() for pred in preds] +... labels = [[label.strip()] for label in labels] + +... return preds, labels + +>>> def compute_metrics(eval_preds): +... preds, labels = eval_preds +... if isinstance(preds, tuple): +... preds = preds[0] +... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) + +... labels = np.where(labels != -100, labels, tokenizer.pad_token_id) +... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) + +... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) + +... result = metric.compute(predictions=decoded_preds, references=decoded_labels) +... result = {"bleu": result["score"]} + +... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] +... result["gen_len"] = np.mean(prediction_lens) +... result = {k: round(v, 4) for k, v in result.items()} +... return result +``` + +دالة `compute_metrics` الخاصة بك جاهزة الآن، وسوف تعود إليها عند إعداد التدريب. + +## التدريب (Train) + + + + + + +إذا لم تكن معتادًا على ضبط دقيق نموذج باستخدام [`Trainer`], فألقِ نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-with-pytorch-trainer)! + + + +أنت جاهز لبدء تدريب نموذجك الآن! حمّل T5 باستخدام [`AutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +في هذه المرحلة، تبقى ثلاث خطوات فقط: + +1. حدد مُعاملات للتدريب في [`Seq2SeqTrainingArguments`]. المُعامل الوحيدة المطلوبة هي `output_dir` التي تحدد مكان حفظ النموذج الخاص بك. ستقوم بدفع هذا النموذج إلى Hub عن طريق تعيين `push_to_hub=True` (يجب عليك تسجيل الدخول إلى Hugging Face لتحميل نموذجك). في نهاية كل حقبة، سيقوم [`Trainer`] بتقييم مقياس SacreBLEU وحفظ نقطة تدقيق التدريب. +2. مرر مُعاملات التدريب إلى [`Seq2SeqTrainer`] جنبًا إلى جنب مع النموذج ومجموعة البيانات والمعالج اللغوي وجامع البيانات ووظيفة `compute_metrics`. +3. نفّذ [`~Trainer.train`] لضبط نموذجك. + +```py +>>> training_args = Seq2SeqTrainingArguments( +... output_dir="my_awesome_opus_books_model", +... eval_strategy="epoch", +... learning_rate=2e-5, +... per_device_train_batch_size=16, +... per_device_eval_batch_size=16, +... weight_decay=0.01, +... save_total_limit=3, +... num_train_epochs=2, +... predict_with_generate=True, +... fp16=True, #change to bf16=True for XPU +... push_to_hub=True, +... ) + +>>> trainer = Seq2SeqTrainer( +... model=model, +... args=training_args, +... train_dataset=tokenized_books["train"], +... eval_dataset=tokenized_books["test"], +... processing_class=tokenizer, +... data_collator=data_collator, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +بمجرد اكتمال التدريب، شارك نموذجك مع Hub باستخدام طريقة [`~transformers.Trainer.push_to_hub`] حتى يتمكن الجميع من استخدام نموذجك: + +```py +>>> trainer.push_to_hub() +``` + + + + +إذا لم تكن معتادًا على ضبط نموذج باستخدام Keras، فألق نظرة على البرنامج التعليمي الأساسي [هنا](../training#train-a-tensorflow-model-with-keras)! + + +لضبط نموذج في TensorFlow، ابدأ بإعداد دالة مُحسِّن وجدول معدل تعلم وبعض المعلمات الفائقة للتدريب: + +```py +>>> from transformers import AdamWeightDecay + +>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01) +``` + +ثم يمكنك تحميل T5 باستخدام [`TFAutoModelForSeq2SeqLM`]: + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint) +``` + +حوّل مجموعات البيانات الخاصة بك إلى تنسيق `tf.data.Dataset` باستخدام [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]: + +```py +>>> tf_train_set = model.prepare_tf_dataset( +... tokenized_books["train"], +... shuffle=True, +... batch_size=16, +... collate_fn=data_collator, +... ) + +>>> tf_test_set = model.prepare_tf_dataset( +... tokenized_books["test"], +... shuffle=False, +... batch_size=16, +... collate_fn=data_collator, +... ) +``` + +قم بتكوين النموذج للتدريب باستخدام [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). لاحظ أن جميع نماذج Transformers تحتوي على دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذلك لا تحتاج إلى تحديد واحدة إلا إذا كنت ترغب في ذلك: + +```py +>>> import tensorflow as tf + +>>> model.compile(optimizer=optimizer) # No loss argument! +``` + +آخر شيئين يجب إعدادهما قبل بدء التدريب هما حساب مقياس SacreBLEU من التوقعات، وتوفير طريقة لدفع نموذجك إلى Hub. يتم كلاهما باستخدام [استدعاءات Keras](../main_classes/keras_callbacks). + +مرر دالة `compute_metrics` الخاصة بك إلى [`~transformers.KerasMetricCallback`]: + +```py +>>> from transformers.keras_callbacks import KerasMetricCallback + +>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_test_set) +``` + +حدد مكان دفع نموذجك ومعالجك اللغوي في [`~transformers.PushToHubCallback`]: + +```py +>>> from transformers.keras_callbacks import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="my_awesome_opus_books_model", +... tokenizer=tokenizer, +... ) +``` + +ثم اجمع استدعاءاتك معًا: + +```py +>>> callbacks = [metric_callback, push_to_hub_callback] +``` + +أخيرًا، أنت جاهز لبدء تدريب نموذجك! اتصل بـ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) مع مجموعات بيانات التدريب والتحقق من الصحة وعدد الحقب واستدعاءاتك لضبط النموذج: + +```py +>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks) +``` + +بمجرد اكتمال التدريب، يتم تحميل نموذجك تلقائيًا إلى Hub حتى يتمكن الجميع من استخدامه! + + + + + +للحصول على مثال أكثر تعمقًا لكيفية ضبط نموذج للترجمة، ألق نظرة على [دفتر ملاحظات PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb) المقابل +أو [دفتر ملاحظات TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb). + + + +## الاستدلال (Inference) + +رائع، الآن بعد أن قمت بضبط نموذج، يمكنك استخدامه للاستدلال! + +أحضر بعض النصوص التي ترغب في ترجمتها إلى لغة أخرى. بالنسبة لـ T5، تحتاج إلى إضافة بادئة إلى مدخلاتك اعتمادًا على المهمة التي تعمل عليها. للترجمة من الإنجليزية إلى الفرنسية، يجب عليك إضافة بادئة إلى مدخلاتك كما هو موضح أدناه: + +```py +>>> text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria." +``` + +أبسط طريقة لتجربة نموذجك المضبوط للاستدلال هي استخدامه في [`pipeline`]. قم بإنشاء مثيل لـ `pipeline` للترجمة باستخدام نموذجك، ومرر النص الخاص بك إليه: + +```py +>>> from transformers import pipeline + +# تغيير `xx` إلى لغة الإدخال و `yy` إلى لغة المخرجات المطلوبة. +# أمثلة: "en" للغة الإنجليزية، "fr" للغة الفرنسية، "de" للغة الألمانية، "es" للغة الإسبانية، "zh" للغة الصينية، إلخ؛ translation_en_to_fr تترجم من الإنجليزية إلى الفرنسية +# يمكنك عرض جميع قوائم اللغات هنا - https://huggingface.co/languages +>>> translator = pipeline("translation_xx_to_yy", model="username/my_awesome_opus_books_model") +>>> translator(text) +[{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}] +``` + +يمكنك أيضًا تكرار نتائج `pipeline` يدويًا إذا أردت: + + + +قم بتحويل النص إلى رموز وإرجاع `input_ids` كموترات PyTorch: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_opus_books_model") +>>> inputs = tokenizer(text, return_tensors="pt").input_ids +``` + +استخدم الدالة [`~generation.GenerationMixin.generate`] لإنشاء الترجمة. لمزيد من التفاصيل حول استراتيجيات توليد النصوص المختلفة والمعلمات للتحكم في التوليد، تحقق من واجهة برمجة تطبيقات [توليد النصوص](../main_classes/text_generation). + +```py +>>> from transformers import AutoModelForSeq2SeqLM + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_opus_books_model") +>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'Les lignées partagent des ressources avec des bactéries enfixant l'azote.' +``` + + +قم بتحويل النص إلى رموز وإرجاع `input_ids` كموترات TensorFlow: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_opus_books_model") +>>> inputs = tokenizer(text, return_tensors="tf").input_ids +``` + +استخدم طريقة [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] لإنشاء الترجمة. لمزيد من التفاصيل حول استراتيجيات توليد النصوص المختلفة والمعلمات للتحكم في التوليد، تحقق من واجهة برمجة تطبيقات [توليد النصوص](../main_classes/text_generation). + +```py +>>> from transformers import TFAutoModelForSeq2SeqLM + +>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_opus_books_model") +>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95) +``` + +فك تشفير معرفات الرموز المولدة مرة أخرى إلى نص: + +```py +>>> tokenizer.decode(outputs[0], skip_special_tokens=True) +'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.' +``` + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks_explained.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks_explained.md new file mode 100644 index 0000000000000000000000000000000000000000..b91297be7d2795d12b1f5ace4aa42fd89b5bb0db --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tasks_explained.md @@ -0,0 +1,279 @@ +# كيف تُنجز نماذج 🤗 Transformers المهام؟ + +في [ما الذي يمكن أن تفعله نماذج 🤗 Transformers](task_summary)، تعلمت عن معالجة اللغات الطبيعية (NLP)، والخطاب والصوت، ورؤية الحاسب، وبعض تطبيقاتها المهمة. ستلقي هذه الصفحة نظرة فاحصة على كيفية حل النماذج لهذه المهام وتوضيح ما يحدث ما يحدث وراء الكواليس. هناك العديد من الطرق لحل مهمة معينة، وقد تنفذ بعض النماذج تقنيات معينة أو حتى تتناول المهمة من زاوية جديدة، ولكن بالنسبة لنماذج Transformer، فإن الفكرة العامة هي نفسها. وبفضل تصميمها المرن، فنظراً لهيكلها المرن، تُعدّ معظم النماذج عبارة عن متغير من بنية المُشفّر (Encoder) أو المُفكّك (Decoder) أو المُشفّر - المُفكّك (Encoder-Decoder). بالإضافة إلى نماذج Transformer، تحتوي مكتبتنا أيضًا على العديد من الشبكات العصبية التلافيفية (CNNs)، والتي لا تزال تستخدم حتى اليوم لمهام رؤية الحاسب. سنشرح أيضًا كيف تعمل شبكة عصبية تلافيفية CNN الحديثة. + +لشرح كيفية حل المهام، سنشرح ما يحدث داخل النموذج لإخراج تنبؤات مفيدة. + +- [Wav2Vec2](model_doc/wav2vec2) لتصنيف الصوت والتعرف التلقائي على الكلام (ASR) +- [Vision Transformer (ViT)](model_doc/vit) و [ConvNeXT](model_doc/convnext) لتصنيف الصور +- [DETR](model_doc/detr) للكشف عن الأجسام +- [Mask2Former](model_doc/mask2former) لتجزئة الصورة +- [GLPN](model_doc/glpn) لتقدير العمق +- [BERT](model_doc/bert) لمهام NLP مثل تصنيف النصوص، وتصنيف الرموز، والإجابة على الأسئلة التي تستخدم مشفرًا +- [GPT2](model_doc/gpt2) لمهام NLP مثل توليد النصوص التي تستخدم فك تشفير +- [BART](model_doc/bart) لمهام NLP مثل الملخص والترجمة التي تستخدم ترميز-فك تشفير + + + +قبل المتابعة، من الجيد أن يكون لديك بعض المعرفة الأساسية بهيكلية المحولات (Transformer Architecture) الأصلية. إن معرفة كيفية عمل المُشفّرات (Encoders) والمُفكّكات (Decoders) وآلية الانتباه (Attention Mechanism) سوف تساعدك في فهم كيفية عمل نماذج Transformer المختلفة. إذا كنت مبتدئًا أو بحاجة إلى مراجعة، فراجع [دورتنا](https://huggingface.co/course/chapter1/4؟fw=pt) لمزيد من المعلومات! + + + +## الكلام والصوت (Speech and audio) + +يُعدّ [Wav2Vec2](model_doc/wav2vec2) نموذجًا مُدرَّبًا ذاتيًا (Self-Supervised) على بيانات الكلام غير المُصنّفة، ويُمكن ضبطه بدقة (Fine-tuning) على بيانات موسومة لأداء مهام تصنيف الصوت والتعرف التلقائي على الكلام. + +
+ +
+ +يتكون هذا النموذج على أربعة مكونات رئيسية: + +1. *مشفّر الميزات (Feature Encoder)* يأخذ الموجة الصوتية الخام، ويقوم بتطبيعها (Normalization) إلى متوسط صفري وانحراف معياري وحدوي، وتحويلها إلى تسلسل من متجهات الميزات التي يبلغ طول كل منها 20 مللي ثانية. + +2. *وحدة التكميم (Quantization Module):** تتميز أشكال الموجات الصوتية بطبيعتها المُستمرة،، لذلك لا يمكن تقسيمها إلى وحدات منفصلة كما يمكن تقسيم التسلسل النصّي إلى كلمات ولهذا السبب يتم تمرير متجهات الميزات إلى *وحدة التكميم*، والتي تهدف إلى تعلم وحدات الكلام المنفصلة. يتم اختيار وحدة الكلام من مجموعة من الرموز، والمعروفة باسم *كتاب الرموز* (يمكنك اعتبار هذا بمثابة المفردات). ومن كتاب الرموز،يتم اختيار المتجه أو وحدة الكلام التي تُمثّل مدخل الصوت المُستمر على أفضل وجه، ويتم تمريرها عبر النموذج. +3. **شبكة السياق (Context Network):** يتم إخفاء حوالي نصف متجهات الميزات بشكل عشوائي، ويتم تغذية متجه الميزة المُقنّع إلى *شبكة السياق*، والتي تعد مُشفّر محوّلات (Transformer Encoder) الذي يضيف أيضًا تضمينات موضعية نسبية (Relative Positional Embeddings).. + +4. **مهمة التناقضية:** يتمثل الهدف من التدريب المسبق لشبكة السياق هو *مهمة تناقضية*. يجب على النموذج التنبؤ بالتمثيل الصحيح للكلام المُكمّم للتنبؤ المقنع من مجموعة من التمثيلات الخاطئة، مما يشجع النموذج على ا إيجاد متجه السياق ووحدة الكلام المُكمّمة الأكثر تشابهًا (التصنيف المستهدف). + +بمجرد تدريب Wav2Vec2 مسبقًا، يمكنك ضبط دقته على بياناتك لتصنيف الصوت أو التعرف التلقائي على الكلام! + +### تصنيف الصوت (Audio classification) + +لاستخدام النموذج الذي تم تدريبه مسبقًا لتصنيف الصوت، أضف رأس تصنيف تسلسلي أعلى نموذج Wav2Vec2 الأساسي. رأس التصنيف هو طبقة خطية تستقبل الحالات المخفية للمشفر. تمثل الحالات المخفية الميزات التي تم تعلمها من كل إطار صوتي والذي يمكن أن يكون له أطوال مختلفة. لتحويلها إلى متجه واحد ثابت الطول، يتم تجميع الحالات المخفية أولاً ثم تحويلها إلى احتمالات عبر تصنيفات الفئات. يتم حساب التكلفة (الخسارة المتقاطعة) بين الاحتمالات والتصنيف المستهدف للعثور على الفئة الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الصوت؟ تحقق من دليلنا الشامل [تصنيف الصوت](tasks/audio_classification) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! + +### التعرف التلقائي على الكلام (Automatic speech recognition - ASR) + +لاستخدام النموذج الذي تم تدريبه مسبقًا للتعرف التلقائي على الكلام، أضف رأس نمذجة لغوية أعلى نموذج Wav2Vec2 الأساسي لـ [[التصنيف الزمني الترابطي (CTC)](glossary#connectionist-temporal-classification-ctc). رأس النمذجة اللغوية عبارة عن طبقة خطية تقبل الحالات المخفية للمُشفّر وتحويلها إلى احتمالات. يمثل كل احتمال فئة رمزية (يأتي عدد الرموز من مفردات المهمة). يتم حساب تكلفة CTC بين الاحتمالات والأهداف للعثور على تسلسل الرموز الأكثر احتمالًا، والتي يتم فك تشفيرها بعد ذلك إلى نص مكتوب. + +هل أنت مستعد لتجربة التعرف التلقائي على الكلام؟ تحقق من دليلنا الشامل [التعرف التلقائي على الكلام](tasks/asr) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! + +## رؤية الحاسب (Computer vision) + +هناك طريقتان لتناول مهام رؤية الحاسب: + +1. قم بتقسيم الصورة إلى تسلسل من الرقع ومعالجتها بالتوازي باستخدام مُحوّل Transformer. +2. استخدم شبكة عصبية تلافيفية CNN) حديثة، مثل [ConvNeXT](model_doc/convnext)، والتي تعتمد على الطبقات التلافيفية ولكنها تعتمد تصميمات حديثة للشبكات. + + + +يقوم النهج الثالث بمزج المحولات مع التلافيف (على سبيل المثال، [Convolutional Vision Transformer](model_doc/cvt) أو [LeViT](model_doc/levit)). لن نناقشها لأنها تجمع ببساطة بين النهجين اللذين نستعرضهما هنا. + + + +يتم استخدام ViT و ConvNeXT بشكل شائع لتصنيف الصور، ولكن بالنسبة لمهام الرؤية الأخرى مثل اكتشاف الكائنات والتجزئة وتقدير العمق، سنلقي نظرة على DETR و Mask2Former و GLPN، على التوالي؛ فهذه النماذج هي الأنسب لتلك المهام. + +### تصنيف الصور (Image classification) + +يمكن استخدام كل من ViT و ConvNeXT لتصنيف الصور؛ الاختلاف الرئيسي هو أن ViT يستخدم آلية انتباه بينما يستخدم ConvNeXT الالتفافات. + +#### المحول Transformer + +[ViT](model_doc/vit) يستبدل التلافيف تمامًا بهندسة Transformer نقية. إذا كنت على دراية بـ Transformer الأصلي، فأنت بالفعل في طريقك إلى فهم ViT. + +
+ +
+ +كان التغيير الرئيسي الذي قدمه ViT هو كيفية تغذية الصور إلى Transformer: + +1. يتم تقسيم الصورة إلى رقع مربعة غير متداخلة، يتم تحويل كل منها إلى متجه أو يُسمى *تمثيل الرقعة*. يتم إنشاء تضمينات الرقع من طبقة تلافيفية ثنائية الأبعاد 2D والتي تقوم بإنشاء أبعاد الإدخال الصحيحة (والتي بالنسبة إلى Transformer الأساسي هي 768 قيمة لكل تضمين رقعة). إذا كان لديك صورة 224x224 بكسل، فيمكنك تقسيمها إلى 196 رقعة صورة 16x16. تمامًا مثل كيفية تجزئة النص إلى كلمات، يتم "تجزئة" الصورة إلى سلسلة من الرقع. + +2. يتم إضافة *رمز قابل للتعلم* - تتم إضافة رمز خاص `[CLS]` - إلى بداية تمثيلات الرقع تمامًا مثل BERT. يتم استخدام الحالة المخفية النهائية للرمز `[CLS]` كمدخل لرأس التصنيف المُرفق؛ يتم تجاهل المخرجات الأخرى. تساعد هذه الرموز النموذج على تعلم كيفية ترميز تمثيل الصورة. + +3. الشيء الأخير تتم إضافة "تمثيلات تموضع" إلى تمثيلات الرقع والرمز القابل للتعلم لأن النموذج لا يعرف كيفية ترتيب رقع الصورة. تكون تمثيلات التموضع قابلة للتعلم أيضًا ولها نفس حجم تمثيلات الرقع. وأخيرًا، يتم تمرير جميع التمثيلات إلى مُشفّر Transformer. + +4. يتم تمرير الإخراج، وتحديدًا مخرج الرمز `[CLS]`، إلى رأس الإدراك المتعدد الطبقات (MLP). الهدف من التدريب المسبق لـ ViT هو التصنيف فقط. يقوم رأس MLP، مثل رؤوس التصنيف الأخرى، يحول رأس MLP المخرجات إلى احتمالات عبر تصنيفات الفئات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على الفئة الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الصور؟ تحقق من دليلنا الشامل [تصنيف الصور](tasks/image_classification) لمعرفة كيفية ضبط دقة نموذج ViT واستخدامه للاستدلال! + +#### الشبكات العصبية التلافيفية (CNN) + + + +يشرح هذا القسم بإيجاز الالتفافات، ولكن سيكون من المفيد أن يكون لديك فهم مسبق لكيفية تغيير شكل الصورة وحجمها. إذا كنت غير معتاد على الالتفافات، تحقق من [فصل الشبكات العصبية التلافيفية](https://github.com/fastai/fastbook/blob/master/13_convolutions.ipynb) من كتاب fastai! + + + +[ConvNeXT](model_doc/convnext) هو بنية CNN تعتمد تصاميم الشبكات الجديدة والحديثة لتحسين الأداء. ومع ذلك، لا تزال الالتفافات هي جوهر النموذج. من منظور عام، [الالتفاف](glossary#convolution) هو عملية حيث يتم ضرب مصفوفة أصغر (*نواة*) بمقطع صغير من وحدات بكسل الصورة. يحسب بعض الميزات منه، مثل نسيج معين أو انحناء خط. ثم ينزلق إلى النافذة التالية من البكسلات؛ المسافة التي تقطعها الالتفاف تسمى *الخطوة*. + +
+ +
+ +عملية التفاف أساسية بدون حشو أو خطو خطوة واسعة، مأخوذة من دليل لحساب الالتفاف للتعلم العميق. + +يمكنك تغذية هذا الناتج إلى طبقة التفاف أخرى، ومع كل طبقة متتالية، تتعلم الشبكة أشياء أكثر تعقيدًا وتجريدية مثل النقانق أو الصواريخ. بين طبقات الالتفاف، من الشائع إضافة طبقة تجميع لتقليل الأبعاد وجعل النموذج أكثر قوة للتغيرات في موضع الميزة. + +
+ +
+ +يقوم ConvNeXT بتحديث شبكة CNN بطرق خمس: + +1. تغيير عدد الكتل في كل مرحلة و"ترقيع" الصورة باستخدام خطوة أكبر وحجم نواة المقابل. تجعل استراتيجية التجزئة غير المتداخلة استراتيجية الترقيع مشابهة للطريقة التي يقسم بها ViT للصورة إلى رقع. + +2. تقلص طبقة *العنق الزجاجي* عدد القنوات ثم تعيدها لأنها أسرع في إجراء التفاف 1x1، ويمكنك زيادة العمق. يقوم عنق الزجاجة المقلوب بالعكس عن طريق توسيع عدد القنوات وتقلصها، وهو أكثر كفاءة من حيث الذاكرة. + +3. استبدل طبقة الالتفاف النموذجية 3x3 في طبقة عنق الزجاجة بـ *الالتفاف بالعمق*، والذي يطبق الالتفاف على كل قناة إدخال بشكل منفصل ثم يقوم بتكديسها معًا مرة أخرى في النهاية. هذا يوسع عرض الشبكة لتحسين الأداء. + +4. لدى ViT مجال استقبال عالمي مما يعني أنه يمكنه رؤية المزيد من الصورة في وقت واحد بفضل آلية الانتباه الخاصة به. تحاول ConvNeXT محاكاة هذا التأثير عن طريق زيادة حجم النواة إلى 7x7. + +5. يقوم ConvNeXT أيضًا بإجراء العديد من تغييرات تصميم الطبقة التي تُحاكي نماذج المحولات. هناك عدد أقل من طبقات التنشيط والطبقات التطبيع، يتم تبديل دالة التنشيط إلى GELU بدلاً من ReLU، ويستخدم LayerNorm بدلاً من BatchNorm. + +يتم تمرير الإخراج من كتل الالتفاف إلى رأس تصنيف يحول المخرجات إلى احتمالات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على التصنيف الأكثر احتمالاً. + +### اكتشاف الكائنات (Object detection) + +[DETR](model_doc/detr)، *DEtection TRansformer*، هو نموذج اكتشاف كائنات من البداية إلى النهاية يجمع بين CNN مع محول المشفر-فك التشفير. + +
+ +
+ +1. يأخذ العمود الفقري CNN *المدرب مسبقًا* صورة، ممثلة بقيم بكسلاتها، وينشئ خريطة ميزات منخفضة الدقة لها. يتم تطبيق التفاف 1x1 على خريطة الميزات لتقليل الأبعاد، و إنشاء خريطة ميزات جديدة بتمثيل صورة عالي المستوى. نظرًا لأن المحول (Transformer) هو نموذج تسلسلي، يتم تسوية خريطة الميزات إلى تسلسل من متجهات الميزات التي يتم دمجها مع تمثيلات التموضع. + +2. يتم تمرير متجهات الميزات إلى المشفر، والذي يتعلم تمثيلات الصورة باستخدام طبقات الانتباه الخاصة به. بعد ذلك، يتم دمج الحالات المخفية للمُشفّر مع *استعلامات الكائنات* في فك التشفير. استعلامات الكائنات هي تمثيلات مكتسبة تركز على مناطق مختلفة من الصورة، ويتم تحديثها أثناء مرورها عبر كل طبقة انتباه. يتم تمرير الحالات المخفية لفك التشفير إلى شبكة تغذية أمامية التي تتنبأ بإحداثيات مربعات الإحاطة وتصنيف العلامة لكل استعلام كائن، أو `بدون كائن` إذا لم يكن هناك أي كائن. + + يقوم DETR بفك تشفير كل استعلام كائن بالتوازي لإخراج *N* من التنبؤات النهائية، حيث *N* هو عدد الاستعلامات. على عكس النموذج التلقائي الذي يتنبأ بعنصر واحد في كل مرة، فإن "اكتشاف الكائنات" هو مهمة تنبؤ بمجموعة من التنبؤات (مثل `مربع إحاطة`، `تصنيف`) تقوم بإجراء *N* من التنبؤات في مرور واحدة. + +3. يستخدم DETR دالة *خسارة المطابقة ثنائية الفئات* أثناء التدريب لمقارنة عدد ثابت من التنبؤات بمجموعة ثابتة من تصنيفات البيانات الحقيقية. إذا كان هناك عدد أقل من تصنيفات البيانات الحقيقية في مجموعة *N* من التصنيفات، فيتم حشوها بفئة "بدون كائن". تشجع دالة الخسارة هذه DETR على العثور على تعيين واحد لواحد بين التنبؤات وتصنيفات البيانات الحقيقية. إذا لم تكن مربعات الإحاطة أو تصنيفات الفئات صحيحة، يتم تكبد خسارة. وبالمثل، إذا تنبأ DETR بكائن غير موجود، فإنه يتم معاقبته. وهذا يشجع DETR على العثور على كائنات أخرى في الصورة بدلاً من التركيز على كائن بارز حقًا. + +يتم إضافة رأس اكتشاف كائن أعلى DETR للعثور على تصنيف الكائن وإحداثيات مربع الإحاطة. هناك مكونان لرأس اكتشاف الكائنات: طبقة خطية لتحويل حالات فك التشفير المخفية إلى احتمالات عبر تصنيفات الفئات، وشبكةMLP للتنبؤ بمربع الإحاطة. + +هل أنت مستعد لتجربة اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل اكتشاف الكائنات](tasks/object_detection) لمعرفة كيفية ضبط نموذج DETR واستخدامه للاستدلال! + +### تجزئة الصورة (Image segmentation) + +يُعد [Mask2Former](model_doc/mask2former) بنيةً شاملةً لحل جميع أنواع مهام تجزئة الصور. عادةً ما تُصمم نماذج التجزئة التقليدية لمهمة فرعية محددة من مهام تجزئة الصور، مثل تجزئة المثيل أو التجزئة الدلالية أو التجزئة الشاملة. يصوغ Mask2Former كل مهمة من تلك المهام على أنها مشكلة *تصنيف الأقنعة*. يقوم تصنيف القناع بتجميع وحدات البكسل في *N* قطعة، ويتنبأ بـ *N* أقنعة وتصنيف الفئة المقابل لها لصورة معينة. سنشرح في هذا القسم كيفية عمل Mask2Former، ويمكنك بعد ذلك تجربة ضبط SegFormer في النهاية. + +
+ +
+ +هناك ثلاثة مكونات رئيسية لـ Mask2Former: + +1. العمود الفقري [Swin](model_doc/swin) يقبل صورة وينشئ خريطة ميزات منخفضة الدقة من 3 عمليات التفافات متتالية 3x3. + +2. يتم تمرير خريطة الميزات إلى *فك تشفير البكسل* الذي يقوم تدريجياً بزيادة الميزات منخفضة الدقة إلى تمثيلات عالية الدقة لكل بكسل. في الواقع، يقوم فك تشفير البكسل بإنشاء ميزات متعددة المقاييس (تحتوي على كل من الميزات منخفضة وعالية الدقة) بدقة 1/32 و1/16 و1/8 من الصورة الأصلية. + +3. يتم تغذية كل من خرائط الميزات ذات المقاييس المختلفة على التوالي إلى طبقة واحدة من طبقات فك التشفير في كل مرة لالتقاط الأجسام الصغيرة من ميزات الدقة العالية. يتمثل مفتاح Mask2Former آلية *الاهتمام المقنع* في فك التشفير. على عكس الانتباه المتقاطع الذي يمكن أن يركز على الصورة بأكملها، يركز الانتباه المقنع فقط على منطقة معينة من الصورة. هذا أسرع ويؤدي إلى أداء أفضل لأن الميزات المحلية لصورة كافية للنموذج للتعلم منها. + +4. مثل [DETR](tasks_explained#object-detection)، يستخدم Mask2Former أيضًا استعلامات كائن مكتسبة ويجمعها مع ميزات الصورة من فك تشفير البكسل لإجراء تنبؤ مجموعة (`تصنيف الفئة`، `التنبؤ بالقناع`). يتم تمرير حالات فك التشفير المخفية إلى طبقة خطية وتحويلها إلى احتمالات عبر علامات التصنيف. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات وتصنيف الفئة لتحديد الأكثر احتمالاً. + + يتم إنشاء تنبؤات الأقنعة عن طريق الجمع بين تمثيلات البكسل وحالات فك التشفير المخفية النهائية. يتم حساب دالة الخسارة المتقاطعة سيجمويد وخسارة النرد بين الاحتمالات والقناع البيانات الحقيقية للعثور على القناع الأكثر احتمالاً. + +هل أنت مستعد لتجربة يدك في اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل تجزئة الصورة](tasks/semantic_segmentation) لمعرفة كيفية ضبط SegFormer واستخدامه للاستدلال! + +### تقدير العمق (Depth estimation) + +[GLPN](model_doc/glpn)، شبكة المسار العالمية المحلية، هي محول ل تقدير العمق الذي يجمع بين مشفر [SegFormer](model_doc/segformer) مع فك تشفير خفيف الوزن. + +
+ +
+ +1. مثل ViT، يتم تقسيم الصورة إلى تسلسل من الرقع، باستثناء أن هذه رقع الصورة أصغر. هذا أفضل لمهام التنبؤ الكثيفة مثل التجزئة أو تقدير العمق. يتم تحويل رقع الصورة إلى تمثيلات للرقع (راجع قسم [تصنيف الصور](#image-classification) لمزيد من التفاصيل حول كيفية إنشاء تمثيلات الرقع)، والتي يتم تغذيتها إلى المشفر. + +2. يقبل المشفر تمثيلات الرقع، ويمررها عبر عدة كتل مشفرة. يتكون كل كتلة من طبقات انتباه وMix-FFN. الغرض من هذا الأخير هو توفير معلومات موضعية. في نهاية كل كتلة مشفرة توجد طبقة *دمج الرقع* لإنشاء تمثيلات هرمية. يتم دمج ميزات كل مجموعة من الرقع المجاورة، ويتم تطبيق طبقة خطية على الميزات المدمجة لتقليل عدد الرقع إلى دقة 1/4. يصبح هذا المُدخل للكتلة المشفرة التالية، حيث تتكرر هذه العملية بأكملها حتى تحصل على ميزات الصورة بدقة 1/8 و1/16 و1/32. + +3. يقوم فك تشفير خفيف الوزن بأخذ خريطة الميزات الأخيرة (مقياس 1/32) من المشفر وزيادة حجمها إلى مقياس 1/16. من هنا، يتم تمرير الميزة إلى وحدة *دمج الميزات الانتقائية (SFF)*، والتي تقوم باختيار ودمج الميزات المحلية والعالمية من خريطة انتباه لكل ميزة ثم زيادة حجمها إلى 1/8. تتم إعادة هذه العملية حتى تصبح الميزات فك التشفير بنفس حجم الصورة الأصلية. يتم تمرير الإخراج عبر طبقتين تلافيفتين ثم يتم تطبيق تنشيط سيجمويد للتنبؤ بعمق كل بكسل. + +## معالجة اللغات الطبيعية (Natural language processing -NLP) + +تم تصميم نموذج المحول Transformer في الأصل للترجمة الآلية، ومنذ ذلك الحين أصبح في الواقع البنية الافتراضية لحل جميع مهام NLP. تناسب بعض المهام بنية المشفر في نموذج المحول، في حين أن البعض الآخر أكثر ملاءمة لفك التشفير. لا تزال مهام أخرى تستخدم بنية المشفر-فك التشفير في نموذج المحول. + +### تصنيف النصوص (Text classification) + +يعد [BERT](model_doc/bert) نموذج يعتمد على المُشفّر فقط، وهو أول نموذج يُطبق بشكل فعال ثنائية الاتجاه العميقة لتعلم تمثيلات أكثر ثراءً للنص من خلال الانتباه إلى الكلمات على كلا الجانبين. + +1. يستخدم BERT تجزئة [WordPiece](tokenizer_summary#wordpiece) لإنشاء تمثيل رمزي للنص. للتمييز بين جملة واحدة وزوج من الجمل، تتم إضافة رمز خاص `[SEP]` للتفريق بينهما. تتم إضافة رمز خاص `[CLS]` إلى بداية كل تسلسل نصي. ويتم استخدام الإخراج النهائي مع الرمز `[CLS]` كمدخل لرأس التصنيف لمهام التصنيف. كما يضيف BERT تضمينًا للمقطع للإشارة إلى ما إذا كان الرمز ينتمي إلى الجملة الأولى أو الثانية في زوج من الجمل. + +2. يتم تدريب BERT المسبق باستخدام هدفين: نمذجة اللغة المقنعة وتنبؤ الجملة التالية. في نمذجة اللغة المقنعة، يتم إخفاء نسبة مئوية مُعيّنة من رموز الإدخال بشكل عشوائي، ويجب على النموذج التنبؤ بها. يحل هذا مشكلة ثنائية الاتجاه، حيث يمكن للنموذج أن يغش ويرى جميع الكلمات و"يتنبأ" بالكلمة التالية. تتم تمرير الحالات المخفية النهائية للرموز المقنعة المتوقعة إلى شبكة تغذية أمامية مع دالة Softmax عبر مفردات اللغة للتنبؤ بالكلمة المقنعة. + + الهدف الثاني من التدريب المسبق هو توقع الجملة التالية. يجب على النموذج التنبؤ بما إذا كانت الجملة "ب" تتبع الجملة"أ". نصف الوقت تكون الجملة "ب" هي الجملة التالية، والنصف الآخر من الوقت، تكون الجملة "ب" عبارة عشوائية. يتم تمرير التنبؤ، سواء كانت الجملة التالية أم لا، إلى شبكة تغذية أمامية مع دالة Softmax عبر الفئتين (`IsNext` و`NotNext`). + +3. يتم تمرير تمثيلات الإدخال عبر عدة طبقات مشفرة لإخراج بعض الحالات المخفية النهائية. + +لاستخدام النموذج المسبق التدريب لتصنيف النصوص، أضف رأس تصنيف تسلسلي أعلى نموذج BERT الأساسي. رأس تصنيف التسلسلي هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى احتمالات logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits والهدف للعثور على التصنيف الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف النصوص؟ تحقق من [دليل تصنيف النصوص](tasks/sequence_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! + +### تصنيف الرموز (Token classification) + +لاستخدام BERT لمهام تصنيف الرموز مثل التعرف على الكيانات المسماة (NER)، أضف رأس تصنيف الرموز أعلى نموذج BERT الأساسي. رأس تصنيف الرموز هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits وكل رمز للعثور على التصنيف الأكثر احتمالًا. + +هل أنت مستعد لتجربة تصنيف الرموز؟ تحقق من [دليل تصنيف الرموز](tasks/token_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! + +### الإجابة على الأسئلة (Question answering) + +لاستخدام BERT للإجابة على الأسئلة، أضف رأس تصنيف المدى أعلى نموذج BERT الأساسي. تقبل هذه الطبقة الخطية الحالات المخفية النهائية وتُجري تحويلًا خطيًا لحساب داية ونهاية `الامتداد` logits `span` البداية والنهاية المقابلة للإجابة. يتم حسابدالة التكلفة (الخسارة المتقاطعة) بين logits وموقع التصنيف للعثور على الامتداد الأكثر احتمالًا من النص المقابل للإجابة. + +هل أنت مستعد لتجربة الإجابة على الأسئلة؟ راجع [دليل الإجابة على الأسئلة](tasks/question_answering) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه في الاستدلال! + + + + +💡 لاحظ مدى سهولة استخدام BERT لمهام مختلفة بمجرد تدريبه مسبقًا. كل ما تحتاج إليه هو إضافة رأس محدد إلى النموذج المسبق التدريب للتلاعب بالحالات المخفية إلى الإخراج المطلوب! + + + +### توليد النصوص (Text generation) + +يُعد [GPT-2](model_doc/gpt2) نموذجًا قائم على فك التشفير فقط تم تدريبه المسبق على كمية كبيرة من النصوص. يمكنه توليد نص مقنع (على الرغم من أنه ليس دائمًا صحيحًا!) بناءً على مُحفّز معين واستكمال مهام NLP الأخرى مثل الإجابة على الأسئلة على الرغم من أنه لم يتم تدريبه بشكل صريح على ذلك. + +
+ +
+ +1. يستخدم GPT-2 [ترميز الأزواج البايتية (BPE)](tokenizer_summary#byte-pair-encoding-bpe) لتجزئة الكلمات وإنشاء تمثيل رمزى. يتم إضافة تمثيلات موضعية إلى تمثيلات الرموز للإشارة إلى موضع كل رمز في التسلسل. يتم تمرير تمثيلات الإدخال عبر عدة كتل فك تشفير لإخراج بعض الحالات المخفية النهائية. داخل كل كتلة فك تشفير، يستخدم GPT-2 طبقة *انتباه ذاتي مقنع* مما يعني أن GPT-2 لا يمكنه الانتباه بالرموز المستقبلية. يُسمح له فقط بالاهتمام بالرموز الموجودة على اليسار. يختلف هذا عن رمز [`mask`] الخاص بـ BERT لأنه، في الانتباه الذاتي المقنع، يتم استخدام قناع انتباه لتعيين النتيجة إلى `0` للرموز المستقبلية. + +2. يتم تمرير الإخراج من فك التشفير إلى رأس نمذجة اللغة، والتي تُجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات logits. التصنيف هو الرمز التالي في التسلسل، والذي يتم إنشاؤه عن طريق تغيير موضع logits إلى اليمين بمقدار واحد. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits التي تم تغيير موضعها والتصنيفات لإخراج الرمز التالي الأكثر احتمالًا. + +يستند هدف التدريب المسبق لـ GPT-2 بالكامل إلى [نمذجة اللغة السببية](glossary#causal-language-modeling)، والتنبؤ بالكلمة التالية في تسلسل. يجعل هذا GPT-2 جيدًا بشكل خاص في المهام التي تتضمن توليد النص. + +هل أنت مستعد لتجربة توليد النصوص؟ تحقق من دليل [دليل نمذجة اللغة السببية](tasks/language_modeling#causal- الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilGPT-2 واستخدامه للاستنتاج! + + + +للحصول على مزيد من المعلومات حول توليد النص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)! + + + +### التلخيص (Summarization) + +تم تصميم نماذج المشفر-فك التشفير مثل [BART](model_doc/bart) و [T5](model_doc/t5) لنمط تسلسل إلى تسلسل لمهمة التلخيص. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. + +
+ +
+ +1. تتشابه بنية المشفر BART كثيرًا مع BERT وتقبل رمزًا وتمثيلًا موضعيًا للنص. يتم تدريب BART مسبقًا عن طريق إتلاف المُدخلات ثم إعادة بنائه باستخدام فك التشفير. على عكس المشفرات الأخرى ذات استراتيجيات الإتلاف المحددة، يمكن لـ BART تطبيق أي نوع من الإتلاف. ومع ذلك، فإن استراتيجية إتلاف "ملء النص" تعمل بشكل أفضل. في ملء النص، يتم استبدال عدد من امتدادات النص برمز **واحد** [`mask`]. هذا أمر مهم لأن النموذج يجب أن يتنبأ بالرموز المقنعة، ويعلّم النموذج التنبؤ بعدد الرموز المفقودة. يتم تمرير تمثيلات الإدخال والامتدادات المقنعة عبر المشفر لإخراج بعض الحالات المخفية النهائية، ولكن على عكس BERT، لا يضيف BART شبكة تغذية أمامية نهائية في النهاية للتنبؤ بكلمة. + +2. يتم تمرير إخراج المشفر إلى فك التشفير، والذي يجب أن يتنبأ بالرموز المقنعة وأي رموز غير تالفة من ناتج المشفر. يمنح هذا فك التشفير سياقًا إضافيًا للمساعدة في استعادة النص الأصلي. يتم تمرير ناتج فك التشفير إلى رأس نمذجة اللغوية، والذي يجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات(logits). يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات logits والتصنيف، وهو مجرد الرمز الذي تم تغيير موضعه إلى اليمين. + +هل أنت مستعد لتجربة التلخيص؟ تحقق من دليل التلخيص الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! + + + +للحصول على مزيد من المعلومات حول توليد النص، راجع دليل استراتيجيات توليد النص! + + + +### الترجمة (Translation) + +تُعد الترجمة مثالًا آخر على مهام التسلسل إلى التسلسل، مما يعني أنه يمكنك استخدام نموذج المشفر-فك التشفير مثل [BART](model_doc/bart) أو [T5](model_doc/t5) للقيام بذلك. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. + +يتكيف BART مع الترجمة عن طريق إضافة مشفر منفصل يتم تهيئته بشكل عشوائي لتعيين لغة المصدر بمدخلات يمكن فك تشفيرها إلى لغة الهدف. يتم تمرير تمثيلات هذا المشفر الجديد إلى المشفر المسبق التدريب بدلاً من تمثيلات الكلمات الأصلية. يتم تدريب مشفر المصدر عن طريق تحديث مشفر المصدر وتمثيلات التموضع وتمثيلات الإدخال باستخدام دالة التكلفة (الخسارة المتقاطعة) من ناتج النموذج. يتم تجميد معلمات النموذج في هذه الخطوة الأولى، ويتم تدريب جميع معلمات النموذج معًا في الخطوة الثانية. + +تم إصدار نسخة متعددة اللغات من BART، تسمى mBART، مُخصصة للترجمة ومُدرّبة مسبقًا على العديد من اللغات المختلفة. + +هل أنت مستعد لتجربة الترجمة؟ تحقق من دليل الترجمة الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! + + + + **للحصول على مزيد من المعلومات حول توليد النصوص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)!** + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tflite.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tflite.md new file mode 100644 index 0000000000000000000000000000000000000000..5e75c7a10a3c66d0eec7b87246269f632b057d2e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tflite.md @@ -0,0 +1,40 @@ +# التصدير إلى TFLite + +[TensorFlow Lite](https://www.tensorflow.org/lite/guide) هو إطار عمل خفيف الوزن لنشر نماذج التعلم الآلي على الأجهزة المحدودة الموارد، مثل الهواتف المحمولة، والأنظمة المدمجة، وأجهزة إنترنت الأشياء (IoT). تم تصميم TFLite لتشغيل النماذج وتحسينها بكفاءة على هذه الأجهزة ذات الطاقة الحاسوبية والذاكرة واستهلاك الطاقة المحدودة. + +يُمثَّل نموذج TensorFlow Lite بتنسيق محمول فعال خاص يُعرَّف بامتداد الملف `.tflite`. + +🤗 Optimum يقدم وظيفة لتصدير نماذج 🤗 Transformers إلى TFLite من خلال الوحدة النمطية `exporters.tflite`. بالنسبة لقائمة هندسات النماذج المدعومة، يرجى الرجوع إلى [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/exporters/tflite/overview). + +لتصدير نموذج إلى TFLite، قم بتثبيت متطلبات البرنامج المطلوبة: + +```bash +pip install optimum[exporters-tf] +``` + +للاطلاع على جميع المغامﻻت المتاحة، راجع [وثائق 🤗 Optimum](https://huggingface.co/docs/optimum/main/en/exporters/tflite/usage_guides/export_a_model)، أو عرض المساعدة في سطر الأوامر: + +```bash +optimum-cli export tflite --help +``` + +لتصدير نسخة النموذج ل 🤗 Hub، على سبيل المثال، `google-bert/bert-base-uncased`، قم بتشغيل الأمر التالي: + +```bash +optimum-cli export tflite --model google-bert/bert-base-uncased --sequence_length 128 bert_tflite/ +``` + +ستظهر لك السجلات التي تُبيّن التقدم وموقع حفظ ملف `model.tflite` الناتج، كما في المثال التالي: + +```bash +Validating TFLite model... + -[✓] TFLite model output names match reference model (logits) + - Validating TFLite Model output "logits": + -[✓] (1, 128, 30522) matches (1, 128, 30522) + -[x] values not close enough, max diff: 5.817413330078125e-05 (atol: 1e-05) +The TensorFlow Lite export succeeded with the warning: The maximum absolute difference between the output of the reference model and the TFLite exported model is not within the set tolerance 1e-05: +- logits: max diff = 5.817413330078125e-05. + The exported model was saved at: bert_tflite +``` + +يُبيّن المثال أعلاه كيفية تصدير نسخة من النموذج ل 🤗 Hub. عند تصدير نموذج محلي، تأكد أولاً من حفظ ملفات أوزان النموذج المجزء اللغوى في نفس المسار (`local_path`). عند استخدام CLI، قم بتمرير `local_path` إلى معامل `model` بدلاً من اسم النسخة على 🤗 Hub. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tiktoken.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tiktoken.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3755d8670cdc75885662477f018ab8bfd4b0a4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tiktoken.md @@ -0,0 +1,41 @@ +# Tiktoken والتفاعل مع Transformers + +يتم دمج دعم ملفات نموذج tiktoken بسلاسة في 🤗 transformers عند تحميل النماذج +`from_pretrained` مع ملف `tokenizer.model` tiktoken على Hub، والذي يتم تحويله تلقائيًا إلى [المحلل اللغوي السريع](https://huggingface.co/docs/transformers/main/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast). + +### النماذج المعروفة التي تم إصدارها مع `tiktoken.model`: + - gpt2 + - llama3 + +## مثال على الاستخدام + +من أجل تحميل ملفات `tiktoken` في `transformers`، تأكد من أن ملف `tokenizer.model` هو ملف tiktoken وسيتم تحميله تلقائيًا عند التحميل `from_pretrained`. إليك كيفية تحميل مجزىء لغوي ونموذج، والذي +يمكن تحميله من نفس الملف بالضبط: + +```py +from transformers import AutoTokenizer + +model_id = "meta-llama/Meta-Llama-3-8B-Instruct" +tokenizer = AutoTokenizer.from_pretrained(model_id, subfolder="original") +``` +## إنشاء مجزىء لغوي tiktoken + +لا يحتوي ملف `tokenizer.model` على أي معلومات حول الرموز أو الأنماط الإضافية. إذا كانت هذه الأمور مهمة، قم بتحويل المحلل اللغوي إلى `tokenizer.json`، وهو التنسيق المناسب لـ [`PreTrainedTokenizerFast`]. + +قم بتوليد ملف `tokenizer.model` باستخدام [tiktoken.get_encoding](https://github.com/openai/tiktoken/blob/63527649963def8c759b0f91f2eb69a40934e468/tiktoken/registry.py#L63) ثم قم بتحويله إلى `tokenizer.json` باستخدام [`convert_tiktoken_to_fast`]. + +```py + +from transformers.integrations.tiktoken import convert_tiktoken_to_fast +from tiktoken import get_encoding + +# يمكنك تحميل ترميزك المخصص أو الترميز الذي توفره OpenAI +encoding = get_encoding("gpt2") +convert_tiktoken_to_fast(encoding, "config/save/dir") +``` + +يتم حفظ ملف `tokenizer.json` الناتج في الدليل المحدد ويمكن تحميله باستخدام [`PreTrainedTokenizerFast`]. + +```py +tokenizer = PreTrainedTokenizerFast.from_pretrained("config/save/dir") +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tokenizer_summary.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tokenizer_summary.md new file mode 100644 index 0000000000000000000000000000000000000000..109521d24bbb76de408a6462a868731481c1d924 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/tokenizer_summary.md @@ -0,0 +1,198 @@ +# ملخص عن المجزئات اللغوية + +[[open-in-colab]] + +في هذه الصفحة، سنتناول بالتفصيل عملية التجزئة. + + + +كما رأينا في [برنامج تعليمي حول المعالجة المسبقة](preprocessing)، فإن تجزئة النص يقسمه إلى كلمات أو +الرموز الفرعية (كلمات جزئية)، والتي يتم بعد ذلك تحويلها إلى معرفات من خلال قائمة بحث. يعد تحويل الكلمات أو الرموز الفرعية إلى معرفات مباشرًا، لذا في هذا الملخص، سنركز على تقسيم النص إلى كلمات أو رموز فرعية (أي تجزئة النص). +وبشكل أكثر تحديدًا، سنلقي نظرة على الأنواع الثلاثة الرئيسية من المُجزئات اللغوية المستخدمة في 🤗 المحولات: [ترميز الأزواج البايتية (BPE)](#byte-pair-encoding)، [WordPiece](#wordpiece)، و [SentencePiece](#sentencepiece)، ونعرض أمثلة +على نوع المُجزئة الذي يستخدمه كل نموذج. + +لاحظ أنه في كل صفحة نموذج، يمكنك الاطلاع على وثائق المُجزئة المرتبط لمعرفة نوع المُجزئ +الذي استخدمه النموذج المُدرب مسبقًا. على سبيل المثال، إذا نظرنا إلى [`BertTokenizer`]، يمكننا أن نرى أن النموذج يستخدم [WordPiece](#wordpiece). + +## مقدمة + +إن تقسيم النص إلى أجزاء أصغر هو مهمة أصعب مما تبدو، وهناك طرق متعددة للقيام بذلك. +على سبيل المثال، دعنا نلقي نظرة على الجملة `"Don't you love 🤗 Transformers? We sure do."` + + + +يمكن تقسيم هذه الجملة ببساطة عن طريق المسافات، مما سينتج عنه ما يلي:``` + +``` +["Don't", "you", "love", "🤗", "Transformers?", "We", "sure", "do."] +``` + +هذه خطوة أولى منطقية، ولكن إذا نظرنا إلى الرموز `"Transformers?"` و `"do."`، فإننا نلاحظ أن علامات الترقيم مُرفقة بالكلمات `"Transformer"` و `"do"`، وهو أمر ليس مثالي. يجب أن نأخذ علامات الترقيم في الاعتبار حتى لا يضطر النموذج إلى تعلم تمثيل مختلف للكلمة وكل رمز ترقيم مُحتمل قد يليها، الأمر الذي من شأنه أن يزيد بشكل هائل عدد التمثيلات التي يجب على النموذج تعلمها. +مع مراعاة علامات الترقيم، سيُصبح تقسيم نصنا على النحو التالي: + +``` +["Don", "'", "t", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."] +``` + +أفضل. ومع ذلك، من غير الملائم كيفية تقسيم الكلمة `"Don't"`. `"Don't"` تعني `"do not"`، لذا سيكون من الأفضل تحليلها على أنها كلمتين مُدمجتين `["Do"، "n't"]`. هنا تبدأ الأمور في التعقيد، وهو جزء من سبب امتلاك كل نموذج لنوّعه الخاص من مُجزّئ النصوص (tokenizer). اعتمادًا على القواعد التي نطبقها لتقسيم النص، يسيتم إنشاء مخرجات مُجزّأة مُختلفة لنفس النص. ولن يؤدي النموذج المُدرب مسبقًا إلى الأداء بشكل صحيح إلا إذا قُدّم له مُدخل تم تقسيمه بنفس القواعد التي تم استخدامها لتقسيم بيانات التدريب الخاصة به. + +يُعد كل من [spaCy](https://spacy.io/) و [Moses](http://www.statmt.org/moses/?n=Development.GetStarted) هما مجزّئي النصوص التي تعتمد على القواعد +الشائعة. عند تطبيقها على مثالنا، فإن *spaCy* و *Moses* ستخرج نّصًا مثل: + +``` +["Do", "n't", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."] +``` + +كما يمكنك أن ترى، يتم هنا استخدام التقسيم المكاني والترقيم، وكذلك تقسيم الكلمات القائم على القواعد. يعد التقسيم المكاني والترقيم والتحليل القائم على القواعد كلاهما مثالين على تقسيم الكلمات، والذي يُعرّف بشكل غير مُحدد على أنه تقسيم الجُمل إلى كلمات. في حين أنها الطريقة الأكثر بديهية لتقسيم النصوص إلى أجزاء أصغر، +يمكن أنها تؤدى إلى مشكلات لمجموعات النصوص الضخمة. في هذه الحالة، عادةً ما يؤدي التقسيم المكاني والترقيم +إلى إنشاء مفردات كبيرة جدًا (مجموعة من جميع الكلمات والرموز الفريدة المستخدمة). على سبيل المثال، يستخدم [Transformer XL](model_doc/transfo-xl) التقسيم المكاني والترقيم، مما يؤدي إلى حجم مُفردات يبلغ 267735! + +يفرض حجم المُفردات الكبير هذا على النموذج أن يكون لديه مصفوفة تضمين (embedding matrix) ضخمة كطبقة إدخال وإخراج، مما يؤدي إلى زيادة كل من التعقيد الزمني والذاكرة. بشكل عام، نادرًا ما يكون لدى نماذج المحولات حجم مفردات +أكبر من 50000، خاصة إذا تم تدريبها مسبقًا على لغة واحدة فقط. + +لذا إذا كان التقسيم المكاني و الترقيم البسيط غير مرضٍ، فلماذا لا نقسّم الحروف ببساطة؟ + + + +في حين أن تقسيم الأحرف بسيط للغاية ومن شأنه أن يقلل بشكل كبير من التعقيد الزمني والذاكرة، إلا أنه يجعل من الصعب +على النموذج تعلم تمثيلات المدخلات ذات معنى. على سبيل المثال، يعد تعلم تمثيل مستقل عن السياق للحرف "t" أكثر صعوبة من تعلم تمثيل مستقل عن السياق لكلمة "اليوم". لذلك، غالبًا ما يكون تحليل الأحرف مصحوبًا بفقدان الأداء. لذا للحصول على أفضل ما في العالمين، تستخدم نماذج المحولات نظامًا هجينًا بين تقسيم على مستوى الكلمة وتقسيم علي مستوى الأحرف يسمى **تقسيم الوحدات الفرعية للّغة** (subword tokenization). + +## تقسيم الوحدات الفرعية للّغة (Subword Tokenization) + + + +تعتمد خوارزميات تقسيم الوحدات الفرعية subword على المبدأ القائل بأن الكلمات الشائعة الاستخدام لا ينبغي تقسيمها إلى وحدات فرعية أصغر، ولكن يجب تفكيك الكلمات النادرة إلى رموز فرعية ذات معنى. على سبيل المثال، قد يتم اعتبار "annoyingly" +كلمة نادرة ويمكن تحليلها إلى "annoying" و "ly". كل من "annoying" و "ly" كـ subwords مستقلة ستظهر بشكل متكرر أكثر في حين أن معنى "annoyingly" يتم الاحتفاظ به من خلال المعنى المركب لـ "annoying" و "ly". هذا مفيد بشكل خاص في اللغات التلصيقية مثل التركية، حيث يمكنك تشكيل كلمات مُركبة طويلة (تقريبًا) بشكل تعسفي عن طريق ضم الرموز الفرعية معًا. + +يسمح تقسيم subword للنموذج بأن يكون له حجم مفردات معقول مع القدرة على تعلم تمثيلات مستقلة عن السياق ذات معنى. بالإضافة إلى ذلك، يمكّن تقسيم subword النموذج من معالجة الكلمات التي لم يسبق له رؤيتها من قبل، عن طريق تحليلها إلى رموز فرعية معروفة. على سبيل المثال، يقوم المحلل [`~transformers.BertTokenizer`] بتحليل"I have a new GPU!" كما يلي: + +```py +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> tokenizer.tokenize("I have a new GPU!") +["i", "have", "a", "new", "gp", "##u", "!"] +``` + +نظرًا لأننا نستخدم نموذجًا غير حساس لحالة الأحرف (uncased model)، فقد تم تحويل الجملة إلى أحرف صغيرة أولاً. يمكننا أن نرى أن الكلمات `["i"، "have"، "a"، "new"]` موجودة في مفردات مُجزّئ النصوص، ولكن الكلمة "gpu" غير موجودة. وبالتالي، يقوم مُجزّئ النصوص بتقسيم "gpu" إلى رموز فرعية معروفة: `["gp" و "##u"]`. يعني "##" أنه يجب ربط بقية الرمز بالرمز السابق، دون مسافة (للترميز أو عكس عملية تقسيم الرموز). + +كمثال آخر، يقوم المحلل [`~transformers.XLNetTokenizer`] بتقسيم نّص مثالنا السابق كما يلي: + +```py +>>> from transformers import XLNetTokenizer + +>>> tokenizer = XLNetTokenizer.from_pretrained("xlnet/xlnet-base-cased") +>>> tokenizer.tokenize("Don't you love 🤗 Transformers? We sure do.") +["▁Don", "'", "t", "▁you", "▁love", "▁"، "🤗"، "▁"، "Transform"، "ers"، "؟"، "▁We"، "▁sure"، "▁do"، "."] +``` +سنعود إلى معنى تلك `"▁"` عندما نلقي نظرة على [SentencePiece](#sentencepiece). كما يمكنك أن ترى، +تم تقسيم الكلمة النادرة "Transformers" إلى الرموز الفرعية الأكثر تكرارًا `"Transform"` و `"ers"`. + +دعنا الآن نلقي نظرة على كيفية عمل خوارزميات تقسيم subword المختلفة. لاحظ أن جميع خوارزميات التقسيم هذه تعتمد على بعض أشكال التدريب الذي يتم عادةً على مجموعة البيانات التي سيتم تدريبها النموذج عليها. + + + +### ترميز الأزواج البايتية (BPE) + +تم تقديم رميز أزواج البايت (BPE) في ورقة بحثية بعنوان [الترجمة الآلية العصبية للكلمات النادرة باستخدام وحدات subword (Sennrich et al.، 2015)](https://arxiv.org/abs/1508.07909). يعتمد BPE على مُجزّئ أولي يقسم بيانات التدريب إلى +كلمات. يمكن أن يكون التحليل المسبق بسيطًا مثل التقسيم المكاني، على سبيل المثال [GPT-2](model_doc/gpt2)، [RoBERTa](model_doc/roberta). تشمل التقسيم الأكثر تقدمًا معتمد على التحليل القائم على القواعد، على سبيل المثال [XLM](model_doc/xlm)، [FlauBERT](model_doc/flaubert) الذي يستخدم Moses لمعظم اللغات، أو [GPT](model_doc/openai-gpt) الذي يستخدم spaCy و ftfy، لحساب تكرار كل كلمة في مجموعة بيانات التدريب. + +بعد التحليل المسبق، يتم إنشاء مجموعة من الكلمات الفريدة وقد تم تحديد تكرار كل كلمة في تم تحديد بيانات التدريب. بعد ذلك، يقوم BPE بإنشاء مفردات أساسية تتكون من جميع الرموز التي تحدث في مجموعة الكلمات الفريدة ويتعلم قواعد الدمج لتشكيل رمز جديد من رمزين من المفردات الأساسية. إنه يفعل ذلك حتى تصل المفردات إلى حجم المفردات المطلوب. لاحظ أن حجم المفردات هو فرط معلمة لتحديد قبل تدريب مُجزّئ النصوص. + +كمثال، دعنا نفترض أنه بعد التقسيم الأولي، تم تحديد مجموعة الكلمات التالية بما في ذلك تكرارها: + +``` +("hug", 10), ("pug", 5), ("pun", 12), ("bun", 4), ("hugs", 5) +``` + +وبالتالي، فإن المفردات الأساسية هي `["b"، "g"، "h"، "n"، "p"، "s"، "u"]`. من خلال تقسيم جميع الكلمات إلى رموز من +المفردات الأساسية، نحصل على: + +``` +("h" "u" "g"، 10)، ("p" "u" "g"، 5)، ("p" "u" "n"، 12)، ("b" "u" "n"، 4)، ("h" "u" "g" "s"، 5) +``` + +بعد ذلك، يقوم BPE بعدد مرات حدوث كل زوج من الرموز المحتملة ويختار زوج الرموز الذي يحدث بشكل متكرر. في +في المثال أعلاه، يحدث "h" متبوعًا بـ "u" _10 + 5 = 15_ مرة (10 مرات في 10 مرات +حدوث "hug"، 5 مرات في 5 مرات حدوث "hugs"). ومع ذلك، فإن أكثر أزواج الرموز شيوعًا هو "u" متبوعًا +بواسطة "g"، والتي تحدث _10 + 5 + 5 = 20_ مرة في المجموع. وبالتالي، فإن أول قاعدة دمج يتعلمها المحلل هي تجميع جميع +رموز "u" التي تتبعها "g" معًا. بعد ذلك، يتم إضافة "ug" إلى المفردات. تصبح مجموعة الكلمات + +``` +("h" "ug"، 10)، ("p" "ug"، 5)، ("p" "u" "n"، 12)، ("b" "u" "n"، 4)، ("h" "ug" "s"، 5) +``` + +بعد ذلك، يحدد BPE ثاني أكثر أزواج الرموز شيوعًا. إنه "u" متبوعًا بـ "n"، والذي يحدث 16 مرة. "u"، +يتم دمج "n" في "un" ويضاف إلى المفردات. ثالث أكثر أزواج الرموز شيوعًا هو "h" متبوعًا +بواسطة "ug"، والتي تحدث 15 مرة. مرة أخرى يتم دمج الزوج ويتم إضافة "hug" إلى المفردات. + +في هذه المرحلة، تكون المفردات هي `["b"، "g"، "h"، "n"، "p"، "s"، "u"، "ug"، "un"، "hug"]` ومجموعة الكلمات الفريدة لدينا +تمثيله كما يلي: + +``` +("hug", 10), ("p" "ug", 5), ("p" "un", 12), ("b" "un", 4), ("hug" "s", 5) +``` + +بافتراض أن تدريب ترميز الأزواج البايت سيتوقف عند هذه النقطة، فسيتم تطبيق قواعد الدمج التي تم تعلمها بعد ذلك على الكلمات الجديدة (طالما أن هذه الكلمات الجديدة لا تشمل رموزًا لم تكن في المفردات الأساسية). على سبيل المثال، سيتم تقسيم كلمة "bug" إلى `["b"، "ug"]` ولكن سيتم تقسيم "mug" على أنها `[""، "ug"]` نظرًا لأن الرمز "m" غير موجود في المفردات الأساسية. بشكل عام، لا يتم استبدال الأحرف الفردية مثل "m" بالرمز "" لأن بيانات التدريب تتضمن عادةً ظهورًا واحدًا على الأقل لكل حرف، ولكن من المحتمل أن يحدث ذلك لرموز خاصة جدًا مثل الرموز التعبيرية. + +كما ذكرنا سابقًا، فإن حجم المفردات، أي حجم المفردات الأساسية + عدد عمليات الدمج، هو معامل يجب اختياره. على سبيل المثال، لدى [GPT](model_doc/openai-gpt) حجم مفردات يبلغ 40478 منذ أن كان لديهم 478 حرفًا أساسيًا واختاروا التوقف عن التدريب بعد 40,000 عملية دمج. + +#### ترميز الأزواج البايتية على مستوى البايت + +قد تكون المفردات الأساسية التي تتضمن جميع الأحرف الأساسية كبيرة جدًا إذا *على سبيل المثال* تم اعتبار جميع أحرف اليونيكود +كأحرف أساسية. لذا، ليكون لديك مفردات أساسية أفضل، يستخدم [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) البايتات كمفردات أساسية، وهي حيلة ذكية لإجبار المفردات الأساسية على أن تكون بحجم 256 مع ضمان أن يتم تضمين كل حرف أساسي في المفردات. مع بعض القواعد الإضافية للتعامل مع علامات الترقيم، يمكن لمُجزّئ النصوص GPT2 تجزئة أي نص دون الحاجة إلى رمز . لدى [GPT-2](model_doc/gpt) حجم مفردات يبلغ 50257، والذي يتوافق مع رموز 256 base byte، ورمز خاص لنهاية النص والرموز التي تم تعلمها باستخدام 50000 عملية دمج. + + + +### WordPiece + +تعتبر WordPiece خوارزمية تجزئة الكلمات الفرعية subword المستخدمة لـ [BERT](model_doc/bert)، [DistilBERT](model_doc/distilbert)، و [Electra](model_doc/electra). تم توضيح الخوارزمية في [البحث الصوتي الياباني والكوري +(Schuster et al.، 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf) وهو مشابه جدًا +BPE. أولاً، يقوم WordPiece بتكوين المفردات لتضمين كل حرف موجود في بيانات التدريب +وتعلم تدريجياً عددًا معينًا من قواعد الدمج. على عكس BPE، لا يختار WordPiece أكثر زوج الرموز المتكررة، ولكن تلك التي تزيد من احتمال بيانات التدريب بمجرد إضافتها إلى المفردات. + +لذا، ماذا يعني هذا بالضبط؟ بالإشارة إلى المثال السابق، فإن زيادة احتمال بيانات التدريب تعادل إيجاد زوج الرموز، الذي يكون احتمال تقسيمه على احتمالات رمزه الأول تليها رمزه الثاني هو الأكبر بين جميع أزواج الرموز. *مثال* `"u"`، تليها `"g"` كانت قد اندمجت فقط إذا كان احتمال `"ug"` مقسومًا على `"u"`، `"g"` كان سيكون أكبر من أي زوج آخر من الرموز. بديهيًا، WordPiece مختلف قليلاً عن BPE في أنه يقيم ما يفقده عن طريق دمج رمزين للتأكد من أنه يستحق ذلك. + + + +### Unigram + +Unigram هو خوارزمية توكنيز subword التي تم تقديمها في [تنظيم subword: تحسين نماذج الترجمة الشبكة العصبية +نماذج مع مرشحين subword متعددة (Kudo، 2018)](https://arxiv.org/pdf/1804.10959.pdf). على عكس BPE أو +WordPiece، يقوم Unigram بتكوين مفرداته الأساسية إلى عدد كبير من الرموز ويقللها تدريجياً للحصول على مفردات أصغر. يمكن أن تتوافق المفردات الأساسية على سبيل المثال مع جميع الكلمات المسبقة التوكنز والسلاسل الفرعية الأكثر شيوعًا. لا يتم استخدام Unigram مباشرة لأي من النماذج في المحولات، ولكنه يستخدم بالاقتران مع [SentencePiece](#sentencepiece). + +في كل خطوة تدريب، يحدد خوارزمية Unigram خسارة (غالبًا ما يتم تعريفها على أنها اللوغاريتم) عبر بيانات التدريب بالنظر إلى المفردات الحالية ونموذج اللغة unigram. بعد ذلك، بالنسبة لكل رمز في المفردات، يحسب الخوارزمية مقدار زيادة الخسارة الإجمالية إذا تم إزالة الرمز من المفردات. ثم يقوم Unigram بإزالة p (مع p عادة ما تكون 10% أو 20%) في المائة من الرموز التي تكون زيادة الخسارة فيها هي الأدنى، *أي* تلك +الرموز التي تؤثر أقل على الخسارة الإجمالية عبر بيانات التدريب. تتكرر هذه العملية حتى تصل المفردات إلى الحجم المطلوب. يحتفظ خوارزمية Unigram دائمًا بالشخصيات الأساسية بحيث يمكن توكنز أي كلمة. + +نظرًا لأن Unigram لا يعتمد على قواعد الدمج (على عكس BPE وWordPiece)، فإن للخوارزمية عدة طرق +توكنز نص جديد بعد التدريب. على سبيل المثال، إذا كان محول Unigram المدرب يعرض المفردات: + +``` +["b"، "g"، "h"، "n"، "p"، "s"، "u"، "ug"، "un"، "hug"]، +``` + +يمكن توكنز `"hugs"` على أنه `["hug"، "s"]`، أو `["h"، "ug"، "s"]` أو `["h"، "u"، "g"، "s"]`. إذن ماذا +لاختيار؟ يحفظ Unigram احتمال كل رمز في فيلق التدريب بالإضافة إلى حفظ المفردات بحيث +يمكن حساب احتمال كل توكنز ممكن بعد التدريب. ببساطة، يختار الخوارزمية الأكثر +توكنز المحتملة في الممارسة، ولكنه يوفر أيضًا إمكانية أخذ عينات من توكنز ممكن وفقًا لاحتمالاتها. + +تتم تعريف هذه الاحتمالات بواسطة الخسارة التي يتم تدريب المحول عليها. بافتراض أن بيانات التدريب تتكون +من الكلمات \\(x_{1}، \dots، x_{N}\\) وأن مجموعة جميع التوكنزات الممكنة لكلمة \\(x_{i}\\) هي +يتم تعريفها على أنها \\(S(x_{i})\\)، ثم يتم تعريف الخسارة الإجمالية على النحو التالي + +$$\mathcal{L} = -\sum_{i=1}^{N} \log \left ( \sum_{x \in S(x_{i})} p(x) \right )$$ + + + +### SentencePiece + +تحتوي جميع خوارزميات توكنز الموصوفة حتى الآن على نفس المشكلة: من المفترض أن النص المدخل يستخدم المسافات لفصل الكلمات. ومع ذلك، لا تستخدم جميع اللغات المسافات لفصل الكلمات. أحد الحلول الممكنة هو استخداممعالج مسبق للغة محدد، *مثال* [XLM](model_doc/xlm) يلذي يستخدم معالجات مسبقة محددة للصينية واليابانية والتايلاندية. +لحل هذه المشكلة بشكل أعم، [SentencePiece: A simple and language independent subword tokenizer and +detokenizer for Neural Text Processing (Kudo et al.، 2018)](https://arxiv.org/pdf/1808.06226.pdf) يتعامل مع المدخلات +كتدفق بيانات خام، وبالتالي يشمل المسافة في مجموعة الأحرف التي سيتم استخدامها. ثم يستخدم خوارزمية BPE أو unigram +لبناء المفردات المناسبة. + +يستخدم [`XLNetTokenizer`] SentencePiece على سبيل المثال، وهو أيضًا سبب تضمين تم تضمين حرف `"▁"` في المفردات. عملية فك التشفير باستخدام SentencePiece سهلة للغاية نظرًا لأنه يمكن دائمًا دمج الرموز معًا واستبدال `"▁"` بمسافة. + +تستخدم جميع نماذج المحولات في المكتبة التي تستخدم SentencePiece بالاقتران مع unigram. أمثلة على النماذج +باستخدام SentencePiece هي [ALBERT](model_doc/albert)، [XLNet](model_doc/xlnet)، [Marian](model_doc/marian)، و [T5](model_doc/t5). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/torchscript.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/torchscript.md new file mode 100644 index 0000000000000000000000000000000000000000..bf0bc0dde04b629932d32f85e15529a6c0128305 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/torchscript.md @@ -0,0 +1,154 @@ +# التصدير إلى TorchScript + + + +هذه هي بداية تجاربنا مع TorchScript ولا زلنا نستكشف قدراته مع نماذج المدخلات المتغيرة الحجم. إنه مجال اهتمامنا وسنعمق تحليلنا في الإصدارات القادمة، مع المزيد من الأمثلة البرمجية، وتنفيذ أكثر مرونة، ومقاييس مقارنة بين الأكواد القائمة على Python مع أكواد TorchScript المُجمّعة. + + + +وفقًا لـ [وثائق TorchScript](https://pytorch.org/docs/stable/jit.html): + +> TorchScript هي طريقة لإنشاء نماذج قابلة للتسلسل والتحسين من تعليمات PyTorch البرمجية. + +هناك وحدتان من PyTorch، [JIT and TRACE](https://pytorch.org/docs/stable/jit.html)، تتيحان للمطورين تصدير نماذجهم لإعادة استخدامها في برامج أخرى مثل برامج C++ المُحسّنة للأداء. + +نقدم واجهة تتيح لك تصدير نماذج 🤗 Transformers إلى TorchScript بحيث يمكن إعادة استخدامها في بيئة مختلفة عن برامج Python القائمة إلى PyTorch. هنا نشرح كيفية تصدير نماذجنا واستخدامها باستخدام TorchScript. + +يتطلب تصدير نموذج أمرين: + +- تهيئة مثيل للنموذج باستخدام علامة `torchscript` +- تمرير مُدخلات وهمية (dummy inputs) خلال النموذج + +تنطوي هذه الضرورات على عدة أمور يجب على المطورين توخي الحذر بشأنها كما هو مفصل أدناه. + +## علامة TorchScript والأوزان المرتبطة + +علامة `torchscript` ضرورية لأن معظم نماذج اللغة 🤗 Transformers لها أوزان مرتبطة بين طبقة `Embedding` وطبقة `Decoding`. لا يسمح لك TorchScript بتصدير النماذج ذات الأوزان المرتبطة، لذلك من الضروري فصل الأوزان ونسخها مسبقًا. + +النماذج المُهيأة باستخدام علامة `torchscript` لها طبقة `Embedding` وطبقة`Decoding` منفصلتين، مما يعني أنه لا ينبغي تدريبها لاحقًا. سيؤدي التدريب إلى عدم تزامن الطبقتين، مما يؤدي إلى نتائج غير متوقعة. + +هذا لا ينطبق على النماذج التي لا تحتوي على رأس نموذج اللغة، حيث لا تملك أوزانًا مرتبطة. يمكن تصدير هذه النماذج بأمان دون علامة `torchscript`. + +## المدخلات الوهمية والأطوال القياسية + +تُستخدم المُدخلات الوهمية لتمرير أمامي خلال النموذج. أثناء انتشار قيم المُدخلات عبر الطبقات، يتتبع PyTorch العمليات المختلفة التي يتم تنفيذها على كل مصفوفة(tensor). ثم يتم استخدام هذه العمليات المُسجلة بعد ذلك لإنشاء *أثر* النموذج. + +يتم إنشاء التتبع بالنسبة لأبعاد المُدخلات. وبالتالي، فهو مُقيّد بأبعاد المُدخلات الوهمية، ولن يعمل لأي طول تسلسل أو حجم دفعة مختلف. عند المحاولة بحجم مختلف، يتم رفع الخطأ التالي: + +``` +`The expanded size of the tensor (3) must match the existing size (7) at non-singleton dimension 2` +``` + +نوصي بتتبع النموذج باستخدام حجم مُدخلات وهمية لا يقل عن أكبر مُدخل سيتم تقديمه للنموذج أثناء الاستدلال. يمكن أن تساعد الحشوة(padding) في ملء القيم المفقودة. ومع ذلك، نظرًا لتتبع النموذج بحجم مُدخل أكبر، ستكون أبعاد المصفوفة ستكون كبيرة أيضًا، مما يؤدي عنه المزيد من الحسابات. + +انتبه إلى إجمالي عدد العمليات المُنفذة على كل مُدخل وتابع الأداء عن كثب عند تصدير نماذج متغيرة طول التسلسل. + +## استخدام TorchScript في Python + +يوضح هذا القسم كيفية حفظ النماذج وتحميلها، بالإضافة إلى كيفية استخدام التتبع للاستدلال. + +### حفظ نموذج + +لتصدير `BertModel` باستخدام TorchScript، قم بتهيئة ـ `BertModel` من فئة `BertConfig` ثم احفظه على القرص تحت اسم الملف `traced_bert.pt`: + +```python +from transformers import BertModel, BertTokenizer, BertConfig +import torch + +enc = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") + +# Tokenizing input text +text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]" +tokenized_text = enc.tokenize(text) + +# Masking one of the input tokens +masked_index = 8 +tokenized_text[masked_index] = "[MASK]" +indexed_tokens = enc.convert_tokens_to_ids(tokenized_text) +segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] + +# Creating a dummy input +tokens_tensor = torch.tensor([indexed_tokens]) +segments_tensors = torch.tensor([segments_ids]) +dummy_input = [tokens_tensor, segments_tensors] + +# Initializing the model with the torchscript flag +# Flag set to True even though it is not necessary as this model does not have an LM Head. +config = BertConfig( + vocab_size_or_config_json_file=32000, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + torchscript=True, +) + +# Instantiating the model +model = BertModel(config) + +# The model needs to be in evaluation mode +model.eval() + +# If you are instantiating the model with *from_pretrained* you can also easily set the TorchScript flag +model = BertModel.from_pretrained("google-bert/bert-base-uncased", torchscript=True) + +# Creating the trace +traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors]) +torch.jit.save(traced_model, "traced_bert.pt") +``` + +### تحميل نموذج + +يمكنك الآن تحميل `BertModel` المُحفظ سابقًا، `traced_bert.pt`، من القرص واستخدامه على `dummy_input` المُهيأ سابقًا: + +```python +loaded_model = torch.jit.load("traced_bert.pt") +loaded_model.eval() + +all_encoder_layers, pooled_output = loaded_model(*dummy_input) +``` + +### استخدام نموذج مُتتبع للاستدلال + +استخدم النموذج المُتتبع للاستدلال باستخدام أسلوب `__call__` الخاص به: + +```python +traced_model(tokens_tensor, segments_tensors) +``` + +## نشر نماذج Hugging Face TorchScript على AWS باستخدام Neuron SDK + +قدمت AWS عائلة [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/) من اﻷجهزة لخفض التكلفة وأداء التعلم الآلي عالي الأداء في البيئة السحابية. تعمل أجهزة Inf1 بواسطة شريحة Inferentia من AWS، وهي مُسرّع أجهزة مُخصص، متخصص في أعباء عمل الاستدلال للتعلم العميق. [AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#) هي SDK لـ Inferentia التي تدعم تتبع نماذج المحولات وتحسينها للنشر على Inf1. توفر Neuron SDK ما يلي: + +1. واجهة برمجة تطبيقات سهلة الاستخدام مع تغيير سطر واحد من التعليمات البرمجية لتتبع نموذج TorchScript وتحسينه للاستدلال في البيئة السحابية. +2. تحسينات الأداء الجاهزة للاستخدام [تحسين التكلفة والأداء](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>). +3. دعم نماذج Hugging Face المحولات المبنية باستخدام إما [PyTorch](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html) أو [TensorFlow](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/tensorflow/huggingface_bert/huggingface_bert.html). + +### الآثار المترتبة + +تعمل نماذج المحولات المستندة إلى بنية [BERT (تمثيلات الترميز ثنائية الاتجاه من المحولات)](https://huggingface.co/docs/transformers/main/model_doc/bert) أو متغيراتها مثل [distilBERT](https://huggingface.co/docs/transformers/main/model_doc/distilbert) و [roBERTa](https://huggingface.co/docs/transformers/main/model_doc/roberta) بشكل أفضل على Inf1 للمهام غير التوليدية مثل الإجابة على الأسئلة الاستخراجية، وتصنيف التسلسلات، وتصنيف الرموز (tokens). ومع ذلك، يمكن تكييف مهام توليد النصوص للعمل على Inf1 وفقًا لهذا [برنامج تعليمي AWS Neuron MarianMT](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html). يمكن العثور على مزيد من المعلومات حول النماذج التي يمكن تحويلها جاهزة على Inferentia في قسم [ملاءمة بنية النموذج](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia) من وثائق Neuron. + +### التبعيات (Dependencies) + +يتطلب استخدام AWS Neuron لتحويل النماذج [بيئة SDK Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide) والتي تأتي مسبقًا على [AMI للتعلم العميق من AWS](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html). + +### تحويل نموذج لـ AWS Neuron + +قم بتحويل نموذج لـ AWS NEURON باستخدام نفس التعليمات البرمجية من [استخدام TorchScript في Python](torchscript#using-torchscript-in-python) لتتبع `BertModel`. قم باستيراد امتداد إطار عمل `torch.neuron` للوصول إلى مكونات Neuron SDK من خلال واجهة برمجة تطبيقات Python: + +```python +from transformers import BertModel, BertTokenizer, BertConfig +import torch +import torch.neuron +``` + +كل ما عليك فعله هو تعديل السطر التالي: + +```diff +- torch.jit.trace(model, [tokens_tensor, segments_tensors]) ++ torch.neuron.trace(model, [token_tensor, segments_tensors]) +``` + +يتيح ذلك لـ Neuron SDK تتبع النموذج وتحسينه لمثيلات Inf1. + +لمعرفة المزيد حول ميزات AWS Neuron SDK والأدوات ودروس البرامج التعليمية والتحديثات الأخيرة، يرجى الاطلاع على [وثائق AWS NeuronSDK](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/trainer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..e70dbb255eacbe1f37bab701ee9374ca6f5cd217 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/trainer.md @@ -0,0 +1,743 @@ +# Trainer + +تُتيح وحدة [`Trainer`] حلقة تدريب وتقييم متكاملة لنماذج PyTorch المطبقة في مكتبة Transformers. تحتاج فقط إلى تمرير المكونات الضرورية للتدريب (النموذج، والمجزىء النصى، ومجموعة البيانات، دالة التقييم، معلمات التدريب الفائقة، إلخ)، وستتولى فئة [`Trainer`] الباقي. هذا يُسهّل بدء التدريب بشكل أسرع دون كتابة حلقة التدريب الخاصة بك يدويًا. ولكن في الوقت نفسه، فإن [`Trainer`] قابل للتخصيص بدرجة كبيرة ويوفر العديد من خيارات التدريب حتى تتمكن من تخصيصه وفقًا لاحتياجات التدريب الخاصة بك بدقة. + + + +بالإضافة إلى فئة [`Trainer`], توفر مكتبة Transformers أيضًا فئة [`Seq2SeqTrainer`] للمهام التسلسلية مثل الترجمة أو التلخيص. هناك أيضًا فئة [`~trl.SFTTrainer`] من مكتبة [TRL](https://hf.co/docs/trl) التي تغلّف فئة [`Trainer`] وهي مُحُسَّنة لتدريب نماذج اللغة مثل Llama-2 وMistral باستخدام تقنيات التوليد اللغوي. كما يدعم [`~trl.SFTTrainer`] ميزات مثل حزم التسلسلات، وLoRA، والقياس الكمي، وDeepSpeed مما يُمكّن من التدريب بكفاءة على نماذج ضخمة الحجم. + +
+ +لا تتردد في الاطلاع على [مرجع API](./main_classes/trainer) لهذه الفئات الأخرى من النوع [`Trainer`] لمعرفة المزيد حول متى يتم استخدام كل منها. بشكل عام، [`Trainer`] هو الخيار الأكثر تنوعًا ومناسبًا لمجموعة واسعة من المهام. تم تصميم [`Seq2SeqTrainer`] للمهام التسلسلية ، و [`~trl.SFTTrainer`] مُصمم لتدريب نماذج اللغة الكبيرة. + +
+ +قبل البدء، تأكد من تثبيت مكتبة [Accelerate](https://hf.co/docs/accelerate) - وهي مكتبة تُمكّن تشغيل تدريب PyTorch في بيئات مُوزعة. + +```bash +pip install accelerate + +# upgrade +pip install accelerate --upgrade +``` + +يوفر هذا الدليل نظرة عامة على فئة [`Trainer`]. + +## الاستخدام الأساسي + +يتضمن [`Trainer`] جميع التعليمات البرمجية التي ستجدها في حلقة التدريب الأساسية: + +1. قم بتنفيذ خطوة تدريب لحساب الخسارة +2. احسب المشتقات باستخدام طريقة [`~accelerate.Accelerator.backward`] +3. تحديث الأوزان بناءً على المشتقات +4. كرر هذه العملية حتى تصل إلى عدد محدد مسبقًا من الدورات (epochs). + +تُجرد فئة [`Trainer`] كل هذه التعليمات البرمجية حتى لا تضطر إلى القلق بشأن كتابة حلقة تدريب يدويًا في كل مرة أما إذا كنت بدأت للتو في PyTorch والتدريب. كل ما عليك فعله هو توفير المكونات الأساسية اللازمة للتدريب، مثل النموذج ومجموعة بيانات، وتتعامل فئة [`Trainer`] مع كل شيء آخر. + +إذا كنت تُريد تحديد أي خيارات تدريب أو معلمات فائقة، فيمكنك العثور عليها في فئة [`TrainingArguments`]. على سبيل المثال، دعنا نحدد أين يتم حفظ النموذج في `output_dir` ورفع النموذج إلى Hub بعد التدريب باستخدام `push_to_hub=True`. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="your-model"، + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + weight_decay=0.01, + eval_strategy="epoch"، + save_strategy="epoch"، + load_best_model_at_end=True, + push_to_hub=True, +) +``` +مرر `training_args` إلى [`Trainer`] جنبًا إلى جنب مع النموذج، ومجموعة بيانات، وشئ لمعالجة مجموعة البيانات مسبقًا (حسب نوع البيانات، فقد يكون محللًا رمزيًا أو مستخرج ميزات أو معالج صور)، وجامع بيانات، ودالة لحساب المقاييس التي تُريد تتبعها أثناء التدريب. + +أخيرًا، استدعِ [`~Trainer.train`] لبدء التدريب! + +```py +from transformers import Trainer + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"]، + eval_dataset=dataset["test"]، + tokenizer=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, +) + +trainer.train() +``` + +### نقاط الحفظ + +تحفظ فئة [`Trainer`] نقاط الحفظ النموذج في الدليل المحدد في معامل `output_dir` من [`TrainingArguments`]. ستجد نقاط الحفظ في مجلد فرعي يسمى `checkpoint-000` حيث تتوافق الأرقام في النهاية مع خطوة التدريب. إن حفظ نقاط الحفظ مفيد لاستئناف التدريب لاحقًا. + +```py +# استأنف من أحدث نقطة حفظ +trainer.train(resume_from_checkpoint=True) + +# استأنف من نقطة حفظ محددة محفوظة في دليل الإخراج +trainer.train(resume_from_checkpoint="your-model/checkpoint-1000") +``` + +يمكنك حفظ نقاط الحفظ الخاصة بك (لا يتم حفظ حالة المُجزىء اللغوى تقائيًا) إلى Hub عن طريق تعيين `push_to_hub=True` في [`TrainingArguments`] لرفعها. الخيارات الأخرى لاتخاذ القرار بشأن كيفية حفظ هذة النقاط الخاصة بك هي الإعداد في معامل [`hub_strategy`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.hub_strategy): + +* `hub_strategy="checkpoint"` يدفع أحدث نقطة حفظ إلى مجلد فرعي يسمى "last-checkpoint" يمكنك استئناف التدريب منه +* `hub_strategy="all_checkpoints"` يدفع جميع نقاط الحفظ إلى الدليل المحدد في `output_dir` (سترى نقطة حفظ واحدة لكل مجلد في مستودع النموذج الخاص بك) + +عند استئناف التدريب من نقطة حفظ، تُحاول [`Trainer`] الحفاظ على حالات RNG Python وNumPy وPyTorch كما كانت عندما تم حفظ نقطة الحفظ. ولكن لأن PyTorch لديها العديد من الإعدادات الافتراضية غير الحتمية مُتنوعة، فإن حالات RNG ليست مضمونة لتكون هي نفسها. إذا كنت تريد تمكين الحتمية الكاملة، فراجع دليل [التحكم في مصادر العشوائية](https://pytorch.org/docs/stable/notes/randomness#controlling-sources-of-randomness) لمعرفة ما يُمكنك تمكينه لجعل تدريبك حتميًا تمامًا. ضع في اعتبارك أنه من خلال جعل إعدادات معينة حتمية، فقد يكون التدريب أبطأ. + +## تخصيص المدرب + +في حين أن فئة [`Trainer`] مُصممة لتكون سهلة الوصول وسهلة الاستخدام، فإنها توفر أيضًا الكثير من قابلية التخصيص للمستخدمين المغامرين. يُمكن إنشاء فئات فرعية من العديد من أساليب [`Trainer`] وتجاوزها لدعم الوظائف التي تُريدها، دون الحاجة إلى إعادة كتابة حلقة التدريب بأكملها من البداية لاستيعابها. تتضمن هذه الأساليب: + +* [`~Trainer.get_train_dataloader`] ينشئ DataLoader للتدريب +* [`~Trainer.get_eval_dataloader`] ينشئ DataLoader للتقييم +* [`~Trainer.get_test_dataloader`] ينشئ DataLoader للاختبار +* [`~Trainer.log`] يسجل معلومات حول مختلف الكائنات التي تراقب التدريب +* [`~Trainer.create_optimizer_and_scheduler`] ينشئ محسنًا ومخططًا لمُعدل التعلم إذا لم يتم تمريرهما في `__init__`؛ يمكن أيضًا تخصيص هذه الوظائف بشكل منفصل باستخدام [`~Trainer.create_optimizer`] و [`~Trainer.create_scheduler`] على التوالي +* [`~Trainer.compute_loss`] يحسب دالة الخسارة على دفعة من مُدخلات التدريب +* [`~Trainer.training_step`] يُنفذ خطوة التدريب +* [`~Trainer.prediction_step`] يُنفذ خطوة التنبؤ والاختبار +* [`~Trainer.evaluate`] يُقيّم النموذج ويعيد مقاييس التقييم +* [`~Trainer.predict`] يُجري التنبؤات (مع المقاييس إذا كانت العلامات متاحة) على مجموعة الاختبار + +على سبيل المثال، إذا كنت تريد تخصيص طريقة [`~Trainer.compute_loss`] لاستخدام دالة خسارة ذات ترجيح بدلاً من ذلك. + + +```py +from torch import nn +from transformers import Trainer + +class CustomTrainer(Trainer): + def compute_loss(self, model, inputs, return_outputs=False): + labels = inputs.pop("labels") + # forward pass + outputs = model(**inputs) + logits = outputs.get("logits") + # compute custom loss for 3 labels with different weights + loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device)) + loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) + return (loss, outputs) if return_outputs else loss +``` + +### دوال الاستدعاء Callbacks + +خيار آخر لتخصيص [`Trainer`] هو استخدام [دوال الاستدعاء](callbacks). لا *تغير* دوال الاستدعاء أي شيء في حلقة التدريب. إنهم تفحص حالة حلقة التدريب ثم تُنفذ بعض الإجراءات (مثل الإيقاف المبكر أو تسجيل النتائج، إلخ) اعتمادًا على الحالة. وبعبارة أخرى، لا يمكن استخدام دالة الاستدعاء لتنفيذ شيء مثل دالة خسارة مخصصة، ويجب عليك تجاوز دالة [`~Trainer.compute_loss`] لذلك. + +على سبيل المثال، إذا كنت تريد إضافة دالة استدعاء إيقاف مبكر إلى حلقة التدريب بعد 10 خطوات. + +```py +from transformers import TrainerCallback + +class EarlyStoppingCallback(TrainerCallback): + def __init__(self, num_steps=10): + self.num_steps = num_steps + + def on_step_end(self, args, state, control, **kwargs): + if state.global_step >= self.num_steps: + return {"should_training_stop": True} + else: + return {} +``` + +ثم مرره إلى معامل `callback` في [`Trainer`]. + +```py +from transformers import Trainer + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"]، + eval_dataset=dataset["test"]، + tokenizer=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, + callback=[EarlyStoppingCallback()], +) +``` + +## تسجيل الأحداث (Logging) + + + +راجع مرجع [API](./main_classes/logging) للتسجيل للحصول على مزيد من المعلومات حول مستويات التسجيل المختلفة للأحداث. + + + +يتم تعيين [`Trainer`] إلى `logging.INFO` افتراضيًا والذي يُبلغ عن الأخطاء والتحذيرات ومعلومات أساسية أخرى. يتم تعيين نسخة [`Trainer`] - في البيئات الموزعة - إلى `logging.WARNING` والتي يُبلغ فقط عن الأخطاء والتحذيرات. يمكنك تغيير مستوى تسجيل الأحداث باستخدام معاملي [`log_level`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level) و [`log_level_replica`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.log_level_replica) في [`TrainingArguments`]. + +لتهيئة إعداد مُستوى تسجيل اﻷحداث لكل عقدة، استخدم معامل [`log_on_each_node`](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments.log_on_each_node) لتحديد ما إذا كان سيتم استخدام مُستوى السجل على كل عقدة أو فقط على العقدة الرئيسية. + + + +يحدد [`Trainer`] مُستوى التسجيل بشكل مُنفصل لكل عقدة في طريقة [`Trainer.__init__`]، لذا فقد ترغب في التفكير في تعيين هذا الإعداد في وقت سابق إذا كنت تستخدم وظائف Transformers الأخرى قبل إنشاء كائن [`Trainer`]. + + + +على سبيل المثال، لتعيين التعليمات البرمجية والوحدات النمطية الرئيسية الخاصة بك لاستخدام نفس مُستوى التسجيل وفقًا لكل عقدة: + +```py +logger = logging.getLogger(__name__) + +logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"، + datefmt="%m/%d/%Y %H:%M:%S"، + handlers=[logging.StreamHandler(sys.stdout)], +) + +log_level = training_args.get_process_log_level() +logger.setLevel(log_level) +datasets.utils.logging.set_verbosity(log_level) +transformers.utils.logging.set_verbosity(log_level) + +trainer = Trainer(...) +``` + +استخدم تركيبات مختلفة من `log_level` و `log_level_replica` لتهيئة ما يتم تسجيله على كل من العقد. + + + + + +```bash +my_app.py ... --log_level warning --log_level_replica error +``` + + + + +أضف معلمة `log_on_each_node 0` لبيئات متعددة العقد. + +```bash +my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0 + +# set to only report errors +my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0 +``` + + + + +## NEFTune + +[NEFTune](https://hf.co/papers/2310.05914) هي تقنية يمكن أن تحسن الأداء عن طريق إضافة ضوضاء إلى مُتجهات التعلم أثناء التدريب. لتمكينه في [`Trainer`], قم بتعيين معامل `neftune_noise_alpha` في [`TrainingArguments`] للتحكم في مقدار الضوضاء المُضافة. + +```py +from transformers import TrainingArguments, Trainer + +training_args = TrainingArguments(..., neftune_noise_alpha=0.1) +trainer = Trainer(..., args=training_args) +``` + +يتم تعطيل NEFTune بعد التدريب لاستعادة طبقة التعلم الأصلية لتجنب أي سلوك غير متوقع. + +## نواة Liger +[Liger-Kernel](https://github.com/linkedin/Liger-Kernel) Kernel هي مجموعة من نوى Triton التي طورتها Linkedin مُصممة خصيصًا لتدريب نماذج اللغة الكبيرة (LLM). لقد قمنا بتنفيذ RMSNorm و RoPE و SwiGLU و CrossEntropy و FusedLinearCrossEntropy مُتوافقة مع Hugging Face، والمزيد قادم. يُمكنها زيادة إنتاجية التدريب متعدد وحدات معالجة الرسومات (GPU) بنسبة 20٪ وتقليل استخدام الذاكرة بنسبة 60٪. تعمل النواة بشكل تلقائي مع flash attention و PyTorch FSDP و Microsoft DeepSpeed. + +احصل على زيادة في الإنتاجية بنسبة 20٪ وتقليل استخدام الذاكرة بنسبة 60٪ على تدريب نماذج LLaMA 3-8B. حقق أطوال سياق أكبر وأحجام دفعات أكبر. كما أنها مُفيدة إذا كنت تُريد زيادة حجم نموذجك إلى تدريب بنماذج متعددة الرؤوس أو أحجام مُفردات ضخمة. أطلق العنان للتدريب بنماذج متعددة الرؤوس (medusa) والمزيد. راجع التفاصيل والأمثلة في [Liger](https://github.com/linkedin/Liger-Kernel/tree/main/examples) +تأكد أولاً من تثبيت مستودع Liger الرسمي: +```bash +pip install liger-kernel +``` +يجب عليك تمرير `use_liger_kernel=True` لتطبيق نواة `liger` على نموذجك، على سبيل المثال: + +```python +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="your-model", + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + weight_decay=0.01, + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + push_to_hub=True, + use_liger_kernel=True +) +``` + +تدعم النواة معماريات نماذج Llama و Gemma و Mistral و Mixtral. يُمكن العثور على أحدث قائمة بالنمائج المدعومة [هنا](https://github.com/linkedin/Liger-Kernel). عندما يتم تعيين `use_liger_kernel` إلى `True`، سيتم تصحيح الطبقات المُقابلة في النموذج الأصلي باستخدام تطبيق Liger الفعال، لذلك لا تحتاج إلى فعل أي شيء إضافي بخلاف تعيين قيمة المعامل. + +## المُحسِّنات +يمكنك اختيار مُحسِّن مدمج للتدريب باستخدام: +```python +from transformers import TrainingArguments +training_args = TrainingArguments(..., optim="adamw_torch") +``` +اطلع على [`OptimizerNames`](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) للاطلاع على القائمة الكاملة للخيارات. نُدرج أمثلة مُتقدمة في الأقسام أدناه. + +يمكنك أيضًا استخدام مُحسِّن PyTorch عشوائي عبر: +```python +import torch + +optimizer_cls = torch.optim.AdamW +optimizer_kwargs = { + "lr": 4e-3, + "betas": (0.9, 0.999), + "weight_decay": 0.05, +} + +from transformers import Trainer +trainer = Trainer(..., optimizer_cls_and_kwargs=(optimizer_cls, optimizer_kwargs)) +``` + + + + +### GaLore + +إسقاط التدرج ذو الرتبة المنخفضة (GaLore) هو إستراتيجية تدريب ذات رتبة منخفضة فعّالة من حيث الذاكرة، تسمح بتعلم المعلمات الكاملة ولكنها أكثر كفاءة من حيث الذاكرة من أساليب التكيّف الشائعة ذات الرتبة المنخفضة، مثل LoRA. + +أولاً، تأكد من تثبيت المستودع الرسمي لـ GaLore: + +```bash +pip install galore-torch +``` + +ثم أضف ببساطة أحد `["galore_adamw"، "galore_adafactor"، "galore_adamw_8bit"]` في `optim` جنبًا إلى جنب مع `optim_target_modules`، والتي يمكن أن تكون قائمة من السلاسل أو التعبيرات النمطية regex أو المسار الكامل المطابق لأسماء الوحدات المستهدفة التي تريد تكييفها. فيما يلي مثال على النص البرمجي كامل(تأكد من `pip install trl datasets`): + +```python +import torch +import datasets +import trl + +from transformers import TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForCausalLM + +train_dataset = datasets.load_dataset('imdb', split='train') + +args = TrainingArguments( + output_dir="./test-galore"، + max_steps=100, + per_device_train_batch_size=2, + optim="galore_adamw"، + optim_target_modules=[r".*.attn.*"، r".*.mlp.*"] +) + +model_id = "google/gemma-2b" + +config = AutoConfig.from_pretrained(model_id) + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_config(config).to(0) + +trainer = trl.SFTTrainer( + model=model, + args=args, + train_dataset=train_dataset, + dataset_text_field='text', + max_seq_length=512, +) + +trainer.train() +``` + +لتمرير معامﻻت إضافية يدعمها GaLore، يجب عليك تمرير `optim_args` بشكل صحيح، على سبيل المثال: + +```python +import torch +import datasets +import trl + +from transformers import TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForCausalLM + +train_dataset = datasets.load_dataset('imdb', split='train') + +args = TrainingArguments( + output_dir="./test-galore", + max_steps=100, + per_device_train_batch_size=2, + optim="galore_adamw", + optim_target_modules=[r".*.attn.*", r".*.mlp.*"], + optim_args="rank=64, update_proj_gap=100, scale=0.10", +) + +model_id = "google/gemma-2b" + +config = AutoConfig.from_pretrained(model_id) + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_config(config).to(0) + +trainer = trl.SFTTrainer( + model=model, + args=args, + train_dataset=train_dataset, + dataset_text_field='text', + max_seq_length=512, +) + +trainer.train() +``` +يمكنك قراءة المزيد حول الطريقة في [المستودع الأصلي](https://github.com/jiaweizzhao/GaLore) أو [الورقة البحثية](https://arxiv.org/abs/2403.03507). + +حاليًا، يمكنك فقط تدريب الطبقات الخطية التي تعتبر طبقات GaLore وستستخدم التحلل ذو الرتبة المنخفضة للتدريب بينما سيتم تحسين الطبقات المتبقية بالطريقة التقليدية. + +لاحظ أنه سيستغرق الأمر بعض الوقت قبل بدء التدريب (~3 دقائق لنموذج 2B على NVIDIA A100)، ولكن يجب أن يسير التدريب بسلاسة بعد ذلك. + +يمكنك أيضًا إجراء تحسين طبقة تلو الأخرى عن طريق إضافة `layerwise` إلى اسم المُحسِّن كما هو موضح أدناه: + +```python +import torch +import datasets +import trl + +from transformers import TrainingArguments، AutoConfig، AutoTokenizer، AutoModelForCausalLM + +train_dataset = datasets.load_dataset('imdb'، split='train') + +args = TrainingArguments( + output_dir="./test-galore"، + max_steps=100، + per_device_train_batch_size=2، + optim="galore_adamw_layerwise"، + optim_target_modules=[r".*.attn.*"، r".*.mlp.*"] +) + +model_id = "google/gemma-2b" + +config = AutoConfig.from_pretrained(model_id) + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_config(config).to(0) + +trainer = trl.SFTTrainer( + model=model، + args=args، + train_dataset=train_dataset، + dataset_text_field='text'، + max_seq_length=512، +) + +trainer.train() +``` + +لاحظ أن تحسين الطبقة تجريبي إلى حد ما ولا يدعم DDP (Distributed Data Parallel)، وبالتالي يمكنك تشغيل التعليمات البرمجية للتدريب على وحدة معالجة الرسومات (GPU) واحدة فقط. يرجى الاطلاع على [هذا القسم المناسب](https://github.com/jiaweizzhao/GaLore?tab=readme-ov-file#train-7b-model-with-a-single-gpu-with-24gb-memory) لمزيد من التفاصيل. قد لا تدعم الميزات الأخرى مثل تقليم التدرجات أو DeepSpeed، إلخ. من الصندوق. يرجى [تقديم تقرير عن المشكلة على GitHub](https://github.com/huggingface/transformers/issues) إذا واجهتك مثل هذه المشكلة. + +### محسنات LOMO + +تم تقديم مُحسِّنات LOMO في [التدريب على المعلمات الكاملة لنماذج اللغة الكبيرة باستخدام موارد محدودة](https://hf.co/papers/2306.09782) و [AdaLomo: تحسين ذاكرة منخفضة بمعدل تعلم متكيف](https://hf.co/papers/2310.10195). +يتكون كلاهما من طريقة فعالة لضبط المعلمات الكاملة. تدمج محسنات LOMO حساب الاشتقاق وتحديث المعلمات في خطوة واحدة لتقليل استخدام الذاكرة. محسنات LOMO المدعومة هي `"lomo"` و `"adalomo"`. أولاً قم بتثبيت LOMO من pypi `pip install lomo-optim` أو قم بتثبيته من المصدر باستخدام `pip install git+https://github.com/OpenLMLab/LOMO.git`. + + + +وفقًا للمؤلفين، يوصى باستخدام `AdaLomo` بدون `grad_norm` للحصول على أداء أفضل وسرعة أعلى. + + + +فيما يلي نص برمجي بسيط يوضح كيفية ضبط نموذج [google/gemma-2b](https://huggingface.co/google/gemma-2b) على مجموعة بيانات IMDB في الدقة الكاملة: + +```python +import torch +import datasets +from transformers import TrainingArguments، AutoTokenizer، AutoModelForCausalLM +import trl + +train_dataset = datasets.load_dataset('imdb'، split='train') + +args = TrainingArguments( + output_dir="./test-lomo"، + max_steps=100، + per_device_train_batch_size=4، + optim="adalomo"، + gradient_checkpointing=True، + logging_strategy="steps"، + logging_steps=1، + learning_rate=2e-6، + save_strategy="no"، + run_name="lomo-imdb"، +) + +model_id = "google/gemma-2b" + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id، low_cpu_mem_usage=True).to(0) + +trainer = trl.SFTTrainer( + model=model، + args=args، + train_dataset=train_dataset، + dataset_text_field='text'، + max_seq_length=1024، +) + +trainer.train() +``` + +### مُحسِّن GrokAdamW +تم تصميم مُحسِّن GrokAdamW لتعزيز أداء التدريب واستقراره، خاصةً للنماذج التي تستفيد من دوال إشارة `grokking`. لاستخدام `GrokAdamW`، قم أولاً بتثبيت حزمة المُحسِّن باستخدام `pip install grokadamw`. + +يُعد GrokAdamW مفيدًا بشكل خاص للنماذج التي تتطلب تقنيات تحسين مُتقدمة لتحقيق أداء واستقرار أفضل. + + +فيما يلي نص برمجى بسيط لشرح كيفية ضبط [google/gemma-2b](https://huggingface.co/google/gemma-2b) بدقة على مجموعة بيانات IMDB باستخدام مُحسِّن GrokAdamW: +```python +import torch +import datasets +from transformers import TrainingArguments, AutoTokenizer, AutoModelForCausalLM, Trainer + +# تحميل مجموعة البيانات IMDB +train_dataset = datasets.load_dataset('imdb', split='train') + +# تعريف معامﻻت التدريب +args = TrainingArguments( + output_dir="./test-grokadamw", + max_steps=1000, + per_device_train_batch_size=4, + optim="grokadamw", + logging_strategy="steps", + logging_steps=1, + learning_rate=2e-5, + save_strategy="no", + run_name="grokadamw-imdb", +) + +# تحميل النموذج والمجزىء اللغوي +model_id = "google/gemma-2b" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True).to(0) + +# تهيئة المدرب +trainer = Trainer( + model=model, + args=args, + train_dataset=train_dataset, +) + +# تدريب النموذج +trainer.train() +``` +يوضح هذا النص البرمجى كيفية ضبط نموذج google/gemma-2b بدقة على مجموعة بيانات IMDB باستخدام مُحسِّن GrokAdamW. يتم تكوين TrainingArguments لاستخدام GrokAdamW، ويتم تمرير مجموعة البيانات إلى Trainer للتدريب. + +### مُحسِّن بدون جدوله (Schedule Free Optimizer) +تم تقديم مُحسِّنات بدون جدوله في [The Road Less Scheduled](https://hf.co/papers/2405.15682). +يستبدل التعلم بدون جدوله زخم المُحسِّن الأساسي بمزيج من المتوسط ​​والتداخل، لإزالة الحاجة تمامًا إلى تخفيف مُعدل التعلم باستخدام جدوله تقليديه. +المُحسِّنات المدعومة لـ SFO هي "schedule_free_adamw" و "schedule_free_sgd". قم أولاً بتثبيت `schedulefree` من pypi باستخدام الأمر `pip install schedulefree`. + +فيما يلي نص برمجى بسيط لشرح كيفية ضبط [google/gemma-2b](https://huggingface.co/google/gemma-2b) بدقة على مجموعة بيانات IMDB بدقة كاملة: +```python +import torch +import datasets +from transformers import TrainingArguments, AutoTokenizer, AutoModelForCausalLM +import trl + +train_dataset = datasets.load_dataset('imdb', split='train') + +args = TrainingArguments( + output_dir="./test-schedulefree", + max_steps=1000, + per_device_train_batch_size=4, + optim="schedule_free_adamw", + gradient_checkpointing=True, + logging_strategy="steps", + logging_steps=1, + learning_rate=2e-6, + save_strategy="no", + run_name="sfo-imdb", +) + +model_id = "google/gemma-2b" + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True).to(0) + +trainer = trl.SFTTrainer( + model=model, + args=args, + train_dataset=train_dataset, + dataset_text_field='text', + max_seq_length=1024, +) + +trainer.train() +``` +## تسريع ومدرب + +يتم تشغيل فئة [`Trainer`] بواسطة [تسريع](https://hf.co/docs/accelerate)، وهي مكتبة لتدريب نماذج PyTorch بسهولة في بيئات موزعة مع دعم عمليات التكامل مثل [FullyShardedDataParallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) و [DeepSpeed](https://www.deepspeed.ai/). + + + +تعرف على المزيد حول استراتيجيات تجزئة FSDP، وتفريغ وحدة المعالجة المركزية (CPU)، والمزيد مع [`Trainer`] في [دليل Fully Sharded Data Parallel](fsdp). + + + +لاستخدام Accelerate مع [`Trainer`]]، قم بتشغيل الأمر [`accelerate.config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) لإعداد التدريب لبيئة التدريب الخاصة بك. نشئ هذا الأمر ملف `config_file.yaml` الذي سيتم استخدامه عند تشغيل نص للتدريب البرمجى. على سبيل المثال، بعض تكوينات المثال التي يمكنك إعدادها هي: + + + + +```yml +compute_environment: LOCAL_MACHINE +distributed_type: MULTI_GPU +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 #change rank as per the node +main_process_ip: 192.168.20.1 +main_process_port: 9898 +main_training_function: main +mixed_precision: fp16 +num_machines: 2 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_forward_prefetch: true + fsdp_offload_params: false + fsdp_sharding_strategy: 1 + fsdp_state_dict_type: FULL_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +deepspeed_config: + deepspeed_config_file: /home/user/configs/ds_zero3_config.json + zero3_init_flag: true +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +deepspeed_config: + gradient_accumulation_steps: 1 + gradient_clipping: 0.7 + offload_optimizer_device: cpu + offload_param_device: cpu + zero3_init_flag: true + zero_stage: 2 +distributed_type: DEEPSPEED +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + + + + +```yml +compute_environment: LOCAL_MACHINE +tp_config: + tp_size: 4 +distributed_type: TP +downcast_bf16: 'no' +machine_rank: 0 +main_training_function: main +mixed_precision: 'no' +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false + +``` + + + +يُعد أمر [`accelerate_launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) هو الطريقة المُوصى بها لتشغيل نص البرمجى للتدريب على نظام موزع باستخدام Accelerate و [`Trainer`] مع المعلمات المحددة في `config_file.yaml`. يتم حفظ هذا الملف في مجلد ذاكرة التخزين المؤقت لـ Accelerate ويتم تحميله تلقائيًا عند تشغيل `accelerate_launch`. + +على سبيل المثال، لتشغيل النص البرنامجي للتدريب [run_glue.py](https://github.com/huggingface/transformers/blob/f4db565b695582891e43a5e042e5d318e28f20b8/examples/pytorch/text-classification/run_glue.py#L4) مع تكوين FSDP: + +```bash +accelerate launch \ + ./examples/pytorch/text-classification/run_glue.py \ + --model_name_or_path google-bert/bert-base-cased \ + --task_name $TASK_NAME \ + --do_train \ + --do_eval \ + --max_seq_length 128 \ + --per_device_train_batch_size 16 \ + --learning_rate 5e-5 \ + --num_train_epochs 3 \ + --output_dir /tmp/$TASK_NAME/ \ + --overwrite_output_dir +``` + +يمكنك أيضًا تحديد المعلمات من ملف `config_file.yaml` مباشرة في سطر الأوامر: + +```bash +accelerate launch --num_processes=2 \ + --use_fsdp \ + --mixed_precision=bf16 \ + --fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP \ + --fsdp_transformer_layer_cls_to_wrap="BertLayer" \ + --fsdp_sharding_strategy=1 \ + --fsdp_state_dict_type=FULL_STATE_DICT \ + ./examples/pytorch/text-classification/run_glue.py + --model_name_or_path google-bert/bert-base-cased \ + --task_name $TASK_NAME \ + --do_train \ + --do_eval \ + --max_seq_length 128 \ + --per_device_train_batch_size 16 \ + --learning_rate 5e-5 \ + --num_train_epochs 3 \ + --output_dir /tmp/$TASK_NAME/ \ + --overwrite_output_dir +``` + +اطلع على برنامج تعليمي [Launching your Accelerate scripts](https://huggingface.co/docs/accelerate/basic_tutorials/launch) لمعرفة المزيد حول `accelerate_launch` والتكوينات المخصصة. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/training.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/training.md new file mode 100644 index 0000000000000000000000000000000000000000..d3e354ff8b1af3b58a72a7a24070452ac49c5d48 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/training.md @@ -0,0 +1,412 @@ +# ضبط نموذج مُدرب مسبقًا + +هناك فوائد كبيرة لاستخدام نموذج مُدرب مسبقًا. فهو يقلل من تكاليف الحوسبة، ويحد من أثرنا البيئي، ويتيح لك استخدام أحدث النماذج دون الحاجة إلى تدريبها من الصفر. توفر مكتبة 🤗 Transformers إمكانية الوصول إلى آلاف النماذج المُدربة مسبقًا لمجموعة واسعة من المهام. عندما تستخدم نموذجًا مُدربًا مسبقًا، فإنك تقوم بتدريبه على مجموعة بيانات خاصة بمهمتك. يُعرف ذلك بالضبط الدقيق، وهي تقنية تدريب قوية للغاية. في هذا البرنامج التعليمي، سوف تقوم بضبط نموذج مُدرب مسبقًا باستخدام إطار عمل للتعلم العميق الذي تختاره: + +* ضبط نموذج مُدرب مسبقًا باستخدام 🤗 Transformers [`Trainer`]. +* ضبط نموذج مُدرب مسبقًا في TensorFlow باستخدام Keras. +* ضبط نموذج مُدرب مسبقًا في PyTorch الأصلي. + + + +## إعداد مجموعة بيانات + +قبل أن تتمكن من ضبط نموذج مُدرب مسبقًا، قم بتنزيل مجموعة بيانات وإعدادها للتدريب. أظهر البرنامج التعليمي السابق كيفية معالجة البيانات للتدريب، والآن لديك الفرصة لاختبار تلك المهارات! + +ابدأ بتحميل مجموعة بيانات [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full): + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("yelp_review_full") +>>> dataset["train"][100] +{'label': 0, + 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'} +``` + +كما تعلم الآن، تحتاج إلى محول نص إلى رمز (tokenizer) لمعالجة النص وتضمين استراتيجيات للحشو والقص للتعامل مع أي أطوال متسلسلة متغيرة. لمعالجة مجموعة البيانات الخاصة بك في خطوة واحدة، استخدم طريقة 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process#map) لتطبيق دالة معالجة مسبقة على مجموعة البيانات بأكملها: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) + + +>>> tokenized_datasets = dataset.map(tokenize_function, batched=True) +``` + +إذا كنت ترغب، يمكنك إنشاء مجموعة فرعية أصغر من مجموعة البيانات الكاملة لضبطها لتقليل الوقت الذي تستغرقه: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + + + +## التدريب + +في هذه المرحلة، يجب عليك اتباع القسم الذي يتوافق مع الإطار الذي تريد استخدامه. يمكنك استخدام الروابط +في شريط التنقل الأيمن للقفز إلى الإطار الذي تريده - وإذا كنت تريد إخفاء كل المحتوى لإطار معين، +فاستخدم الزر في الركن العلوي الأيمن من كتلة الإطار! + + + + + +## التدريب باستخدام PyTorch Trainer + +تقدم مكتبة 🤗 Transformers فئة [`Trainer`] مُحسّنة لتدريب نماذج 🤗 Transformers، مما يسهل بدء التدريب دون الحاجة إلى كتابة حلقة التدريب الخاصة بك يدويًا. تدعم واجهة برمجة تطبيقات [`Trainer`] مجموعة واسعة من خيارات التدريب والميزات مثل التسجيل، وتراكم التدرجات، والدقة المختلطة. + +ابدأ بتحميل نموذجك وتحديد عدد التصنيفات المتوقعة. من بطاقة مجموعة بيانات Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields)، تعرف أنه يوجد خمسة تصنيفات: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + + + +سترى تحذيرًا بشأن بعض أوزان النموذج المُدرب مسبقًا لن تُستخدم وبعض الأوزان الأخرى ستُبدء بشكل عشوائي. لا تقلق، هذا أمر طبيعي تمامًا! يتم التخلص من رأس النموذج المُدرب مسبقًا لشبكة BERT، ويتم استبداله برأس تصنيف يُبدء بشكل عشوائي. سوف تقوم بضبط الرأس الجديد للنموذج بدقة على مهمة تصنيف التسلسلات الخاصة بك، مما ينقل المعرفة من النموذج المُدرب مسبقًا إليه. + + + +### اختيار أحسن العوامل والمتغيرات للتدريب (Training hyperparameters) + +بعد ذلك، قم بإنشاء كائن من فئة [`TrainingArguments`] والتي تحتوي على جميع العوامل والمتغيرات التي يمكنك ضبطها بالإضافة إلى خيارات تنشيط التدريب المختلفة. بالنسبة لهذا البرنامج التعليمي، يمكنك البدء بمعاملات التدريب الافتراضية [hyperparameters](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments)، ولكن لا تتردد في تجربتها للعثور على الإعدادات المثلى. + +حدد مكان حفظ النسخ من تدريبك: + +```py +>>> from transformers import TrainingArguments + +>>> training_args = TrainingArguments(output_dir="test_trainer") +``` + +### التقييم + +لا يقوم [`Trainer`] تلقائيًا بتقييم أداء النموذج أثناء التدريب. ستحتاج إلى تمرير دالة إلى [`Trainer`] لحساب وإبلاغ المقاييس. توفر مكتبة [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) دالة [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) بسيطة يمكنك تحميلها باستخدام الدالة [`evaluate.load`] (راجع هذا [الدليل السريع](https://huggingface.co/docs/evaluate/a_quick_tour) لمزيد من المعلومات): + +```py +>>> import numpy as np +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +``` + +استدعِ دالة [`~evaluate.compute`] على `metric` لحساب دقة تنبؤاتك. قبل تمرير تنبؤاتك إلى دالة `compute`، تحتاج إلى تحويل النتائج الخام logits إلى تنبؤات نهائية (تذكر أن جميع نماذج 🤗 Transformers تعيد نتائج الخام logits): + +```py +>>> def compute_metrics(eval_pred): +... logits، labels = eval_pred +... predictions = np.argmax(logits, axis=-1) +... return metric.compute(predictions=predictions, references=labels) +``` + +إذا كنت ترغب في مراقبة مقاييس التقييم الخاصة بك أثناء الضبط الدقيق، فحدد معلمة `eval_strategy` في معاملات التدريب الخاصة بك لإظهار مقياس التقييم في نهاية كل حقبة تدريبه: + +```py +>>> from transformers import TrainingArguments, Trainer + +>>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch") +``` + +### المدرب + +قم بإنشاء كائن [`Trainer`] باستخدام نموذجك، ومعاملات التدريب، ومجموعات البيانات التدريبية والاختبارية، ودالة التقييم: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +ثم قم بضبط نموذجك عن طريق استدعاء [`~transformers.Trainer.train`]: + +```py +>>> trainer.train() +``` + + + + + + +## تدريب نموذج TensorFlow باستخدام Keras + +يمكنك أيضًا تدريب نماذج 🤗 Transformers في TensorFlow باستخدام واجهة برمجة تطبيقات Keras! + +### تحميل البيانات لـ Keras + +عندما تريد تدريب نموذج 🤗 Transformers باستخدام واجهة برمجة تطبيقات Keras، فأنت بحاجة إلى تحويل مجموعة البيانات الخاصة بك إلى تنسيق يفهمه +Keras. إذا كانت مجموعة البيانات الخاصة بك صغيرة، فيمكنك ببساطة تحويلها بالكامل إلى مصفوفات NumPy وإرسالها إلى Keras. +دعونا نجرب ذلك أولاً قبل أن نقوم بأي شيء أكثر تعقيدًا. + +أولاً، قم بتحميل مجموعة بيانات. سنستخدم مجموعة بيانات CoLA من معيار [GLUE benchmark](https://huggingface.co/datasets/glue)، +نظرًا لأنه مهمة تصنيف نص ثنائي بسيطة، وسنأخذ فقط قسم التدريب الآن. + +```py +from datasets import load_dataset + +dataset = load_dataset("glue"، "cola") +dataset = dataset ["train"] # خذ فقط قسم التدريب الآن +``` + +بعد ذلك، قم بتحميل أداة المُجزّئ اللغوي وقم بترميز البيانات كمصفوفات NumPy. لاحظ أن التصنيفات هي بالفعل قائمة من 0 و 1، +لذا يمكننا ببساطة تحويل ذلك مباشرة إلى مصفوفة NumPy بدون ترميز! + +```py +from transformers import AutoTokenizer +import numpy as np + +tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True) +# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras +tokenized_data = dict(tokenized_data) + +labels = np.array(dataset["label"]) # Label is already an array of 0 and 1 +``` + +أخيرًا، قم بتحميل وتجميع وتناسب النموذج. لاحظ أن نماذج Transformers تحتوي جميعها على دالة خسارة ذات صلة بالمهمة بشكل افتراضي، لذا فأنت لست بحاجة إلى تحديد واحدة ما لم ترغب في ذلك: + +```py +from transformers import TFAutoModelForSequenceClassification +from tensorflow.keras.optimizers import Adam + +# تحميل وتجميع النموذج الخاص بنا +model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased") +# معدلات التعلم المنخفضة أفضل غالبًا لضبط النماذج الدقيقة +model.compile(optimizer=Adam(3e-5)) # لا توجد دالة خسارة! + +model.fit(tokenized_data, labels) +``` + + + +أنت لست مضطرًا لتمرير دالة خسارة إلى نماذجك عند تجميعها! تختار نماذج Hugging Face تلقائيًا +دالة خسارة مناسبة لمهمتها وهندسة نموذجها إذا تُركت هذه الحجة فارغة. يمكنك دائمًا +تجاوز ذلك عن طريق تحديد دالة خسارة بنفسك إذا كنت تريد ذلك! + + + +يعمل هذا النهج بشكل رائع لمجموعات البيانات الصغيرة، ولكن بالنسبة لمجموعات البيانات الأكبر، فقد تجد أنه يصبح مشكلة. لماذا؟ +لأن المصفوفة المرمزة والتصنيفات يجب أن يتم تحميلها بالكامل في الذاكرة، ولأن NumPy لا يتعامل مع +المصفوفات"غير المنتظمة"، لذا حشو كل عينة إلى طول أطول عينة في مجموعة البيانات بأكملها. سيؤدي ذلك إلى زيادة حجم المصفوفة لديك، وستبطئ الرموز الزائده من عملية التدريب أيضًا! + +### تحميل البيانات كـ tf.data.Dataset + +إذا كنت تريد تجنب إبطاء التدريب، فيمكنك تحميل بياناتك كـ `tf.data.Dataset` بدلاً من ذلك. على الرغم من أنه يمكنك كتابة خط أنابيب `tf.data` الخاص بك إذا كنت تريد، إلا أن لدينا طريقتين مختصرتين للقيام بذلك: +- [`~TFPreTrainedModel.prepare_tf_dataset`]: هذه هي الطريقة التي نوصي بها في معظم الحالات. نظرًا لأنه طريقة +على نموذجك، فيمكنه فحص النموذج لتحديد الأعمدة القابلة للاستخدام كمدخلات للنموذج تلقائيًا، +واستبعاد الأعمدة الأخرى لإنشاء مجموعة بيانات أبسط وأكثر كفاءة. +- [`~datasets.Dataset.to_tf_dataset`]: هذه الطريقة أكثر أساسية، وهي مفيدة عندما تريد التحكم بدقة في كيفية +إنشاء مجموعة البيانات الخاصة بك، عن طريق تحديد أعمدة `columns` و `label_cols` المحددة التي سيتم تضمينها. + +قبل أن تتمكن من استخدام [`~TFPreTrainedModel.prepare_tf_dataset`]، ستحتاج إلى إضافة مخرجات المُجزئ إلى مجموعة البيانات الخاصة بك كأعمدة، كما هو موضح في +عينة التعليمات البرمجية التالية: + +```py +def tokenize_dataset (data): +# ستتم إضافة مفاتيح القاموس الذي تمت إعادته كأعمدة إلى مجموعة البيانات +return tokenizer(data["text"]) + + +dataset = dataset.map(tokenize_dataset) +``` + +تذكر أن مجموعات بيانات Hugging Face يتم تخزينها على القرص بشكل افتراضي، لذا فلن يؤدي ذلك إلى تضخيم استخدام الذاكرة لديك! بمجرد إضافة الأعمدة، يمكنك بث الدفعات من مجموعة البيانات وإضافة الترميز إلى كل دفعة، مما يقلل بشكل كبير من عدد رموز الترقيم مقارنة بترميز مجموعة البيانات بأكملها. + + +```py +>>> tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer) +``` + +لاحظ أنه في عينة التعليمات البرمجية أعلاه، تحتاج إلى تمرير المُجزئ اللغوي إلى `prepare_tf_dataset` حتى تتمكن من حشو الدُفعات بشكل صحيح أثناء تحميلها. +إذا كانت جميع العينات في مجموعة البيانات الخاصة بك بنفس الطول ولم يكن الترميز ضروريًا، فيمكنك تخطي هذا المعامل. +إذا كنت بحاجة إلى القيام بشيء أكثر تعقيدًا من مجرد ترميز العينات (على سبيل المثال، إفساد الرموز للنمذجة اللغوية المُقنعة)، +فيمكنك استخدام معامل `collate_fn` بدلاً من ذلك لتمرير دالة يتم استدعاؤها لتحويل +قائمة العينات إلى دفعة وتطبيق أي معالجة مسبقة تريدها. راجع أمثلةنا [examples](https://github.com/huggingface/transformers/tree/main/examples) أو +[دفاتر الملاحظات](https://huggingface.co/docs/transformers/notebooks) لرؤية هذا النهج في العمل. + +بمجرد إنشاء `tf.data.Dataset`، يمكنك تجميع النموذج وتناسبه كما هو الحال من قبل: + +```py +model.compile(optimizer=Adam(3e-5)) # No loss argument! + +model.fit(tf_dataset) +``` + + + + + +## تدريب في PyTorch الأصلي + + + + + +[`Trainer`] يهتم بحلقة التدريب ويسمح لك بضبط نموذج في سطر واحد من التعليمات البرمجية. بالنسبة للمستخدمين الذين يفضلون كتابة حلقة التدريب الخاصة بهم، يمكنك أيضًا ضبط نموذج 🤗 Transformers في PyTorch الأصلي. + +في هذه المرحلة، قد تحتاج إلى إعادة تشغيل دفتر الملاحظات الخاص بك أو تنفيذ التعليمات البرمجية التالية لتحرير بعض الذاكرة: + +```py +del model +del trainer +torch.cuda.empty_cache() +``` + +بعد ذلك، قم بمعالجة `tokenized_dataset` يدويًا لإعداده للتدريب. + +1. إزالة عمود `text` لأن النموذج لا يقبل النص الخام كإدخال: + + ```py + >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"]) + ``` + +2. إعادة تسمية عمود `label` إلى `labels` لأن النموذج يتوقع أن يكون الاسم `labels`: + + ```py + >>> tokenized_datasets = tokenized_datasets.rename_column("label"، "labels") + ``` + +3. قم بتعيين تنسيق مجموعة البيانات لإرجاع مؤشرات PyTorch بدلاً من القوائم: + + ```py + >>> tokenized_datasets.set_format("torch") + ``` + +بعد ذلك، قم بإنشاء مجموعة فرعية أصغر من مجموعة البيانات كما هو موضح سابقًا لتسريع الضبط الدقيق: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + +### DataLoader + +قم بإنشاء `DataLoader` لمجموعات بيانات التدريب والاختبار الخاصة بك حتى تتمكن من التكرار عبر دفعات البيانات: + +```py +>>> from torch.utils.data import DataLoader + +>>> train_dataloader = DataLoader(small_train_dataset، shuffle=True، batch_size=8) +>>> eval_dataloader = DataLoader(small_eval_dataset، batch_size=8) +``` + +قم بتحميل نموذجك مع عدد التصنيفات المتوقعة: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased"، num_labels=5) +``` + +### المحسن ومخطط معدل التعلم + +قم بإنشاء محسن ومخطط معدل تعلم لضبط النموذج الدقيق. دعنا نستخدم [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) المحسن من PyTorch: + +```py +>>> from torch.optim import AdamW + +>>> optimizer = AdamW(model.parameters()، lr=5e-5) +``` + +قم بإنشاء مخطط معدل التعلم الافتراضي من [`Trainer`]: + +```py +>>> from transformers import get_scheduler + +>>> num_epochs = 3 +>>> num_training_steps = num_epochs * len(train_dataloader) +>>> lr_scheduler = get_scheduler( +... name="linear"، optimizer=optimizer، num_warmup_steps=0، num_training_steps=num_training_steps +... ) +``` + +أخيرًا، حدد `device` لاستخدام وحدة معالجة الرسومات (GPU) إذا كان لديك حق الوصول إليها. وإلا، فقد يستغرق التدريب على وحدة المعالجة المركزية (CPU) عدة ساعات بدلاً من دقائق قليلة. + +```py +>>> import torch + +>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +>>> model.to(device) +``` + + + +احصل على وصول مجاني إلى وحدة معالجة رسومات سحابية إذا لم يكن لديك واحدة مع دفتر ملاحظات مستضاف مثل [Colaboratory](https://colab.research.google.com/) أو [SageMaker StudioLab](https://studiolab.sagemaker.aws/). + + + +رائع، الآن أنت مستعد للتدريب! 🥳 + +### حلقة التدريب + +لمراقبة تقدم التدريب الخاص بك، استخدم مكتبة [tqdm](https://tqdm.github.io/) لإضافة شريط تقدم فوق عدد خطوات التدريب: + +```py +>>> from tqdm.auto import tqdm + +>>> progress_bar = tqdm(range(num_training_steps)) + +>>> model.train() +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... batch = {k: v.to(device) for k، v in batch.items()} +... outputs = model(**batch) +... loss = outputs.loss +... loss.backward() + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +### تقييم + +تمامًا كما أضفت وظيفة تقييم إلى [`Trainer`]]، تحتاج إلى القيام بنفس الشيء عندما تكتب حلقة التدريب الخاصة بك. ولكن بدلاً من حساب الإبلاغ عن المقياس في نهاية كل حقبة، هذه المرة ستقوم بتجميع جميع الدفعات باستخدام [`~evaluate.add_batch`] وحساب المقياس في النهاية. + +```py +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +>>> model.eval() +>>> for batch in eval_dataloader: +... batch = {k: v.to(device) for k، v in batch.items()} +... with torch.no_grad(): +... outputs = model(**batch) + +... logits = outputs.logits +... predictions = torch.argmax(logits، dim=-1) +... metric.add_batch(predictions=predictions، references=batch["labels"]) + +>>> metric.compute() +``` + + + + + +## موارد إضافية + +لمزيد من الأمثلة على الضبط الدقيق، راجع: + +- [🤗 أمثلة المحولات](https://github.com/huggingface/transformers/tree/main/examples) تتضمن + النصوص البرمجية لتدريب مهام NLP الشائعة في PyTorch وTensorFlow. + +- [🤗 دفاتر ملاحظات المحولات](notebooks) يحتوي على دفاتر ملاحظات مختلفة حول كيفية ضبط نموذج لمهمة محددة في PyTorch وTensorFlow. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/troubleshooting.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..7874a9fad13304a859967b79d9117da8dc34a545 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/ar/troubleshooting.md @@ -0,0 +1,171 @@ +# استكشاف الأخطاء وإصلاحها + +تحدث الأخطاء أحيانًا، لكننا هنا للمساعدة! يغطي هذا الدليل بعض المشكلات الأكثر شيوعًا التي واجهناها وكيفية حلها. مع ذلك، لا يُقصد بهذا الدليل أن يكون مجموعة شاملة لكل مشكلات 🤗 Transformers. لمزيد من المساعدة في استكشاف مشكلتك وإصلاحها، جرب ما يلي: + + + +1. اطلب المساعدة على [المنتديات](https://discuss.huggingface.co/). هناك فئات محددة يمكنك نشر سؤالك فيها، مثل [المبتدئين](https://discuss.huggingface.co/c/beginners/5) أو [🤗 Transformers](https://discuss.huggingface.co/c/transformers/9). تأكد من كتابة منشور جيد وواضح على المنتدى مع بعض التعليمات البرمجية القابلة للتكرار لزيادة احتمالية حل مشكلتك! + + +2. قم بإنشاء [مشكلة](https://github.com/huggingface/transformers/issues/new/choose) في مستودع 🤗 Transformers إذا كانت هناك مشكلة متعلقة بالمكتبة. حاول تضمين أكبر قدر ممكن من المعلومات التي تصف المشكلة لمساعدتنا في معرفة ما هو الخطأ وكيفية إصلاحه. + +3. تحقق من دليل [الترحيل](migration) إذا كنت تستخدم إصدارًا أقدم من مكتبة 🤗 Transformers حيث تم إدخال بعض التغييرات المهمة بين الإصدارات. + + +للحصول على مزيد من التفاصيل حول استكشاف الأخطاء وإصلاحها والحصول على المساعدة، راجع [الفصل 8](https://huggingface.co/course/chapter8/1?fw=pt) من دورة Hugging Face. + +## بيئات جدار الحماية + +بعض وحدات معالجة الرسومات (GPU) على السحابة وإعدادات الشبكة الداخلية محمية بجدار حماية من الاتصالات الخارجية، مما يؤدي إلى حدوث خطأ في الاتصال. عندما تحاول تعليمات البرنامج النصي تنزيل أوزان النموذج أو مجموعات البيانات، سيتوقف التنزيل ثم ينتهي بخطأ مثل: + +``` +ValueError: Connection error, and we cannot find the requested files in the cached path. +Please try again or make sure your Internet connection is on. +``` + +في هذه الحالة، يجب محاولة تشغيل 🤗 Transformers في [وضع عدم الاتصال](installation#offline-mode) لتجنب خطأ الاتصال. + +## CUDA نفاد الذاكرة + +يمكن أن يكون تدريب النماذج الكبيرة التي تحتوي على ملايين المعلمات أمرًا صعبًا بدون الأجهزة المناسبة. أحد الأخطاء الشائعة التي قد تواجهها عند نفاد ذاكرة GPU هو: + +``` +CUDA out of memory. Tried to allocate 256.00 MiB (GPU 0; 11.17 GiB total capacity; 9.70 GiB already allocated; 179.81 MiB free; 9.85 GiB reserved in total by PyTorch) +``` + +فيما يلي بعض الحلول المحتملة التي يمكنك تجربتها لتقليل استخدام الذاكرة: + +- قلل من قيمة [`per_device_train_batch_size`](main_classes/trainer#transformers.TrainingArguments.per_device_train_batch_size) في [`TrainingArguments`]. + +- حاول استخدام [`gradient_accumulation_steps`](main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps) في [`TrainingArguments`] لزيادة حجم الدُفعة بشكل فعال. + + +راجع دليل [الأداء](performance) لمزيد من التفاصيل حول تقنيات توفير الذاكرة. + + +## عدم القدرة على تحميل نموذج TensorFlow محفوظ + +تقوم طريقة TensorFlow [model.save](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) بحفظ النموذج بالكامل - الهندسة المعمارية، الأوزان، تكوين التدريب - في ملف واحد. ومع ذلك، عند تحميل ملف النموذج مرة أخرى، قد تواجه خطأ لأن مكتبة 🤗 Transformers قد لا تقوم بتحميل جميع الكائنات المتعلقة بـ TensorFlow في ملف النموذج. لتجنب المشكلات المتعلقة بحفظ وتحميل نماذج TensorFlow، نوصي بما يلي: + +- احفظ أوزان النموذج كملف `h5` باستخدام [`model.save_weights`](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) ثم أعد تحميل النموذج باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```python +>>> from transformers import TFPreTrainedModel +>>> from tensorflow import keras + +>>> model.save_weights("some_folder/tf_model.h5") +>>> model = TFPreTrainedModel.from_pretrained("some_folder") +``` + +- احفظ النموذج باستخدام [`~TFPretrainedModel.save_pretrained`] وقم بتحميله مرة أخرى باستخدام [`~TFPreTrainedModel.from_pretrained`]: + +```python +>>> from transformers import TFPreTrainedModel + +>>> model.save_pretrained("path_to/model") +>>> model = TFPreTrainedModel.from_pretrained("path_to/model") +``` + +## ImportError + +خطأ شائع آخر قد تواجهه، خاصة إذا كان نموذجًا تم إصداره حديثًا، هو `ImportError`: + +``` +ImportError: cannot import name 'ImageGPTImageProcessor' from 'transformers' (unknown location) +``` + +بالنسبة لأنواع الأخطاء هذه، تحقق من أن لديك أحدث إصدار من مكتبة Hugging Face Transformers مثبتًا للوصول إلى أحدث النماذج: + +```bash +pip install transformers --upgrade +``` + +## خطأ CUDA: تم تشغيل التأكيد على جانب الجهاز + +في بعض الأحيان، قد تواجه خطأ CUDA عامًا حول خطأ في كود الجهاز. + +``` +RuntimeError: CUDA error: device-side assert triggered +``` + +يجب عليك محاولة تشغيل الكود على وحدة المعالجة المركزية (CPU) أولاً للحصول على رسالة خطأ أكثر دقة. أضف متغير البيئة التالي في بداية كودك للتبديل إلى وحدة المعالجة المركزية: + +```python +>>> import os + +>>> os.environ["CUDA_VISIBLE_DEVICES"] = "" +``` + +الخيار الآخر هو الحصول على تتبع مكدس أفضل من GPU. أضف متغير البيئة التالي في بداية كودك للحصول على تتبع المكدس للإشارة إلى مصدر الخطأ: + +```python +>>> import os + +>>> os.environ["CUDA_LAUNCH_BLOCKING"] = "1" +``` + +## إخراج غير صحيح عند عدم إخفاء رموز الحشو + +في بعض الحالات، قد يكون `hidden_state` غير صحيحة إذا تضمنت `input_ids` رموز حشو. ولإثبات ذلك، قم بتحميل نموذج ومجزىء لغوى. يمكنك الوصول إلى `pad_token_id` للنموذج لمعرفة قيمته. قد تكون `pad_token_id` `None` لبعض النماذج، ولكن يمكنك دائمًا تعيينها يدويًا. + +```python +>>> from transformers import AutoModelForSequenceClassification +>>> import torch + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-uncased") +>>> model.config.pad_token_id +0 +``` + +يوضح المثال التالي المُخرجات بدون إخفاء رموز الحشو: + +```python +>>> input_ids = torch.tensor([[7592, 2057, 2097, 2393, 9611, 2115], [7592, 0, 0, 0, 0, 0]]) +>>> output = model(input_ids) +>>> print(output.logits) +tensor([[ 0.0082, -0.2307], +[ 0.1317, -0.1683]], grad_fn=) +``` + +هنا المُخرجات الفعلية للتسلسل الثاني: + +```python +>>> input_ids = torch.tensor([[7592]]) +>>> output = model(input_ids) +>>> print(output.logits) +tensor([[-0.1008, -0.4061]], grad_fn=) +``` + +يجب عليك في معظم الوقت توفير `attention_mask` للنموذج لتجاهل رموز الحشو لتجنب هذا الخطأ الصامت. الآن يتطابق مُخرجات التسلسل الثاني مع مُخرجاته الفعلية: + + +بشكل افتراضي، ينشئ مجزىء النصوص `attention_mask` لك استنادًا إلى إعدادات المجزىء المحدد. + + +```python +>>> attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]]) +>>> output = model(input_ids, attention_mask=attention_mask) +>>> print(output.logits) +tensor([[ 0.0082, -0.2307], +[-0.1008, -0.4061]], grad_fn=) +``` + +لا ينشئ 🤗 Transformers تلقائيًا `attention_mask` لإخفاء رمز الحشو إذا تم توفيره لأن: + +- بعض النماذج ليس لها رمز حشو. + +- بالنسبة لبعض الاستخدامات، يريد المستخدمون أن ينتبه النموذج إلى رمز الحشو. +## ValueError: فئة التكوين غير المعترف بها XYZ لهذا النوع من AutoModel + +بشكل عام، نوصي باستخدام فئة [`AutoModel`] لتحميل النسخ المدربة مسبقًا من النماذج. يمكن لهذه الفئة أن تستنتج وتُحمل تلقائيًا البنية الصحيحة من نسخ معينة بناءً على التكوين. إذا رأيت هذا الخطأ `ValueError` عند تحميل نموذج من نسخة، فهذا يعني أن الفئة التلقائية (Auto) لم تتمكن من العثور على خريطة من التكوين في نقطة التفتيش المعطاة إلى نوع النموذج الذي تُحاول تحميله. وغالبًا ما يحدث هذا عندما لا تدعم نقطة التفتيش مهمة معينة. + +على سبيل المثال، سترى هذا الخطأ في المثال التالي لأنه لا يوجد GPT2 للإجابة على الأسئلة: + +```py +>>> from transformers import AutoProcessor, AutoModelForQuestionAnswering + +>>> processor = AutoProcessor.from_pretrained("openai-community/gpt2-medium") +>>> model = AutoModelForQuestionAnswering.from_pretrained("openai-community/gpt2-medium") +ValueError: Unrecognized configuration class for this kind of AutoModel: AutoModelForQuestionAnswering. +Model type should be one of AlbertConfig, BartConfig, BertConfig, BigBirdConfig, BigBirdPegasusConfig, BloomConfig, ... +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_config.py b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_toctree.yml b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..859c4b7b3b30102766dd846788c339e9379ec07f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/_toctree.yml @@ -0,0 +1,42 @@ +- sections: + - local: index + title: 🤗 Transformers + - local: quicktour + title: Schnellstart + - local: installation + title: Installation + title: Erste Schritte +- sections: + - local: pipeline_tutorial + title: Pipelines für Inferenzen + - local: autoclass_tutorial + title: Laden von vortrainierten Instanzen mit einer AutoClass + - local: preprocessing + title: Vorverarbeiten + - local: training + title: Optimierung eines vortrainierten Modells + - local: run_scripts + title: Trainieren mit einem Skript + - local: accelerate + title: Verteiltes Training mit 🤗 Accelerate + - local: peft + title: Laden und Trainieren von Adaptern mit 🤗 PEFT + - local: model_sharing + title: Ein Modell teilen + - local: transformers_agents + title: Agents + - local: llm_tutorial + title: Generation with LLMs + title: Tutorials +- sections: + - local: contributing + title: Wie kann man zu 🤗 Transformers beitragen? + - local: add_new_model + title: Wie fügt man ein Modell zu 🤗 Transformers hinzu? + - local: add_new_pipeline + title: Wie fügt man eine Pipeline zu 🤗 Transformers hinzu? + - local: testing + title: Testen + - local: pr_checks + title: Überprüfung einer Pull Request + title: Contribute \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/accelerate.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..98a11cbdc4177170fd5b02c29fc19b36ebf259cb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/accelerate.md @@ -0,0 +1,136 @@ + + +# Verteiltes Training mit 🤗 Accelerate + +Da die Modelle immer größer werden, hat sich die Parallelität als Strategie zum Trainieren größerer Modelle auf begrenzter Hardware und zur Beschleunigung der Trainingsgeschwindigkeit um mehrere Größenordnungen erwiesen. Bei Hugging Face haben wir die Bibliothek [🤗 Accelerate](https://huggingface.co/docs/accelerate) entwickelt, um Nutzern zu helfen, ein 🤗 Transformers-Modell auf jeder Art von verteiltem Setup zu trainieren, egal ob es sich um mehrere GPUs auf einer Maschine oder mehrere GPUs auf mehreren Maschinen handelt. In diesem Tutorial lernen Sie, wie Sie Ihre native PyTorch-Trainingsschleife anpassen, um das Training in einer verteilten Umgebung zu ermöglichen. + +## Einrichtung + +Beginnen Sie mit der Installation von 🤗 Accelerate: + +```bash +pip install accelerate +``` + +Dann importieren und erstellen Sie ein [`~accelerate.Accelerator`]-Objekt. Der [`~accelerate.Accelerator`] wird automatisch Ihre Art der verteilten Einrichtung erkennen und alle notwendigen Komponenten für das Training initialisieren. Sie müssen Ihr Modell nicht explizit auf einem Gerät platzieren. + +```py +>>> from accelerate import Accelerator + +>>> accelerator = Accelerator() +``` + +## Vorbereiten auf die Beschleunigung + +Der nächste Schritt ist die Übergabe aller relevanten Trainingsobjekte an die Methode [`~accelerate.Accelerator.prepare`]. Dazu gehören Ihre Trainings- und Evaluierungs-DataLoader, ein Modell und ein Optimierer: + +```py +>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( +... train_dataloader, eval_dataloader, model, optimizer +... ) +``` + +## Rückwärts + +Die letzte Ergänzung besteht darin, das typische `loss.backward()` in der Trainingsschleife durch die 🤗 Accelerate-Methode [`~accelerate.Accelerator.backward`] zu ersetzen: + +```py +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... outputs = model(**batch) +... loss = outputs.loss +... accelerator.backward(loss) + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +Wie Sie im folgenden Code sehen können, müssen Sie nur vier zusätzliche Codezeilen zu Ihrer Trainingsschleife hinzufügen, um verteiltes Training zu ermöglichen! + +```diff ++ from accelerate import Accelerator + from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler + ++ accelerator = Accelerator() + + model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) + optimizer = AdamW(model.parameters(), lr=3e-5) + +- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +- model.to(device) + ++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ++ train_dataloader, eval_dataloader, model, optimizer ++ ) + + num_epochs = 3 + num_training_steps = num_epochs * len(train_dataloader) + lr_scheduler = get_scheduler( + "linear", + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=num_training_steps + ) + + progress_bar = tqdm(range(num_training_steps)) + + model.train() + for epoch in range(num_epochs): + for batch in train_dataloader: +- batch = {k: v.to(device) for k, v in batch.items()} + outputs = model(**batch) + loss = outputs.loss +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +## Trainieren + +Sobald Sie die entsprechenden Codezeilen hinzugefügt haben, starten Sie Ihr Training in einem Skript oder einem Notebook wie Colaboratory. + +### Trainieren mit einem Skript + +Wenn Sie Ihr Training mit einem Skript durchführen, führen Sie den folgenden Befehl aus, um eine Konfigurationsdatei zu erstellen und zu speichern: + +```bash +accelerate config +``` + +Dann starten Sie Ihr Training mit: + +```bash +accelerate launch train.py +``` + +### Trainieren mit einem Notebook + +🤗 Accelerate kann auch in einem Notebook laufen, wenn Sie planen, die TPUs von Colaboratory zu verwenden. Verpacken Sie den gesamten Code, der für das Training verantwortlich ist, in eine Funktion und übergeben Sie diese an [`~accelerate.notebook_launcher`]: + +```py +>>> from accelerate import notebook_launcher + +>>> notebook_launcher(training_function) +``` + +Weitere Informationen über 🤗 Accelerate und seine umfangreichen Funktionen finden Sie in der [Dokumentation](https://huggingface.co/docs/accelerate). \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_model.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..3c8987f44254bc1acc59396d1d282781c7d6126e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_model.md @@ -0,0 +1,891 @@ + + +# Wie kann ich ein Modell zu 🤗 Transformers hinzufügen? + +Die 🤗 Transformers-Bibliothek ist dank der Beiträge der Community oft in der Lage, neue Modelle anzubieten. Aber das kann ein anspruchsvolles Projekt sein und erfordert eine eingehende Kenntnis der 🤗 Transformers-Bibliothek und des zu implementierenden Modells. Bei Hugging Face versuchen wir, mehr Mitgliedern der Community die Möglichkeit zu geben, aktiv Modelle hinzuzufügen, und wir haben diese Anleitung zusammengestellt, die Sie durch den Prozess des Hinzufügens eines PyTorch-Modells führt (stellen Sie sicher, dass Sie [PyTorch installiert haben](https://pytorch.org/get-started/locally/)). + +Auf dem Weg dorthin, werden Sie: + +- Einblicke in bewährte Open-Source-Verfahren erhalten +- die Konstruktionsprinzipien hinter einer der beliebtesten Deep-Learning-Bibliotheken verstehen +- lernen Sie, wie Sie große Modelle effizient testen können +- lernen Sie, wie Sie Python-Hilfsprogramme wie `black`, `ruff` und `make fix-copies` integrieren, um sauberen und lesbaren Code zu gewährleisten + +Ein Mitglied des Hugging Face-Teams wird Ihnen dabei zur Seite stehen, damit Sie nicht alleine sind. 🤗 ❤️ + +Um loszulegen, öffnen Sie eine [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) Ausgabe für das Modell, das Sie in 🤗 Transformers sehen möchten. Wenn Sie nicht besonders wählerisch sind, wenn es darum geht, ein bestimmtes Modell beizusteuern, können Sie nach dem [New model label](https://github.com/huggingface/transformers/labels/New%20model) filtern, um zu sehen, ob es noch unbeanspruchte Modellanfragen gibt, und daran arbeiten. + +Sobald Sie eine neue Modellanfrage eröffnet haben, sollten Sie sich zunächst mit 🤗 Transformers vertraut machen, falls Sie das noch nicht sind! + +## Allgemeiner Überblick über 🤗 Transformers + +Zunächst sollten Sie sich einen allgemeinen Überblick über 🤗 Transformers verschaffen. 🤗 Transformers ist eine sehr meinungsfreudige Bibliothek, es ist also möglich, dass +Es besteht also die Möglichkeit, dass Sie mit einigen der Philosophien oder Designentscheidungen der Bibliothek nicht einverstanden sind. Aus unserer Erfahrung heraus haben wir jedoch +dass die grundlegenden Designentscheidungen und Philosophien der Bibliothek entscheidend sind, um 🤗 Transformers effizient zu skalieren. +Transformatoren zu skalieren und gleichzeitig die Wartungskosten auf einem vernünftigen Niveau zu halten. + +Ein guter erster Ansatzpunkt, um die Bibliothek besser zu verstehen, ist die Lektüre der [Dokumentation unserer Philosophie](Philosophie). Als Ergebnis unserer Arbeitsweise gibt es einige Entscheidungen, die wir versuchen, auf alle Modelle anzuwenden: + +- Komposition wird im Allgemeinen gegenüber Abstraktion bevorzugt +- Die Duplizierung von Code ist nicht immer schlecht, wenn sie die Lesbarkeit oder Zugänglichkeit eines Modells stark verbessert +- Modelldateien sind so in sich geschlossen wie möglich, so dass Sie, wenn Sie den Code eines bestimmten Modells lesen, idealerweise nur + in die entsprechende Datei `modeling_....py` schauen müssen. + +Unserer Meinung nach ist der Code der Bibliothek nicht nur ein Mittel, um ein Produkt bereitzustellen, *z.B.* die Möglichkeit, BERT für +Inferenz zu verwenden, sondern auch als das Produkt selbst, das wir verbessern wollen. Wenn Sie also ein Modell hinzufügen, ist der Benutzer nicht nur die +Person, die Ihr Modell verwenden wird, sondern auch jeder, der Ihren Code liest, zu verstehen versucht und ihn möglicherweise verbessert. + +Lassen Sie uns daher ein wenig tiefer in das allgemeine Design der Bibliothek einsteigen. + +### Überblick über die Modelle + +Um ein Modell erfolgreich hinzuzufügen, ist es wichtig, die Interaktion zwischen Ihrem Modell und seiner Konfiguration zu verstehen, +[`PreTrainedModel`] und [`PretrainedConfig`]. Als Beispiel werden wir +das Modell, das zu 🤗 Transformers hinzugefügt werden soll, `BrandNewBert` nennen. + +Schauen wir uns das mal an: + + + +Wie Sie sehen, machen wir in 🤗 Transformers von der Vererbung Gebrauch, aber wir beschränken die Abstraktionsebene auf ein absolutes Minimum. +Minimum. Es gibt nie mehr als zwei Abstraktionsebenen für ein Modell in der Bibliothek. `BrandNewBertModel` +erbt von `BrandNewBertPreTrainedModel`, das wiederum von [`PreTrainedModel`] erbt und +das war's. In der Regel wollen wir sicherstellen, dass ein neues Modell nur von +[`PreTrainedModel`] abhängt. Die wichtigen Funktionalitäten, die jedem neuen Modell automatisch zur Verfügung gestellt werden, sind +Modell automatisch bereitgestellt werden, sind [`~PreTrainedModel.from_pretrained`] und +[`~PreTrainedModel.save_pretrained`], die für die Serialisierung und Deserialisierung verwendet werden. Alle +anderen wichtigen Funktionalitäten, wie `BrandNewBertModel.forward` sollten vollständig in der neuen +Skript `modeling_brand_new_bert.py` definiert werden. Als nächstes wollen wir sicherstellen, dass ein Modell mit einer bestimmten Kopfebene, wie z.B. +`BrandNewBertForMaskedLM` nicht von `BrandNewBertModel` erbt, sondern `BrandNewBertModel` verwendet +als Komponente, die im Forward Pass aufgerufen werden kann, um die Abstraktionsebene niedrig zu halten. Jedes neue Modell erfordert eine +Konfigurationsklasse, genannt `BrandNewBertConfig`. Diese Konfiguration wird immer als ein Attribut in +[PreTrainedModel] gespeichert und kann daher über das Attribut `config` für alle Klassen aufgerufen werden +die von `BrandNewBertPreTrainedModel` erben: + +```python +model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert") +model.config # model has access to its config +``` + +Ähnlich wie das Modell erbt die Konfiguration grundlegende Serialisierungs- und Deserialisierungsfunktionalitäten von +[`PretrainedConfig`]. Beachten Sie, dass die Konfiguration und das Modell immer in zwei verschiedene Formate serialisiert werden +unterschiedliche Formate serialisiert werden - das Modell in eine *pytorch_model.bin* Datei und die Konfiguration in eine *config.json* Datei. Aufruf von +[`~PreTrainedModel.save_pretrained`] wird automatisch +[`~PretrainedConfig.save_pretrained`] auf, so dass sowohl das Modell als auch die Konfiguration gespeichert werden. + + +### Code-Stil + +Wenn Sie Ihr neues Modell kodieren, sollten Sie daran denken, dass Transformers eine Bibliothek mit vielen Meinungen ist und dass wir selbst ein paar Macken haben +wie der Code geschrieben werden sollte :-) + +1. Der Vorwärtsdurchlauf Ihres Modells sollte vollständig in die Modellierungsdatei geschrieben werden und dabei völlig unabhängig von anderen + Modellen in der Bibliothek. Wenn Sie einen Block aus einem anderen Modell wiederverwenden möchten, kopieren Sie den Code und fügen ihn mit einem + `# Kopiert von` ein (siehe [hier](https://github.com/huggingface/transformers/blob/v4.17.0/src/transformers/models/roberta/modeling_roberta.py#L160) + für ein gutes Beispiel und [hier](pr_checks#check-copies) für weitere Dokumentation zu Copied from). +2. Der Code sollte vollständig verständlich sein, auch für einen Nicht-Muttersprachler. Das heißt, Sie sollten + beschreibende Variablennamen wählen und Abkürzungen vermeiden. Ein Beispiel: `activation` ist `act` vorzuziehen. + Von Variablennamen mit nur einem Buchstaben wird dringend abgeraten, es sei denn, es handelt sich um einen Index in einer for-Schleife. +3. Generell ziehen wir längeren expliziten Code einem kurzen magischen Code vor. +4. Vermeiden Sie die Unterklassifizierung von `nn.Sequential` in PyTorch, sondern unterklassifizieren Sie `nn.Module` und schreiben Sie den Vorwärtspass, so dass jeder + so dass jeder, der Ihren Code verwendet, ihn schnell debuggen kann, indem er Druckanweisungen oder Haltepunkte hinzufügt. +5. Ihre Funktionssignatur sollte mit einer Typ-Annotation versehen sein. Im Übrigen sind gute Variablennamen viel lesbarer und verständlicher + verständlicher als Typ-Anmerkungen. + +### Übersicht der Tokenizer + +Noch nicht ganz fertig :-( Dieser Abschnitt wird bald hinzugefügt! + +## Schritt-für-Schritt-Rezept zum Hinzufügen eines Modells zu 🤗 Transformers + +Jeder hat andere Vorlieben, was die Portierung eines Modells angeht. Daher kann es sehr hilfreich sein, wenn Sie sich Zusammenfassungen ansehen +wie andere Mitwirkende Modelle auf Hugging Face portiert haben. Hier ist eine Liste von Blogbeiträgen aus der Community, wie man ein Modell portiert: + +1. [Portierung eines GPT2-Modells](https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28) von [Thomas](https://huggingface.co/thomwolf) +2. [Portierung des WMT19 MT-Modells](https://huggingface.co/blog/porting-fsmt) von [Stas](https://huggingface.co/stas) + +Aus Erfahrung können wir Ihnen sagen, dass die wichtigsten Dinge, die Sie beim Hinzufügen eines Modells beachten müssen, sind: + +- Erfinden Sie das Rad nicht neu! Die meisten Teile des Codes, den Sie für das neue 🤗 Transformers-Modell hinzufügen werden, existieren bereits + irgendwo in 🤗 Transformers. Nehmen Sie sich etwas Zeit, um ähnliche, bereits vorhandene Modelle und Tokenizer zu finden, die Sie kopieren können + von. [grep](https://www.gnu.org/software/grep/) und [rg](https://github.com/BurntSushi/ripgrep) sind Ihre + Freunde. Beachten Sie, dass es sehr gut möglich ist, dass der Tokenizer Ihres Modells auf einer Modellimplementierung basiert und + und der Modellierungscode Ihres Modells auf einer anderen. *Z.B.* Der Modellierungscode von FSMT basiert auf BART, während der Tokenizer-Code von FSMT + auf XLM basiert. +- Es handelt sich eher um eine technische als um eine wissenschaftliche Herausforderung. Sie sollten mehr Zeit auf die Schaffung einer + eine effiziente Debugging-Umgebung zu schaffen, als zu versuchen, alle theoretischen Aspekte des Modells in dem Papier zu verstehen. +- Bitten Sie um Hilfe, wenn Sie nicht weiterkommen! Modelle sind der Kernbestandteil von 🤗 Transformers, so dass wir bei Hugging Face mehr als + mehr als glücklich, Ihnen bei jedem Schritt zu helfen, um Ihr Modell hinzuzufügen. Zögern Sie nicht zu fragen, wenn Sie merken, dass Sie nicht weiterkommen. + Fortschritte machen. + +Im Folgenden versuchen wir, Ihnen ein allgemeines Rezept an die Hand zu geben, das uns bei der Portierung eines Modells auf 🤗 Transformers am nützlichsten erschien. + +Die folgende Liste ist eine Zusammenfassung all dessen, was getan werden muss, um ein Modell hinzuzufügen und kann von Ihnen als To-Do verwendet werden +Liste verwenden: + +☐ (Optional) Verstehen der theoretischen Aspekte des Modells
+☐ Vorbereiten der 🤗 Transformers-Entwicklungsumgebung
+☐ Debugging-Umgebung des ursprünglichen Repositorys eingerichtet
+☐ Skript erstellt, das den Durchlauf `forward()` unter Verwendung des ursprünglichen Repositorys und des Checkpoints erfolgreich durchführt
+☐ Erfolgreich das Modellskelett zu 🤗 Transformers hinzugefügt
+☐ Erfolgreiche Umwandlung des ursprünglichen Prüfpunkts in den 🤗 Transformers-Prüfpunkt
+☐ Erfolgreich den Durchlauf `forward()` in 🤗 Transformers ausgeführt, der eine identische Ausgabe wie der ursprüngliche Prüfpunkt liefert
+☐ Modell-Tests in 🤗 Transformers abgeschlossen
+☐ Erfolgreich Tokenizer in 🤗 Transformers hinzugefügt
+☐ End-to-End-Integrationstests ausgeführt
+☐ Docs fertiggestellt
+☐ Modellgewichte in den Hub hochgeladen
+☐ Die Pull-Anfrage eingereicht
+☐ (Optional) Hinzufügen eines Demo-Notizbuchs + +Für den Anfang empfehlen wir in der Regel, mit einem guten theoretischen Verständnis von `BrandNewBert` zu beginnen. Wie auch immer, +wenn Sie es vorziehen, die theoretischen Aspekte des Modells *on-the-job* zu verstehen, dann ist es völlig in Ordnung, direkt in die +in die Code-Basis von `BrandNewBert` einzutauchen. Diese Option könnte für Sie besser geeignet sein, wenn Ihre technischen Fähigkeiten besser sind als +als Ihre theoretischen Fähigkeiten, wenn Sie Schwierigkeiten haben, die Arbeit von `BrandNewBert` zu verstehen, oder wenn Sie einfach Spaß am Programmieren +mehr Spaß am Programmieren haben als am Lesen wissenschaftlicher Abhandlungen. + +### 1. (Optional) Theoretische Aspekte von BrandNewBert + +Sie sollten sich etwas Zeit nehmen, um die Abhandlung von *BrandNewBert* zu lesen, falls eine solche Beschreibung existiert. Möglicherweise gibt es große +Abschnitte des Papiers, die schwer zu verstehen sind. Wenn das der Fall ist, ist das in Ordnung - machen Sie sich keine Sorgen! Das Ziel ist +ist es nicht, ein tiefes theoretisches Verständnis des Papiers zu erlangen, sondern die notwendigen Informationen zu extrahieren, um +das Modell effektiv in 🤗 Transformers zu implementieren. Das heißt, Sie müssen nicht zu viel Zeit auf die +theoretischen Aspekten verbringen, sondern sich lieber auf die praktischen Aspekte konzentrieren, nämlich: + +- Welche Art von Modell ist *brand_new_bert*? BERT-ähnliches Modell nur für den Encoder? GPT2-ähnliches reines Decoder-Modell? BART-ähnliches + Encoder-Decoder-Modell? Sehen Sie sich die [model_summary](model_summary) an, wenn Sie mit den Unterschieden zwischen diesen Modellen nicht vertraut sind. +- Was sind die Anwendungen von *brand_new_bert*? Textklassifizierung? Texterzeugung? Seq2Seq-Aufgaben, *z.B.,* + Zusammenfassungen? +- Was ist die neue Eigenschaft des Modells, die es von BERT/GPT-2/BART unterscheidet? +- Welches der bereits existierenden [🤗 Transformers-Modelle](https://huggingface.co/transformers/#contents) ist am ähnlichsten + ähnlich wie *brand_new_bert*? +- Welche Art von Tokenizer wird verwendet? Ein Satzteil-Tokenisierer? Ein Wortstück-Tokenisierer? Ist es derselbe Tokenisierer, der für + für BERT oder BART? + +Nachdem Sie das Gefühl haben, einen guten Überblick über die Architektur des Modells erhalten zu haben, können Sie dem +Hugging Face Team schreiben und Ihre Fragen stellen. Dazu können Fragen zur Architektur des Modells gehören, +seiner Aufmerksamkeitsebene usw. Wir werden Ihnen gerne weiterhelfen. + +### 2. Bereiten Sie als nächstes Ihre Umgebung vor + +1. Forken Sie das [Repository](https://github.com/huggingface/transformers), indem Sie auf der Seite des Repositorys auf die Schaltfläche 'Fork' klicken. + Seite des Repositorys klicken. Dadurch wird eine Kopie des Codes unter Ihrem GitHub-Benutzerkonto erstellt. + +2. Klonen Sie Ihren `transformers` Fork auf Ihre lokale Festplatte und fügen Sie das Basis-Repository als Remote hinzu: + +```bash +git clone https://github.com/[your Github handle]/transformers.git +cd transformers +git remote add upstream https://github.com/huggingface/transformers.git +``` + +3. Richten Sie eine Entwicklungsumgebung ein, indem Sie z.B. den folgenden Befehl ausführen: + +```bash +python -m venv .env +source .env/bin/activate +pip install -e ".[dev]" +``` + +Abhängig von Ihrem Betriebssystem und da die Anzahl der optionalen Abhängigkeiten von Transformers wächst, kann es sein, dass Sie bei diesem Befehl einen +Fehler mit diesem Befehl. Stellen Sie in diesem Fall sicher, dass Sie das Deep Learning Framework, mit dem Sie arbeiten, installieren +(PyTorch, TensorFlow und/oder Flax) und führen Sie es aus: + +```bash +pip install -e ".[quality]" +``` + +was für die meisten Anwendungsfälle ausreichend sein sollte. Sie können dann zum übergeordneten Verzeichnis zurückkehren + +```bash +cd .. +``` + +4. Wir empfehlen, die PyTorch-Version von *brand_new_bert* zu Transformers hinzuzufügen. Um PyTorch zu installieren, folgen Sie bitte den + Anweisungen auf https://pytorch.org/get-started/locally/. + +**Anmerkung:** Sie müssen CUDA nicht installiert haben. Es reicht aus, das neue Modell auf der CPU zum Laufen zu bringen. + +5. Um *brand_new_bert* zu portieren, benötigen Sie außerdem Zugriff auf das Original-Repository: + +```bash +git clone https://github.com/org_that_created_brand_new_bert_org/brand_new_bert.git +cd brand_new_bert +pip install -e . +``` + +Jetzt haben Sie eine Entwicklungsumgebung eingerichtet, um *brand_new_bert* auf 🤗 Transformers zu portieren. + +### 3.-4. Führen Sie einen Pre-Training-Checkpoint mit dem Original-Repository durch + +Zunächst werden Sie mit dem ursprünglichen *brand_new_bert* Repository arbeiten. Oft ist die ursprüngliche Implementierung sehr +"forschungslastig". Das bedeutet, dass es an Dokumentation mangeln kann und der Code schwer zu verstehen sein kann. Aber das sollte +genau Ihre Motivation sein, *brand_new_bert* neu zu implementieren. Eines unserer Hauptziele bei Hugging Face ist es, *die Menschen dazu zu bringen +auf den Schultern von Giganten zu stehen*, was sich hier sehr gut darin ausdrückt, dass wir ein funktionierendes Modell nehmen und es umschreiben, um es so +es so **zugänglich, benutzerfreundlich und schön** wie möglich zu machen. Dies ist die wichtigste Motivation für die Neuimplementierung von +Modelle in 🤗 Transformers umzuwandeln - der Versuch, komplexe neue NLP-Technologie für **jeden** zugänglich zu machen. + +Sie sollten damit beginnen, indem Sie in das Original-Repository eintauchen. + +Die erfolgreiche Ausführung des offiziellen Pre-Trainingsmodells im Original-Repository ist oft **der schwierigste** Schritt. +Unserer Erfahrung nach ist es sehr wichtig, dass Sie einige Zeit damit verbringen, sich mit der ursprünglichen Code-Basis vertraut zu machen. Sie müssen +das Folgende herausfinden: + +- Wo finden Sie die vortrainierten Gewichte? +- Wie lädt man die vorab trainierten Gewichte in das entsprechende Modell? +- Wie kann der Tokenizer unabhängig vom Modell ausgeführt werden? +- Verfolgen Sie einen Forward Pass, damit Sie wissen, welche Klassen und Funktionen für einen einfachen Forward Pass erforderlich sind. Normalerweise, + müssen Sie nur diese Funktionen reimplementieren. +- Sie müssen in der Lage sein, die wichtigen Komponenten des Modells zu finden: Wo befindet sich die Klasse des Modells? Gibt es Unterklassen des Modells, + *z.B.* EncoderModel, DecoderModel? Wo befindet sich die Selbstaufmerksamkeitsschicht? Gibt es mehrere verschiedene Aufmerksamkeitsebenen, + *z.B.* *Selbstaufmerksamkeit*, *Kreuzaufmerksamkeit*...? +- Wie können Sie das Modell in der ursprünglichen Umgebung des Repo debuggen? Müssen Sie *print* Anweisungen hinzufügen, können Sie + mit einem interaktiven Debugger wie *ipdb* arbeiten oder sollten Sie eine effiziente IDE zum Debuggen des Modells verwenden, wie z.B. PyCharm? + +Es ist sehr wichtig, dass Sie, bevor Sie mit der Portierung beginnen, den Code im Original-Repository **effizient** debuggen können +Repository können! Denken Sie auch daran, dass Sie mit einer Open-Source-Bibliothek arbeiten, also zögern Sie nicht, ein Problem oder +oder sogar eine Pull-Anfrage im Original-Repository zu stellen. Die Betreuer dieses Repositorys sind wahrscheinlich sehr froh darüber +dass jemand in ihren Code schaut! + +An diesem Punkt liegt es wirklich an Ihnen, welche Debugging-Umgebung und Strategie Sie zum Debuggen des ursprünglichen +Modell zu debuggen. Wir raten dringend davon ab, eine kostspielige GPU-Umgebung einzurichten, sondern arbeiten Sie einfach auf einer CPU, sowohl wenn Sie mit dem +in das ursprüngliche Repository einzutauchen und auch, wenn Sie beginnen, die 🤗 Transformers-Implementierung des Modells zu schreiben. Nur +ganz am Ende, wenn das Modell bereits erfolgreich auf 🤗 Transformers portiert wurde, sollte man überprüfen, ob das +Modell auch auf der GPU wie erwartet funktioniert. + +Im Allgemeinen gibt es zwei mögliche Debugging-Umgebungen für die Ausführung des Originalmodells + +- [Jupyter notebooks](https://jupyter.org/) / [google colab](https://colab.research.google.com/notebooks/intro.ipynb) +- Lokale Python-Skripte. + +Jupyter-Notebooks haben den Vorteil, dass sie eine zellenweise Ausführung ermöglichen, was hilfreich sein kann, um logische Komponenten besser voneinander zu trennen und +logische Komponenten voneinander zu trennen und schnellere Debugging-Zyklen zu haben, da Zwischenergebnisse gespeichert werden können. Außerdem, +Außerdem lassen sich Notebooks oft leichter mit anderen Mitwirkenden teilen, was sehr hilfreich sein kann, wenn Sie das Hugging Face Team um Hilfe bitten möchten. +Face Team um Hilfe bitten. Wenn Sie mit Jupyter-Notizbüchern vertraut sind, empfehlen wir Ihnen dringend, mit ihnen zu arbeiten. + +Der offensichtliche Nachteil von Jupyter-Notizbüchern ist, dass Sie, wenn Sie nicht daran gewöhnt sind, mit ihnen zu arbeiten, einige Zeit damit verbringen müssen +einige Zeit damit verbringen müssen, sich an die neue Programmierumgebung zu gewöhnen, und dass Sie möglicherweise Ihre bekannten Debugging-Tools nicht mehr verwenden können +wie z.B. `ipdb` nicht mehr verwenden können. + +Für jede Codebasis ist es immer ein guter erster Schritt, einen **kleinen** vortrainierten Checkpoint zu laden und in der Lage zu sein, einen +einzelnen Vorwärtsdurchlauf mit einem Dummy-Integer-Vektor von Eingabe-IDs als Eingabe zu reproduzieren. Ein solches Skript könnte wie folgt aussehen (in +Pseudocode): + +```python +model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids +original_output = model.predict(input_ids) +``` + +Was die Debugging-Strategie anbelangt, so können Sie im Allgemeinen aus mehreren Strategien wählen: + +- Zerlegen Sie das ursprüngliche Modell in viele kleine testbare Komponenten und führen Sie für jede dieser Komponenten einen Vorwärtsdurchlauf zur + Überprüfung +- Zerlegen Sie das ursprüngliche Modell nur in den ursprünglichen *Tokenizer* und das ursprüngliche *Modell*, führen Sie einen Vorwärtsdurchlauf für diese Komponenten durch + und verwenden Sie dazwischenliegende Druckanweisungen oder Haltepunkte zur Überprüfung. + +Auch hier bleibt es Ihnen überlassen, welche Strategie Sie wählen. Oft ist die eine oder die andere Strategie vorteilhaft, je nach der ursprünglichen Codebasis +Basis. + +Wenn die ursprüngliche Codebasis es Ihnen erlaubt, das Modell in kleinere Teilkomponenten zu zerlegen, *z.B.* wenn die ursprüngliche +Code-Basis problemlos im Eager-Modus ausgeführt werden kann, lohnt es sich in der Regel, dies zu tun. Es gibt einige wichtige Vorteile +am Anfang den schwierigeren Weg zu gehen: + +- Wenn Sie später das ursprüngliche Modell mit der Hugging Face-Implementierung vergleichen, können Sie automatisch überprüfen, ob + für jede Komponente einzeln überprüfen, ob die entsprechende Komponente der 🤗 Transformers-Implementierung übereinstimmt, anstatt sich auf + anstatt sich auf den visuellen Vergleich über Druckanweisungen zu verlassen +- können Sie das große Problem der Portierung eines Modells in kleinere Probleme der Portierung einzelner Komponenten zerlegen + einzelnen Komponenten zu zerlegen und so Ihre Arbeit besser zu strukturieren +- Die Aufteilung des Modells in logisch sinnvolle Komponenten hilft Ihnen, einen besseren Überblick über das Design des Modells zu bekommen + und somit das Modell besser zu verstehen +- In einem späteren Stadium helfen Ihnen diese komponentenweisen Tests dabei, sicherzustellen, dass keine Regressionen auftreten, während Sie fortfahren + Ihren Code ändern + +[Lysandre's](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed) Integrationstests für ELECTRA +gibt ein schönes Beispiel dafür, wie dies geschehen kann. + +Wenn die ursprüngliche Codebasis jedoch sehr komplex ist oder nur die Ausführung von Zwischenkomponenten in einem kompilierten Modus erlaubt, +könnte es zu zeitaufwändig oder sogar unmöglich sein, das Modell in kleinere testbare Teilkomponenten zu zerlegen. Ein gutes +Beispiel ist die [T5's MeshTensorFlow](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) Bibliothek, die sehr komplex ist +sehr komplex ist und keine einfache Möglichkeit bietet, das Modell in seine Unterkomponenten zu zerlegen. Bei solchen Bibliotheken ist man +oft auf die Überprüfung von Druckanweisungen angewiesen. + +Unabhängig davon, welche Strategie Sie wählen, ist die empfohlene Vorgehensweise oft die gleiche, nämlich dass Sie mit der Fehlersuche in den +die Anfangsebenen zuerst und die Endebenen zuletzt debuggen. + +Es wird empfohlen, dass Sie die Ausgaben der folgenden Ebenen abrufen, entweder durch Druckanweisungen oder Unterkomponentenfunktionen +Schichten in der folgenden Reihenfolge abrufen: + +1. Rufen Sie die Eingabe-IDs ab, die an das Modell übergeben wurden +2. Rufen Sie die Worteinbettungen ab +3. Rufen Sie die Eingabe der ersten Transformer-Schicht ab +4. Rufen Sie die Ausgabe der ersten Transformer-Schicht ab +5. Rufen Sie die Ausgabe der folgenden n - 1 Transformer-Schichten ab +6. Rufen Sie die Ausgabe des gesamten BrandNewBert Modells ab + +Die Eingabe-IDs sollten dabei aus einem Array von Ganzzahlen bestehen, *z.B.* `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]` + +Die Ausgaben der folgenden Schichten bestehen oft aus mehrdimensionalen Float-Arrays und können wie folgt aussehen: + +``` +[[ + [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024], + [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132], + [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648], + ..., + [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288], + [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191], + [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]], +``` + +Wir erwarten, dass jedes zu 🤗 Transformers hinzugefügte Modell eine Reihe von Integrationstests besteht, was bedeutet, dass das ursprüngliche +Modell und die neu implementierte Version in 🤗 Transformers exakt dieselbe Ausgabe liefern müssen, und zwar mit einer Genauigkeit von 0,001! +Da es normal ist, dass das exakt gleiche Modell, das in verschiedenen Bibliotheken geschrieben wurde, je nach Bibliotheksrahmen eine leicht unterschiedliche Ausgabe liefern kann +eine leicht unterschiedliche Ausgabe liefern kann, akzeptieren wir eine Fehlertoleranz von 1e-3 (0,001). Es reicht nicht aus, wenn das Modell +fast das gleiche Ergebnis liefert, sie müssen fast identisch sein. Daher werden Sie sicherlich die Zwischenergebnisse +Zwischenergebnisse der 🤗 Transformers-Version mehrfach mit den Zwischenergebnissen der ursprünglichen Implementierung von +*brand_new_bert* vergleichen. In diesem Fall ist eine **effiziente** Debugging-Umgebung des ursprünglichen Repositorys absolut +wichtig ist. Hier sind einige Ratschläge, um Ihre Debugging-Umgebung so effizient wie möglich zu gestalten. + +- Finden Sie den besten Weg, um Zwischenergebnisse zu debuggen. Ist das ursprüngliche Repository in PyTorch geschrieben? Dann sollten Sie + dann sollten Sie sich wahrscheinlich die Zeit nehmen, ein längeres Skript zu schreiben, das das ursprüngliche Modell in kleinere Unterkomponenten zerlegt, um + Zwischenwerte abzurufen. Ist das ursprüngliche Repository in Tensorflow 1 geschrieben? Dann müssen Sie sich möglicherweise auf die + TensorFlow Druckoperationen wie [tf.print](https://www.tensorflow.org/api_docs/python/tf/print) verlassen, um die + Zwischenwerte auszugeben. Ist das ursprüngliche Repository in Jax geschrieben? Dann stellen Sie sicher, dass das Modell **nicht jitted** ist, wenn + wenn Sie den Vorwärtsdurchlauf ausführen, *z.B.* schauen Sie sich [dieser Link](https://github.com/google/jax/issues/196) an. +- Verwenden Sie den kleinsten vortrainierten Prüfpunkt, den Sie finden können. Je kleiner der Prüfpunkt ist, desto schneller wird Ihr Debugging-Zyklus + wird. Es ist nicht effizient, wenn Ihr vorab trainiertes Modell so groß ist, dass Ihr Vorwärtsdurchlauf mehr als 10 Sekunden dauert. + Falls nur sehr große Checkpoints verfügbar sind, kann es sinnvoller sein, ein Dummy-Modell in der neuen + Umgebung mit zufällig initialisierten Gewichten zu erstellen und diese Gewichte zum Vergleich mit der 🤗 Transformers-Version + Ihres Modells +- Vergewissern Sie sich, dass Sie den einfachsten Weg wählen, um einen Forward Pass im ursprünglichen Repository aufzurufen. Idealerweise sollten Sie + die Funktion im originalen Repository finden, die **nur** einen einzigen Vorwärtspass aufruft, *d.h.* die oft aufgerufen wird + Vorhersagen", "Auswerten", "Vorwärts" oder "Aufruf" genannt wird. Sie wollen keine Funktion debuggen, die `forward` aufruft + mehrfach aufruft, *z.B.* um Text zu erzeugen, wie `autoregressive_sample`, `generate`. +- Versuchen Sie, die Tokenisierung vom *Forward*-Pass des Modells zu trennen. Wenn das Original-Repository Beispiele zeigt, bei denen + Sie eine Zeichenkette eingeben müssen, dann versuchen Sie herauszufinden, an welcher Stelle im Vorwärtsaufruf die Zeichenketteneingabe in Eingabe-IDs geändert wird + geändert wird und beginnen Sie an dieser Stelle. Das könnte bedeuten, dass Sie möglicherweise selbst ein kleines Skript schreiben oder den + Originalcode so ändern müssen, dass Sie die ids direkt eingeben können, anstatt eine Zeichenkette einzugeben. +- Vergewissern Sie sich, dass sich das Modell in Ihrem Debugging-Setup **nicht** im Trainingsmodus befindet, der oft dazu führt, dass das Modell + Dies führt häufig zu zufälligen Ergebnissen, da das Modell mehrere Dropout-Schichten enthält. Stellen Sie sicher, dass der Vorwärtsdurchlauf in Ihrer Debugging + Umgebung **deterministisch** ist, damit die Dropout-Schichten nicht verwendet werden. Oder verwenden Sie *transformers.utils.set_seed*. + wenn sich die alte und die neue Implementierung im selben Framework befinden. + +Im folgenden Abschnitt finden Sie genauere Details/Tipps, wie Sie dies für *brand_new_bert* tun können. + +### 5.-14. Portierung von BrandNewBert auf 🤗 Transformatoren + +Als nächstes können Sie endlich damit beginnen, neuen Code zu 🤗 Transformers hinzuzufügen. Gehen Sie in den Klon Ihres 🤗 Transformers Forks: + +```bash +cd transformers +``` + +In dem speziellen Fall, dass Sie ein Modell hinzufügen, dessen Architektur genau mit der Modellarchitektur eines +Modells übereinstimmt, müssen Sie nur ein Konvertierungsskript hinzufügen, wie in [diesem Abschnitt](#write-a-conversion-script) beschrieben. +In diesem Fall können Sie einfach die gesamte Modellarchitektur des bereits vorhandenen Modells wiederverwenden. + +Andernfalls beginnen wir mit der Erstellung eines neuen Modells. Wir empfehlen die Verwendung des folgenden Skripts, um ein Modell hinzuzufügen +ein bestehendes Modell: + +```bash +transformers-cli add-new-model-like +``` + +Sie werden mit einem Fragebogen aufgefordert, die grundlegenden Informationen Ihres Modells einzugeben. + +**Eröffnen Sie einen Pull Request auf dem Haupt-Repositorium huggingface/transformers** + +Bevor Sie mit der Anpassung des automatisch generierten Codes beginnen, ist es nun an der Zeit, einen "Work in progress (WIP)" Pull +Anfrage, *z.B.* "[WIP] Add *brand_new_bert*", in 🤗 Transformers zu öffnen, damit Sie und das Hugging Face Team +Seite an Seite an der Integration des Modells in 🤗 Transformers arbeiten können. + +Sie sollten Folgendes tun: + +1. Erstellen Sie eine Verzweigung mit einem beschreibenden Namen von Ihrer Hauptverzweigung + +```bash +git checkout -b add_brand_new_bert +``` + +2. Bestätigen Sie den automatisch generierten Code: + +```bash +git add . +git commit +``` + +3. Abrufen und zurücksetzen auf die aktuelle Haupt + +```bash +git fetch upstream +git rebase upstream/main +``` + +4. Übertragen Sie die Änderungen auf Ihr Konto mit: + +```bash +git push -u origin a-descriptive-name-for-my-changes +``` + +5. Wenn Sie zufrieden sind, gehen Sie auf die Webseite Ihrer Abspaltung auf GitHub. Klicken Sie auf "Pull request". Stellen Sie sicher, dass Sie das + GitHub-Handle einiger Mitglieder des Hugging Face-Teams als Reviewer hinzuzufügen, damit das Hugging Face-Team über zukünftige Änderungen informiert wird. + zukünftige Änderungen benachrichtigt wird. + +6. Ändern Sie den PR in einen Entwurf, indem Sie auf der rechten Seite der GitHub-Pull-Request-Webseite auf "In Entwurf umwandeln" klicken. + +Vergessen Sie im Folgenden nicht, wenn Sie Fortschritte gemacht haben, Ihre Arbeit zu committen und in Ihr Konto zu pushen, damit sie in der Pull-Anfrage erscheint. +damit sie in der Pull-Anfrage angezeigt wird. Außerdem sollten Sie darauf achten, dass Sie Ihre Arbeit von Zeit zu Zeit mit dem aktuellen main +von Zeit zu Zeit zu aktualisieren, indem Sie dies tun: + +```bash +git fetch upstream +git merge upstream/main +``` + +Generell sollten Sie alle Fragen, die Sie in Bezug auf das Modell oder Ihre Implementierung haben, in Ihrem PR stellen und +in der PR diskutiert/gelöst werden. Auf diese Weise wird das Hugging Face Team immer benachrichtigt, wenn Sie neuen Code einreichen oder +wenn Sie eine Frage haben. Es ist oft sehr hilfreich, das Hugging Face-Team auf Ihren hinzugefügten Code hinzuweisen, damit das Hugging Face-Team Ihr Problem oder Ihre Frage besser verstehen kann. +Face-Team Ihr Problem oder Ihre Frage besser verstehen kann. + +Gehen Sie dazu auf die Registerkarte "Geänderte Dateien", auf der Sie alle Ihre Änderungen sehen, gehen Sie zu einer Zeile, zu der Sie eine Frage stellen möchten +eine Frage stellen möchten, und klicken Sie auf das "+"-Symbol, um einen Kommentar hinzuzufügen. Wenn eine Frage oder ein Problem gelöst wurde, +können Sie auf die Schaltfläche "Lösen" des erstellten Kommentars klicken. + +Auf dieselbe Weise wird das Hugging Face-Team Kommentare öffnen, wenn es Ihren Code überprüft. Wir empfehlen, die meisten Fragen +auf GitHub in Ihrem PR zu stellen. Für einige sehr allgemeine Fragen, die für die Öffentlichkeit nicht sehr nützlich sind, können Sie das +Hugging Face Team per Slack oder E-Mail zu stellen. + +**5. Passen Sie den Code der generierten Modelle für brand_new_bert** an. + +Zunächst werden wir uns nur auf das Modell selbst konzentrieren und uns nicht um den Tokenizer kümmern. Den gesamten relevanten Code sollten Sie +finden Sie in den generierten Dateien `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` und +`src/transformers/models/brand_new_bert/configuration_brand_new_bert.py`. + +Jetzt können Sie endlich mit dem Programmieren beginnen :). Der generierte Code in +`src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` wird entweder die gleiche Architektur wie BERT haben, wenn +wenn es sich um ein reines Encoder-Modell handelt oder BART, wenn es sich um ein Encoder-Decoder-Modell handelt. An diesem Punkt sollten Sie sich daran erinnern, was +was Sie am Anfang über die theoretischen Aspekte des Modells gelernt haben: *Wie unterscheidet sich das Modell von BERT oder +BART?*". Implementieren Sie diese Änderungen, was oft bedeutet, dass Sie die *Selbstaufmerksamkeitsschicht*, die Reihenfolge der Normalisierungsschicht usw. ändern müssen. +Schicht usw... Auch hier ist es oft nützlich, sich die ähnliche Architektur bereits bestehender Modelle in Transformers anzusehen, um ein besseres Gefühl dafür zu bekommen +ein besseres Gefühl dafür zu bekommen, wie Ihr Modell implementiert werden sollte. + +**Beachten Sie**, dass Sie an diesem Punkt nicht sehr sicher sein müssen, dass Ihr Code völlig korrekt oder sauber ist. Vielmehr ist es +Sie sollten vielmehr eine erste *unbereinigte*, kopierte Version des ursprünglichen Codes in +src/transformers/models/brand_new_bert/modeling_brand_new_bert.py" hinzuzufügen, bis Sie das Gefühl haben, dass der gesamte notwendige Code +hinzugefügt wurde. Unserer Erfahrung nach ist es viel effizienter, schnell eine erste Version des erforderlichen Codes hinzuzufügen und +den Code iterativ mit dem Konvertierungsskript zu verbessern/korrigieren, wie im nächsten Abschnitt beschrieben. Das einzige, was +zu diesem Zeitpunkt funktionieren muss, ist, dass Sie die 🤗 Transformers-Implementierung von *brand_new_bert* instanziieren können, *d.h.* der +folgende Befehl sollte funktionieren: + +```python +from transformers import BrandNewBertModel, BrandNewBertConfig + +model = BrandNewBertModel(BrandNewBertConfig()) +``` + +Der obige Befehl erstellt ein Modell gemäß den Standardparametern, die in `BrandNewBertConfig()` definiert sind, mit +zufälligen Gewichten und stellt damit sicher, dass die `init()` Methoden aller Komponenten funktionieren. + +Beachten Sie, dass alle zufälligen Initialisierungen in der Methode `_init_weights` Ihres `BrandnewBertPreTrainedModel` stattfinden sollten. +Klasse erfolgen sollte. Sie sollte alle Blattmodule in Abhängigkeit von den Variablen der Konfiguration initialisieren. Hier ist ein Beispiel mit der +BERT `_init_weights` Methode: + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) +``` + +Sie können weitere benutzerdefinierte Schemata verwenden, wenn Sie eine spezielle Initialisierung für einige Module benötigen. Zum Beispiel in +`Wav2Vec2ForPreTraining` müssen die letzten beiden linearen Schichten die Initialisierung des regulären PyTorch `nn.Linear` haben. +aber alle anderen sollten eine Initialisierung wie oben verwenden. Dies ist wie folgt kodiert: + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, Wav2Vec2ForPreTraining): + module.project_hid.reset_parameters() + module.project_q.reset_parameters() + module.project_hid._is_hf_initialized = True + module.project_q._is_hf_initialized = True + elif isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() +``` + +Das Flag `_is_hf_initialized` wird intern verwendet, um sicherzustellen, dass wir ein Submodul nur einmal initialisieren. Wenn Sie es auf +`True` für `module.project_q` und `module.project_hid` setzen, stellen wir sicher, dass die benutzerdefinierte Initialisierung, die wir vorgenommen haben, später nicht überschrieben wird, +die Funktion `_init_weights` nicht auf sie angewendet wird. + +**6. Schreiben Sie ein Konvertierungsskript** + +Als nächstes sollten Sie ein Konvertierungsskript schreiben, mit dem Sie den Checkpoint, den Sie zum Debuggen von *brand_new_bert* im +im ursprünglichen Repository in einen Prüfpunkt konvertieren, der mit Ihrer gerade erstellten 🤗 Transformers-Implementierung von +*brand_new_bert*. Es ist nicht ratsam, das Konvertierungsskript von Grund auf neu zu schreiben, sondern die bereits +bestehenden Konvertierungsskripten in 🤗 Transformers nach einem Skript zu suchen, das für die Konvertierung eines ähnlichen Modells verwendet wurde, das im +demselben Framework wie *brand_new_bert* geschrieben wurde. Normalerweise reicht es aus, ein bereits vorhandenes Konvertierungsskript zu kopieren und +es für Ihren Anwendungsfall leicht anzupassen. Zögern Sie nicht, das Hugging Face Team zu bitten, Sie auf ein ähnliches, bereits vorhandenes +Konvertierungsskript für Ihr Modell zu finden. + +- Wenn Sie ein Modell von TensorFlow nach PyTorch portieren, ist ein guter Ausgangspunkt das Konvertierungsskript von BERT [hier](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91) +- Wenn Sie ein Modell von PyTorch nach PyTorch portieren, ist ein guter Ausgangspunkt das Konvertierungsskript von BART [hier](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py) + +Im Folgenden werden wir kurz erklären, wie PyTorch-Modelle Ebenengewichte speichern und Ebenennamen definieren. In PyTorch wird der +Name einer Ebene durch den Namen des Klassenattributs definiert, das Sie der Ebene geben. Lassen Sie uns ein Dummy-Modell in +PyTorch, das wir `SimpleModel` nennen, wie folgt: + +```python +from torch import nn + + +class SimpleModel(nn.Module): + def __init__(self): + super().__init__() + self.dense = nn.Linear(10, 10) + self.intermediate = nn.Linear(10, 10) + self.layer_norm = nn.LayerNorm(10) +``` + +Jetzt können wir eine Instanz dieser Modelldefinition erstellen, die alle Gewichte ausfüllt: `dense`, `intermediate`, +`layer_norm` mit zufälligen Gewichten. Wir können das Modell ausdrucken, um seine Architektur zu sehen + +```python +model = SimpleModel() + +print(model) +``` + +Dies gibt folgendes aus: + +``` +SimpleModel( + (dense): Linear(in_features=10, out_features=10, bias=True) + (intermediate): Linear(in_features=10, out_features=10, bias=True) + (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) +) +``` + +Wir können sehen, dass die Ebenennamen durch den Namen des Klassenattributs in PyTorch definiert sind. Sie können die Gewichtswerte +Werte einer bestimmten Ebene anzeigen lassen: + +```python +print(model.dense.weight.data) +``` + +um zu sehen, dass die Gewichte zufällig initialisiert wurden + +``` +tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, + -0.2077, 0.2157], + [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, + 0.2166, -0.0212], + [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, + -0.1023, -0.0447], + [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, + -0.1876, -0.2467], + [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, + 0.2577, 0.0402], + [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, + 0.2132, 0.1680], + [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, + 0.2707, -0.2509], + [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, + 0.1829, -0.1568], + [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, + 0.0333, -0.0536], + [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, + 0.2220, 0.2358]]). +``` + +Im Konvertierungsskript sollten Sie diese zufällig initialisierten Gewichte mit den genauen Gewichten der +entsprechenden Ebene im Kontrollpunkt. *Z.B.* + +```python +# retrieve matching layer weights, e.g. by +# recursive algorithm +layer_name = "dense" +pretrained_weight = array_of_dense_layer + +model_pointer = getattr(model, "dense") + +model_pointer.weight.data = torch.from_numpy(pretrained_weight) +``` + +Dabei müssen Sie sicherstellen, dass jedes zufällig initialisierte Gewicht Ihres PyTorch-Modells und sein entsprechendes +Checkpoint-Gewicht in **Form und Name** genau übereinstimmen. Zu diesem Zweck ist es **notwendig**, assert +Anweisungen für die Form hinzuzufügen und die Namen der Checkpoint-Gewichte auszugeben. Sie sollten z.B. Anweisungen hinzufügen wie: + +```python +assert ( + model_pointer.weight.shape == pretrained_weight.shape +), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" +``` + +Außerdem sollten Sie die Namen der beiden Gewichte ausdrucken, um sicherzustellen, dass sie übereinstimmen, *z.B.*. + +```python +logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") +``` + +Wenn entweder die Form oder der Name nicht übereinstimmt, haben Sie wahrscheinlich das falsche Kontrollpunktgewicht einer zufällig +Ebene der 🤗 Transformers-Implementierung zugewiesen. + +Eine falsche Form ist höchstwahrscheinlich auf eine falsche Einstellung der Konfigurationsparameter in `BrandNewBertConfig()` zurückzuführen, die +nicht genau mit denen übereinstimmen, die für den zu konvertierenden Prüfpunkt verwendet wurden. Es könnte aber auch sein, dass +die PyTorch-Implementierung eines Layers erfordert, dass das Gewicht vorher transponiert wird. + +Schließlich sollten Sie auch überprüfen, ob **alle** erforderlichen Gewichte initialisiert sind und alle Checkpoint-Gewichte ausgeben, die +die nicht zur Initialisierung verwendet wurden, um sicherzustellen, dass das Modell korrekt konvertiert wurde. Es ist völlig normal, dass die +Konvertierungsversuche entweder mit einer falschen Shape-Anweisung oder einer falschen Namenszuweisung fehlschlagen. Das liegt höchstwahrscheinlich daran, dass entweder +Sie haben falsche Parameter in `BrandNewBertConfig()` verwendet, haben eine falsche Architektur in der 🤗 Transformers +Implementierung, Sie haben einen Fehler in den `init()` Funktionen einer der Komponenten der 🤗 Transformers +Implementierung oder Sie müssen eine der Kontrollpunktgewichte transponieren. + +Dieser Schritt sollte mit dem vorherigen Schritt wiederholt werden, bis alle Gewichte des Kontrollpunkts korrekt in das +Transformers-Modell geladen sind. Nachdem Sie den Prüfpunkt korrekt in die 🤗 Transformers-Implementierung geladen haben, können Sie das Modell +das Modell unter einem Ordner Ihrer Wahl `/path/to/converted/checkpoint/folder` speichern, der dann sowohl ein +Datei `pytorch_model.bin` und eine Datei `config.json` enthalten sollte: + +```python +model.save_pretrained("/path/to/converted/checkpoint/folder") +``` + +**7. Implementieren Sie den Vorwärtspass** + +Nachdem es Ihnen gelungen ist, die trainierten Gewichte korrekt in die 🤗 Transformers-Implementierung zu laden, sollten Sie nun dafür sorgen +sicherstellen, dass der Forward Pass korrekt implementiert ist. In [Machen Sie sich mit dem ursprünglichen Repository vertraut](#3-4-führen-sie-einen-pre-training-checkpoint-mit-dem-original-repository-durch) haben Sie bereits ein Skript erstellt, das einen Forward Pass +Durchlauf des Modells unter Verwendung des Original-Repositorys durchführt. Jetzt sollten Sie ein analoges Skript schreiben, das die 🤗 Transformers +Implementierung anstelle der Originalimplementierung verwenden. Es sollte wie folgt aussehen: + +```python +model = BrandNewBertModel.from_pretrained("/path/to/converted/checkpoint/folder") +input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] +output = model(input_ids).last_hidden_states +``` + +Es ist sehr wahrscheinlich, dass die 🤗 Transformers-Implementierung und die ursprüngliche Modell-Implementierung nicht genau die gleiche Ausgabe liefern. +beim ersten Mal nicht die gleiche Ausgabe liefern oder dass der Vorwärtsdurchlauf einen Fehler auslöst. Seien Sie nicht enttäuscht - das ist zu erwarten! Erstens, +sollten Sie sicherstellen, dass der Vorwärtsdurchlauf keine Fehler auslöst. Es passiert oft, dass die falschen Dimensionen verwendet werden +verwendet werden, was zu einem *Dimensionality mismatch* Fehler führt oder dass der falsche Datentyp verwendet wird, *z.B.* `torch.long` +anstelle von `torch.float32`. Zögern Sie nicht, das Hugging Face Team um Hilfe zu bitten, wenn Sie bestimmte Fehler nicht lösen können. +bestimmte Fehler nicht lösen können. + +Um sicherzustellen, dass die Implementierung von 🤗 Transformers korrekt funktioniert, müssen Sie sicherstellen, dass die Ausgaben +einer Genauigkeit von `1e-3` entsprechen. Zunächst sollten Sie sicherstellen, dass die Ausgabeformen identisch sind, *d.h.*. +Die Ausgabeform *outputs.shape* sollte für das Skript der 🤗 Transformers-Implementierung und die ursprüngliche +Implementierung ergeben. Als nächstes sollten Sie sicherstellen, dass auch die Ausgabewerte identisch sind. Dies ist einer der schwierigsten +Teile des Hinzufügens eines neuen Modells. Häufige Fehler, warum die Ausgaben nicht identisch sind, sind: + +- Einige Ebenen wurden nicht hinzugefügt, *d.h.* eine *Aktivierungsebene* wurde nicht hinzugefügt, oder die Restverbindung wurde vergessen +- Die Worteinbettungsmatrix wurde nicht gebunden +- Es werden die falschen Positionseinbettungen verwendet, da die ursprüngliche Implementierung einen Offset verwendet +- Dropout wird während des Vorwärtsdurchlaufs angewendet. Um dies zu beheben, stellen Sie sicher, dass *model.training auf False* steht und dass keine Dropout + Schicht während des Vorwärtsdurchlaufs fälschlicherweise aktiviert wird, *d.h.* übergeben Sie *self.training* an [PyTorch's functional dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout) + +Der beste Weg, das Problem zu beheben, besteht normalerweise darin, sich den Vorwärtsdurchlauf der ursprünglichen Implementierung und die 🤗 +Transformers-Implementierung nebeneinander zu sehen und zu prüfen, ob es Unterschiede gibt. Idealerweise sollten Sie die +Zwischenergebnisse beider Implementierungen des Vorwärtsdurchlaufs debuggen/ausdrucken, um die genaue Position im Netzwerk zu finden, an der die 🤗 +Transformers-Implementierung eine andere Ausgabe zeigt als die ursprüngliche Implementierung. Stellen Sie zunächst sicher, dass die +hartcodierten `input_ids` in beiden Skripten identisch sind. Überprüfen Sie dann, ob die Ausgaben der ersten Transformation von +der `input_ids` (normalerweise die Worteinbettungen) identisch sind. Und dann arbeiten Sie sich bis zur allerletzten Schicht des +Netzwerks. Irgendwann werden Sie einen Unterschied zwischen den beiden Implementierungen feststellen, der Sie auf den Fehler +in der Implementierung von 🤗 Transformers hinweist. Unserer Erfahrung nach ist ein einfacher und effizienter Weg, viele Druckanweisungen hinzuzufügen +sowohl in der Original-Implementierung als auch in der 🤗 Transformers-Implementierung an den gleichen Stellen im Netzwerk +hinzuzufügen und nacheinander Druckanweisungen zu entfernen, die dieselben Werte für Zwischenpräsentationen anzeigen. + +Wenn Sie sicher sind, dass beide Implementierungen die gleiche Ausgabe liefern, überprüfen Sie die Ausgaben mit +`torch.allclose(original_output, output, atol=1e-3)` überprüfen, haben Sie den schwierigsten Teil hinter sich! Herzlichen Glückwunsch - die +Arbeit, die noch zu erledigen ist, sollte ein Kinderspiel sein 😊. + +**8. Hinzufügen aller notwendigen Modelltests** + +An diesem Punkt haben Sie erfolgreich ein neues Modell hinzugefügt. Es ist jedoch sehr gut möglich, dass das Modell noch nicht +noch nicht vollständig mit dem erforderlichen Design übereinstimmt. Um sicherzustellen, dass die Implementierung vollständig kompatibel mit 🤗 Transformers ist, sollten alle +gemeinsamen Tests bestehen. Der Cookiecutter sollte automatisch eine Testdatei für Ihr Modell hinzugefügt haben, wahrscheinlich unter +demselben `tests/models/brand_new_bert/test_modeling_brand_new_bert.py`. Führen Sie diese Testdatei aus, um zu überprüfen, ob alle gängigen +Tests bestehen: + +```bash +pytest tests/models/brand_new_bert/test_modeling_brand_new_bert.py +``` + +Nachdem Sie alle allgemeinen Tests festgelegt haben, müssen Sie nun sicherstellen, dass all die schöne Arbeit, die Sie geleistet haben, gut getestet ist, damit + +- a) die Community Ihre Arbeit leicht nachvollziehen kann, indem sie sich spezifische Tests von *brand_new_bert* ansieht +- b) zukünftige Änderungen an Ihrem Modell keine wichtigen Funktionen des Modells zerstören. + +Als erstes sollten Sie Integrationstests hinzufügen. Diese Integrationstests tun im Wesentlichen dasselbe wie die Debugging-Skripte +die Sie zuvor zur Implementierung des Modells in 🤗 Transformers verwendet haben. Eine Vorlage für diese Modelltests wurde bereits von dem +Cookiecutter hinzugefügt, die `BrandNewBertModelIntegrationTests` heißt und nur noch von Ihnen ausgefüllt werden muss. Um sicherzustellen, dass diese +Tests erfolgreich sind, führen Sie + +```bash +RUN_SLOW=1 pytest -sv tests/models/brand_new_bert/test_modeling_brand_new_bert.py::BrandNewBertModelIntegrationTests +``` + + + +Falls Sie Windows verwenden, sollten Sie `RUN_SLOW=1` durch `SET RUN_SLOW=1` ersetzen. + + + +Zweitens sollten alle Funktionen, die speziell für *brand_new_bert* sind, zusätzlich in einem separaten Test getestet werden unter +`BrandNewBertModelTester`/`BrandNewBertModelTest`. Dieser Teil wird oft vergessen, ist aber in zweierlei Hinsicht äußerst nützlich +Weise: + +- Er hilft dabei, das Wissen, das Sie während der Modellerweiterung erworben haben, an die Community weiterzugeben, indem er zeigt, wie die + speziellen Funktionen von *brand_new_bert* funktionieren sollten. +- Künftige Mitwirkende können Änderungen am Modell schnell testen, indem sie diese speziellen Tests ausführen. + + +**9. Implementieren Sie den Tokenizer** + +Als nächstes sollten wir den Tokenizer von *brand_new_bert* hinzufügen. Normalerweise ist der Tokenizer äquivalent oder sehr ähnlich zu einem +bereits vorhandenen Tokenizer von 🤗 Transformers. + +Es ist sehr wichtig, die ursprüngliche Tokenizer-Datei zu finden/extrahieren und es zu schaffen, diese Datei in die 🤗 +Transformers Implementierung des Tokenizers zu laden. + +Um sicherzustellen, dass der Tokenizer korrekt funktioniert, empfiehlt es sich, zunächst ein Skript im ursprünglichen Repository zu erstellen +zu erstellen, das eine Zeichenkette eingibt und die `input_ids` zurückgibt. Es könnte etwa so aussehen (in Pseudocode): + +```python +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = model.tokenize(input_str) +``` + +Möglicherweise müssen Sie noch einmal einen Blick in das ursprüngliche Repository werfen, um die richtige Tokenizer-Funktion zu finden, oder Sie müssen +Sie müssen vielleicht sogar Änderungen an Ihrem Klon des Original-Repositorys vornehmen, um nur die `input_ids` auszugeben. Nach dem Schreiben +ein funktionierendes Tokenisierungsskript geschrieben, das das ursprüngliche Repository verwendet, sollten Sie ein analoges Skript für 🤗 Transformers +erstellt werden. Es sollte ähnlich wie dieses aussehen: + +```python +from transformers import BrandNewBertTokenizer + +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." + +tokenizer = BrandNewBertTokenizer.from_pretrained("/path/to/tokenizer/folder/") + +input_ids = tokenizer(input_str).input_ids +``` + +Wenn beide `input_ids` die gleichen Werte ergeben, sollte als letzter Schritt auch eine Tokenizer-Testdatei hinzugefügt werden. + +Analog zu den Modellierungstestdateien von *brand_new_bert* sollten auch die Tokenisierungs-Testdateien von *brand_new_bert* +eine Reihe von fest kodierten Integrationstests enthalten. + +**10. Führen Sie End-to-End-Integrationstests aus** + +Nachdem Sie den Tokenizer hinzugefügt haben, sollten Sie auch ein paar End-to-End-Integrationstests, die sowohl das Modell als auch den +Tokenizer zu `tests/models/brand_new_bert/test_modeling_brand_new_bert.py` in 🤗 Transformers. +Ein solcher Test sollte bei einem aussagekräftigen +Text-zu-Text-Beispiel zeigen, dass die Implementierung von 🤗 Transformers wie erwartet funktioniert. Ein aussagekräftiges Text-zu-Text-Beispiel kann +z.B. *ein Quell-zu-Ziel-Übersetzungspaar, ein Artikel-zu-Zusammenfassung-Paar, ein Frage-zu-Antwort-Paar, usw... Wenn keiner der +der portierten Prüfpunkte in einer nachgelagerten Aufgabe feinabgestimmt wurde, genügt es, sich einfach auf die Modelltests zu verlassen. In einem +letzten Schritt, um sicherzustellen, dass das Modell voll funktionsfähig ist, sollten Sie alle Tests auch auf der GPU durchführen. Es kann +Es kann vorkommen, dass Sie vergessen haben, einige `.to(self.device)` Anweisungen zu internen Tensoren des Modells hinzuzufügen, was in einem solchen +Test zu einem Fehler führen würde. Falls Sie keinen Zugang zu einem Grafikprozessor haben, kann das Hugging Face Team diese Tests für Sie durchführen. +Tests für Sie übernehmen. + +**11. Docstring hinzufügen** + +Nun sind alle notwendigen Funktionen für *brand_new_bert* hinzugefügt - Sie sind fast fertig! Das Einzige, was Sie noch hinzufügen müssen, ist +ein schöner Docstring und eine Doku-Seite. Der Cookiecutter sollte eine Vorlagendatei namens +`docs/source/model_doc/brand_new_bert.md` hinzugefügt haben, die Sie ausfüllen sollten. Die Benutzer Ihres Modells werden in der Regel zuerst einen Blick auf +diese Seite ansehen, bevor sie Ihr Modell verwenden. Daher muss die Dokumentation verständlich und prägnant sein. Es ist sehr nützlich für +die Gemeinschaft, einige *Tipps* hinzuzufügen, um zu zeigen, wie das Modell verwendet werden sollte. Zögern Sie nicht, das Hugging Face-Team anzupingen +bezüglich der Docstrings. + +Stellen Sie als nächstes sicher, dass der zu `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` hinzugefügte docstring +korrekt ist und alle erforderlichen Eingaben und Ausgaben enthält. Wir haben eine ausführliche Anleitung zum Schreiben von Dokumentationen und unserem Docstring-Format [hier](writing-documentation). Es ist immer gut, sich daran zu erinnern, dass die Dokumentation +mindestens so sorgfältig behandelt werden sollte wie der Code in 🤗 Transformers, denn die Dokumentation ist in der Regel der erste Kontaktpunkt der +Berührungspunkt der Community mit dem Modell ist. + +**Code refactor** + +Großartig, jetzt haben Sie den gesamten erforderlichen Code für *brand_new_bert* hinzugefügt. An diesem Punkt sollten Sie einige mögliche +falschen Codestil korrigieren, indem Sie ausführen: + +```bash +make style +``` + +und überprüfen Sie, ob Ihr Kodierungsstil die Qualitätsprüfung besteht: + +```bash +make quality +``` + +Es gibt noch ein paar andere sehr strenge Designtests in 🤗 Transformers, die möglicherweise noch fehlschlagen, was sich in den +den Tests Ihres Pull Requests. Dies liegt oft an fehlenden Informationen im Docstring oder an einer falschen +Benennung. Das Hugging Face Team wird Ihnen sicherlich helfen, wenn Sie hier nicht weiterkommen. + +Und schließlich ist es immer eine gute Idee, den eigenen Code zu refaktorisieren, nachdem man sichergestellt hat, dass er korrekt funktioniert. Wenn alle +Tests bestanden haben, ist es nun an der Zeit, den hinzugefügten Code noch einmal durchzugehen und einige Überarbeitungen vorzunehmen. + +Sie haben nun den Codierungsteil abgeschlossen, herzlichen Glückwunsch! 🎉 Sie sind großartig! 😎 + +**12. Laden Sie die Modelle in den Model Hub hoch** + +In diesem letzten Teil sollten Sie alle Checkpoints konvertieren und in den Modell-Hub hochladen und eine Modellkarte für jeden +hochgeladenen Modell-Kontrollpunkt. Sie können sich mit den Hub-Funktionen vertraut machen, indem Sie unsere [Model sharing and uploading Page](model_sharing) lesen. Hier sollten Sie mit dem Hugging Face-Team zusammenarbeiten, um einen passenden Namen für jeden +Checkpoint festzulegen und die erforderlichen Zugriffsrechte zu erhalten, um das Modell unter der Organisation des Autors *brand_new_bert* hochladen zu können. +*brand_new_bert*. Die Methode `push_to_hub`, die in allen Modellen in `transformers` vorhanden ist, ist ein schneller und effizienter Weg, Ihren Checkpoint in den Hub zu pushen. Ein kleines Snippet ist unten eingefügt: + +```python +brand_new_bert.push_to_hub("brand_new_bert") +# Uncomment the following line to push to an organization. +# brand_new_bert.push_to_hub("/brand_new_bert") +``` + +Es lohnt sich, etwas Zeit darauf zu verwenden, für jeden Kontrollpunkt passende Musterkarten zu erstellen. Die Modellkarten sollten die +spezifischen Merkmale dieses bestimmten Prüfpunkts hervorheben, * z.B.* auf welchem Datensatz wurde der Prüfpunkt +vortrainiert/abgestimmt? Für welche nachgelagerte Aufgabe sollte das Modell verwendet werden? Und fügen Sie auch etwas Code bei, wie Sie +wie das Modell korrekt verwendet wird. + +**13. (Optional) Notizbuch hinzufügen** + +Es ist sehr hilfreich, ein Notizbuch hinzuzufügen, in dem im Detail gezeigt wird, wie *brand_new_bert* für Schlussfolgerungen verwendet werden kann und/oder +bei einer nachgelagerten Aufgabe feinabgestimmt wird. Dies ist nicht zwingend erforderlich, um Ihren PR zusammenzuführen, aber sehr nützlich für die Gemeinschaft. + +**14. Reichen Sie Ihren fertigen PR ein** + +Sie sind jetzt mit der Programmierung fertig und können zum letzten Schritt übergehen, nämlich der Zusammenführung Ihres PR mit main. Normalerweise hat das +Hugging Face Team Ihnen an diesem Punkt bereits geholfen haben, aber es lohnt sich, sich etwas Zeit zu nehmen, um Ihrem fertigen +PR eine schöne Beschreibung zu geben und eventuell Kommentare zu Ihrem Code hinzuzufügen, wenn Sie Ihren Gutachter auf bestimmte Designentscheidungen hinweisen wollen. +Gutachter hinweisen wollen. + +### Teilen Sie Ihre Arbeit!! + +Jetzt ist es an der Zeit, von der Community Anerkennung für Ihre Arbeit zu bekommen! Die Fertigstellung einer Modellergänzung ist ein wichtiger +Beitrag zu Transformers und der gesamten NLP-Gemeinschaft. Ihr Code und die portierten vortrainierten Modelle werden sicherlich +von Hunderten und vielleicht sogar Tausenden von Entwicklern und Forschern genutzt werden. Sie sollten stolz auf Ihre Arbeit sein und Ihre +Ihre Leistung mit der Gemeinschaft teilen. + +**Sie haben ein weiteres Modell erstellt, das für jeden in der Community super einfach zugänglich ist! 🤯** diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_pipeline.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..47d93e90ac14948b1d0429214efd281790701c01 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/add_new_pipeline.md @@ -0,0 +1,254 @@ + + +# Wie erstellt man eine benutzerdefinierte Pipeline? + +In dieser Anleitung sehen wir uns an, wie Sie eine benutzerdefinierte Pipeline erstellen und sie auf dem [Hub](https://hf.co/models) freigeben oder sie der +🤗 Transformers-Bibliothek hinzufügen. + +Zuallererst müssen Sie entscheiden, welche Roheingaben die Pipeline verarbeiten kann. Es kann sich um Strings, rohe Bytes, +Dictionaries oder was auch immer die wahrscheinlichste gewünschte Eingabe ist. Versuchen Sie, diese Eingaben so rein wie möglich in Python zu halten +denn das macht die Kompatibilität einfacher (auch mit anderen Sprachen über JSON). Dies werden die Eingaben der +Pipeline (`Vorverarbeitung`). + +Definieren Sie dann die `Outputs`. Dieselbe Richtlinie wie für die Eingänge. Je einfacher, desto besser. Dies werden die Ausgaben der +Methode `Postprocess`. + +Beginnen Sie damit, die Basisklasse `Pipeline` mit den 4 Methoden zu erben, die für die Implementierung von `preprocess` benötigt werden, +Weiterleiten", "Nachbearbeitung" und "Parameter säubern". + + +```python +from transformers import Pipeline + + +class MyPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + return preprocess_kwargs, {}, {} + + def preprocess(self, inputs, maybe_arg=2): + model_input = Tensor(inputs["input_ids"]) + return {"model_input": model_input} + + def _forward(self, model_inputs): + # model_inputs == {"model_input": model_input} + outputs = self.model(**model_inputs) + # Maybe {"logits": Tensor(...)} + return outputs + + def postprocess(self, model_outputs): + best_class = model_outputs["logits"].softmax(-1) + return best_class +``` + +Die Struktur dieser Aufteilung soll eine relativ nahtlose Unterstützung für CPU/GPU ermöglichen und gleichzeitig die Durchführung von +Vor-/Nachbearbeitung auf der CPU in verschiedenen Threads + +Preprocess" nimmt die ursprünglich definierten Eingaben und wandelt sie in etwas um, das in das Modell eingespeist werden kann. Es kann +mehr Informationen enthalten und ist normalerweise ein `Dict`. + +`_forward` ist das Implementierungsdetail und ist nicht dafür gedacht, direkt aufgerufen zu werden. Weiterleiten" ist die bevorzugte +aufgerufene Methode, da sie Sicherheitsvorkehrungen enthält, die sicherstellen, dass alles auf dem erwarteten Gerät funktioniert. Wenn etwas +mit einem realen Modell verknüpft ist, gehört es in die Methode `_forward`, alles andere gehört in die Methoden preprocess/postprocess. + +Die Methode `Postprocess` nimmt die Ausgabe von `_forward` und verwandelt sie in die endgültige Ausgabe, die zuvor festgelegt wurde. +zuvor entschieden wurde. + +Die Methode `_sanitize_parameters` ermöglicht es dem Benutzer, beliebige Parameter zu übergeben, wann immer er möchte, sei es bei der Initialisierung +Zeit `pipeline(...., maybe_arg=4)` oder zur Aufrufzeit `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`. + +Die Rückgabe von `_sanitize_parameters` sind die 3 Dicts von kwargs, die direkt an `preprocess` übergeben werden, +`_forward` und `postprocess` übergeben werden. Füllen Sie nichts aus, wenn der Aufrufer keinen zusätzlichen Parameter angegeben hat. Das +erlaubt es, die Standardargumente in der Funktionsdefinition beizubehalten, was immer "natürlicher" ist. + +Ein klassisches Beispiel wäre das Argument `top_k` in der Nachbearbeitung bei Klassifizierungsaufgaben. + +```python +>>> pipe = pipeline("my-new-task") +>>> pipe("This is a test") +[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05} +{"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}] + +>>> pipe("This is a test", top_k=2) +[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}] +``` + +In order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit +`_sanitize_parameters` to allow this new parameter. + + +```python +def postprocess(self, model_outputs, top_k=5): + best_class = model_outputs["logits"].softmax(-1) + # Add logic to handle top_k + return best_class + + +def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + + postprocess_kwargs = {} + if "top_k" in kwargs: + postprocess_kwargs["top_k"] = kwargs["top_k"] + return preprocess_kwargs, {}, postprocess_kwargs +``` + +Versuchen Sie, die Eingaben/Ausgaben sehr einfach und idealerweise JSON-serialisierbar zu halten, da dies die Verwendung der Pipeline sehr einfach macht +ohne dass die Benutzer neue Arten von Objekten verstehen müssen. Es ist auch relativ üblich, viele verschiedene Arten von Argumenten zu unterstützen +von Argumenten zu unterstützen (Audiodateien, die Dateinamen, URLs oder reine Bytes sein können). + + + +## Hinzufügen zur Liste der unterstützten Aufgaben + +Um Ihre `neue Aufgabe` in die Liste der unterstützten Aufgaben aufzunehmen, müssen Sie sie zur `PIPELINE_REGISTRY` hinzufügen: + +```python +from transformers.pipelines import PIPELINE_REGISTRY + +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, +) +``` + +Wenn Sie möchten, können Sie ein Standardmodell angeben. In diesem Fall sollte es mit einer bestimmten Revision (die der Name einer Verzweigung oder ein Commit-Hash sein kann, hier haben wir `"abcdef"` genommen) sowie mit dem Typ versehen sein: + +```python +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, + default={"pt": ("user/awesome_model", "abcdef")}, + type="text", # current support type: text, audio, image, multimodal +) +``` + +## Teilen Sie Ihre Pipeline auf dem Hub + +Um Ihre benutzerdefinierte Pipeline auf dem Hub freizugeben, müssen Sie lediglich den benutzerdefinierten Code Ihrer `Pipeline`-Unterklasse in einer +Python-Datei speichern. Nehmen wir zum Beispiel an, Sie möchten eine benutzerdefinierte Pipeline für die Klassifizierung von Satzpaaren wie folgt verwenden: + +```py +import numpy as np + +from transformers import Pipeline + + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} +``` + +Die Implementierung ist Framework-unabhängig und funktioniert für PyTorch- und TensorFlow-Modelle. Wenn wir dies in einer Datei +einer Datei namens `pair_classification.py` gespeichert haben, können wir sie importieren und wie folgt registrieren: + +```py +from pair_classification import PairClassificationPipeline +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, +) +``` + +Sobald dies geschehen ist, können wir es mit einem vortrainierten Modell verwenden. Zum Beispiel wurde `sgugger/finetuned-bert-mrpc` auf den +auf den MRPC-Datensatz abgestimmt, der Satzpaare als Paraphrasen oder nicht klassifiziert. + +```py +from transformers import pipeline + +classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc") +``` + +Dann können wir sie auf dem Hub mit der Methode `push_to_hub` freigeben: + +```py +classifier.push_to_hub("test-dynamic-pipeline") +``` + +Dadurch wird die Datei, in der Sie `PairClassificationPipeline` definiert haben, in den Ordner `"test-dynamic-pipeline"` kopiert, +und speichert das Modell und den Tokenizer der Pipeline, bevor Sie alles in das Repository verschieben +`{Ihr_Benutzername}/test-dynamic-pipeline`. Danach kann jeder die Pipeline verwenden, solange er die Option +`trust_remote_code=True` angeben: + +```py +from transformers import pipeline + +classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True) +``` + +## Hinzufügen der Pipeline zu 🤗 Transformers + +Wenn Sie Ihre Pipeline zu 🤗 Transformers beitragen möchten, müssen Sie ein neues Modul im Untermodul `pipelines` hinzufügen +mit dem Code Ihrer Pipeline hinzufügen. Fügen Sie es dann der Liste der in `pipelines/__init__.py` definierten Aufgaben hinzu. + +Dann müssen Sie noch Tests hinzufügen. Erstellen Sie eine neue Datei `tests/test_pipelines_MY_PIPELINE.py` mit Beispielen für die anderen Tests. + +Die Funktion `run_pipeline_test` ist sehr allgemein gehalten und läuft auf kleinen Zufallsmodellen auf jeder möglichen +Architektur, wie durch `model_mapping` und `tf_model_mapping` definiert. + +Dies ist sehr wichtig, um die zukünftige Kompatibilität zu testen, d.h. wenn jemand ein neues Modell für +`XXXForQuestionAnswering` hinzufügt, wird der Pipeline-Test versuchen, mit diesem Modell zu arbeiten. Da die Modelle zufällig sind, ist es +ist es unmöglich, die tatsächlichen Werte zu überprüfen. Deshalb gibt es eine Hilfsfunktion `ANY`, die einfach versucht, die +Ausgabe der Pipeline TYPE. + +Außerdem *müssen* Sie 2 (idealerweise 4) Tests implementieren. + +- `test_small_model_pt` : Definieren Sie 1 kleines Modell für diese Pipeline (es spielt keine Rolle, ob die Ergebnisse keinen Sinn ergeben) + und testen Sie die Ausgaben der Pipeline. Die Ergebnisse sollten die gleichen sein wie bei `test_small_model_tf`. +- `test_small_model_tf` : Definieren Sie 1 kleines Modell für diese Pipeline (es spielt keine Rolle, ob die Ergebnisse keinen Sinn ergeben) + und testen Sie die Ausgaben der Pipeline. Die Ergebnisse sollten die gleichen sein wie bei `test_small_model_pt`. +- `test_large_model_pt` (`optional`): Testet die Pipeline an einer echten Pipeline, bei der die Ergebnisse + Sinn machen. Diese Tests sind langsam und sollten als solche gekennzeichnet werden. Hier geht es darum, die Pipeline zu präsentieren und sicherzustellen + sicherzustellen, dass es in zukünftigen Versionen keine Abweichungen gibt. +- `test_large_model_tf` (`optional`): Testet die Pipeline an einer echten Pipeline, bei der die Ergebnisse + Sinn machen. Diese Tests sind langsam und sollten als solche gekennzeichnet werden. Hier geht es darum, die Pipeline zu präsentieren und sicherzustellen + sicherzustellen, dass es in zukünftigen Versionen keine Abweichungen gibt. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/autoclass_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/autoclass_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..5dea87ca552c1af2ee6953bcf424b12f7bc56217 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/autoclass_tutorial.md @@ -0,0 +1,131 @@ + + +# Vortrainierte Instanzen mit einer AutoClass laden + +Bei so vielen verschiedenen Transformator-Architekturen kann es eine Herausforderung sein, eine für Ihren Checkpoint zu erstellen. Als Teil der 🤗 Transformers Kernphilosophie, die Bibliothek leicht, einfach und flexibel nutzbar zu machen, leitet eine `AutoClass` automatisch die richtige Architektur aus einem gegebenen Checkpoint ab und lädt sie. Mit der Methode `from_pretrained()` kann man schnell ein vortrainiertes Modell für eine beliebige Architektur laden, so dass man keine Zeit und Ressourcen aufwenden muss, um ein Modell von Grund auf zu trainieren. Die Erstellung dieser Art von Checkpoint-agnostischem Code bedeutet, dass Ihr Code, wenn er für einen Checkpoint funktioniert, auch mit einem anderen Checkpoint funktionieren wird - solange er für eine ähnliche Aufgabe trainiert wurde - selbst wenn die Architektur unterschiedlich ist. + + + +Denken Sie daran, dass sich die Architektur auf das Skelett des Modells bezieht und die Checkpoints die Gewichte für eine bestimmte Architektur sind. Zum Beispiel ist [BERT](https://huggingface.co/google-bert/bert-base-uncased) eine Architektur, während `google-bert/bert-base-uncased` ein Checkpoint ist. Modell ist ein allgemeiner Begriff, der entweder Architektur oder Prüfpunkt bedeuten kann. + + + +In dieser Anleitung lernen Sie, wie man: + +* Einen vortrainierten Tokenizer lädt. +* Einen vortrainierten Merkmalsextraktor lädt. +* Einen vortrainierten Prozessor lädt. +* Ein vortrainiertes Modell lädt. + +## AutoTokenizer + +Nahezu jede NLP-Aufgabe beginnt mit einem Tokenizer. Ein Tokenizer wandelt Ihre Eingabe in ein Format um, das vom Modell verarbeitet werden kann. + +Laden Sie einen Tokenizer mit [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") +``` + +Dann tokenisieren Sie Ihre Eingabe wie unten gezeigt: + +```py +>>> sequence = "In a hole in the ground there lived a hobbit." +>>> print(tokenizer(sequence)) +{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +## AutoFeatureExtractor + +Für Audio- und Bildverarbeitungsaufgaben verarbeitet ein Merkmalsextraktor das Audiosignal oder Bild in das richtige Eingabeformat. + +Laden Sie einen Merkmalsextraktor mit [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained( +... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +## AutoProcessor + +Multimodale Aufgaben erfordern einen Prozessor, der zwei Arten von Vorverarbeitungswerkzeugen kombiniert. Das Modell [LayoutLMV2](model_doc/layoutlmv2) beispielsweise benötigt einen Feature-Extraktor für Bilder und einen Tokenizer für Text; ein Prozessor kombiniert beide. + +Laden Sie einen Prozessor mit [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased") +``` + +## AutoModel + + + +Mit den `AutoModelFor`-Klassen können Sie schließlich ein vortrainiertes Modell für eine bestimmte Aufgabe laden (siehe [hier](model_doc/auto) für eine vollständige Liste der verfügbaren Aufgaben). Laden Sie zum Beispiel ein Modell für die Sequenzklassifikation mit [`AutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Sie können denselben Prüfpunkt problemlos wiederverwenden, um eine Architektur für eine andere Aufgabe zu laden: + +```py +>>> from transformers import AutoModelForTokenClassification + +>>> model = AutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + + + +Für PyTorch-Modelle verwendet die Methode `from_pretrained()` `torch.load()`, die intern `pickle` verwendet und als unsicher bekannt ist. Generell sollte man niemals ein Modell laden, das aus einer nicht vertrauenswürdigen Quelle stammen könnte, oder das manipuliert worden sein könnte. Dieses Sicherheitsrisiko wird für öffentliche Modelle, die auf dem Hugging Face Hub gehostet werden, teilweise gemildert, da diese bei jeder Übertragung [auf Malware](https://huggingface.co/docs/hub/security-malware) gescannt werden. Siehe die [Hub-Dokumentation](https://huggingface.co/docs/hub/security) für Best Practices wie [signierte Commit-Verifizierung](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg) mit GPG. + +TensorFlow- und Flax-Checkpoints sind nicht betroffen und können in PyTorch-Architekturen mit den Kwargs `from_tf` und `from_flax` für die Methode `from_pretrained` geladen werden, um dieses Problem zu umgehen. + + + +Im Allgemeinen empfehlen wir die Verwendung der Klasse "AutoTokenizer" und der Klasse "AutoModelFor", um trainierte Instanzen von Modellen zu laden. Dadurch wird sichergestellt, dass Sie jedes Mal die richtige Architektur laden. Im nächsten [Tutorial] (Vorverarbeitung) erfahren Sie, wie Sie Ihren neu geladenen Tokenizer, Feature Extractor und Prozessor verwenden, um einen Datensatz für die Feinabstimmung vorzuverarbeiten. + + +Mit den Klassen `TFAutoModelFor` schließlich können Sie ein vortrainiertes Modell für eine bestimmte Aufgabe laden (siehe [hier](model_doc/auto) für eine vollständige Liste der verfügbaren Aufgaben). Laden Sie zum Beispiel ein Modell für die Sequenzklassifikation mit [`TFAutoModelForSequenceClassification.from_pretrained`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Sie können denselben Prüfpunkt problemlos wiederverwenden, um eine Architektur für eine andere Aufgabe zu laden: + +```py +>>> from transformers import TFAutoModelForTokenClassification + +>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert/distilbert-base-uncased") +``` + +Im Allgemeinen empfehlen wir, die Klasse "AutoTokenizer" und die Klasse "TFAutoModelFor" zu verwenden, um vortrainierte Instanzen von Modellen zu laden. Dadurch wird sichergestellt, dass Sie jedes Mal die richtige Architektur laden. Im nächsten [Tutorial] (Vorverarbeitung) erfahren Sie, wie Sie Ihren neu geladenen Tokenizer, Feature Extractor und Prozessor verwenden, um einen Datensatz für die Feinabstimmung vorzuverarbeiten. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/contributing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..61ee8c3fc4e3472c1a94017d77915deae28e6dd3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/contributing.md @@ -0,0 +1,332 @@ + + +# Zu 🤗 Transformers beitragen + +Jeder ist willkommen, einen Beitrag zu leisten, und wir schätzen den Beitrag jedes Einzelnen. Codebeiträge sind nicht der einzige Weg, der Community zu helfen. Fragen zu beantworten, anderen zu helfen und die Dokumentation zu verbessern, sind ebenfalls äußerst wertvoll. + +Es hilft uns auch, wenn Sie das Projekt weiterempfehlen! Erwähnen Sie die Bibliothek in Blogposts über die großartigen Projekte, die sie ermöglicht hat, tweeten Sie, wenn sie Ihnen geholfen hat, oder hinterlassen Sie dem Repository ein ⭐️, um Danke zu sagen. + +Wie auch immer Sie sich entscheiden beizutragen, seien Sie achtsam und respektieren Sie unseren [Verhaltenskodex](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**Dieser Leitfaden wurde stark durch den fantastischen [scikit-learn-Leitfaden für Beiträge](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md) inspiriert.** + +## Beitragsmöglichkeiten + +Es gibt mehrere Wege, wie Sie zu 🤗 Transformers beitragen können: + +* Beheben Sie bestehende Probleme im vorhandenen Code. +* Erstellen Sie Issues im Zusammenhang mit Fehlern oder gewünschten neuen Funktionen. +* Implementieren Sie neue Modelle. +* Tragen Sie zu den Beispielen oder zur Dokumentation bei. + +Wenn Sie nicht wissen, wo Sie anfangen sollen, gibt es eine spezielle Liste von [Good First Issues](https://github.com/huggingface/transformers/contribute). Sie bietet Ihnen eine Liste offener und anfängerfreundlicher Probleme und hilft Ihnen, einen ersten Beitrag zu Open-Source zu leisten. Idealerweise erstellen Sie eine Pull-Anfrage und verlinken sie mit dem Issue, an dem Sie arbeiten möchten. Wir versuchen, erstellte PRs bevorzugt zu behandeln, da wir so den Fortschritt leicht verfolgen können, und die Option besteht, dass jemand anderes den PR übernehmen kann, falls der Beitragende keine Zeit mehr hat. + +Für etwas mehr Herausforderung, können Sie auch einen Blick auf die Liste der [Good Second Issues](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) werfen. Generell gilt: Legen Sie los, wenn Sie sich den Anforderungen gewachsen sehen und wir helfen Ihnen dabei! 🚀 + +> Alle Beiträge sind für die Community gleichermaßen wertvoll. 🥰 + +## Bestehende Probleme beheben + +Wenn Ihnen ein Problem im vorhandenen Code auffällt und Sie eine Lösung im Sinn haben, können Sie gerne einen Beitrag leisten und [eine Pull-Anfrage erstellen](#eine-pull-anfrage-erstellen)! + +## Ein fehlerspezifisches Issue oder eine Feature-Anfrage erstellen + +Tun Sie Ihr Bestes, diesen Richtlinien zu folgen, wenn Sie ein fehlerspezifisches Issue erstellen oder eine Feature-Anfrage einreichen. Das macht es uns leichter, Ihnen schnell und mit gutem Feedback zu antworten. + +### Haben Sie einen Fehler gefunden? + +Die 🤗 Transformers-Bibliothek verdankt ihre Robustheit und Zuverlässigkeit aller Nutzer, die frisch entdeckte Probleme melden. + +Wir würden es wirklich schätzen, wenn Sie **sicherstellen könnten, dass der Fehler noch nicht gemeldet wurde** (verwenden Sie die Suchleiste auf GitHub unter Issues), bevor Sie ein Issue erstellen. Ihr Problem sollte sich auch auf Fehler in der Bibliothek selbst und nicht auf Ihren eigenen Code beziehen. Wenn Sie sich nicht sicher sind, ob der Fehler in Ihrem eigenen Code oder der Bibliothek liegt, fragen Sie bitte zuerst im [Forum](https://discuss.huggingface.co/) nach. Das hilft uns, schneller auf Probleme im Zusammenhang mit der Bibliothek zu reagieren, anstatt auf allgemeine Fragen. + +Wenn Sie sich vergewissert haben, dass der Fehler noch nicht gemeldet wurde, geben Sie bitte die folgenden Informationen in Ihrem Issue an, damit wir es schnell beheben können: + +* Ihr **Betriebssystem und Version** sowie die Versionen von **Python**, **PyTorch** und **TensorFlow**, falls zutreffend. +* Ein kurzes und unabhängiges Code-Snippet, das es uns ermöglicht, den Fehler in weniger als 30 Sekunden nachzustellen. +* Den *vollständigen* Traceback, wenn eine Ausnahme geworfen wird. +* Fügen Sie weitere hilfreiche Informationen, wie z. B. Screenshots, an. + +Um das Betriebssystem und die Softwareversionen automatisch auszugeben, führen Sie den folgenden Befehl aus: + +```bash +transformers-cli env +``` + +Sie können denselben Befehl auch im Hauptverzeichnis des Repositorys ausführen: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Möchten Sie eine neue Funktion? + +Wenn Sie eine bestimmte neue Funktion in 🤗 Transformers sehen möchten, erstellen Sie bitte ein Issue und fügen Sie eine Beschreibung hinzu: + +1. Was ist die *Motivation* hinter dieser Funktion? Steht sie in Zusammenhang mit einem Problem oder einer Frustration mit der Bibliothek? Ist es eine Funktion, die Sie für ein Projekt benötigen? Ist es etwas, an dem Sie gearbeitet haben und denken, dass es der Community nutzen könnte? + + Was auch immer es ist, wir würden uns freuen, davon zu hören! + +1. Beschreiben Sie Ihre gewünschte Funktion so detailliert wie möglich. Je mehr Sie uns darüber erzählen können, desto besser können wir Ihnen helfen. +1. Stellen Sie einen *Code-Schnipsel* bereit, der die Funktionsweise demonstriert. +1. Falls die Funktion auf einem Paper beruht, verlinken Sie dieses bitte. + +Wenn Ihr Issue gut geschrieben ist, sind wir zum Zeitpunkt seiner Erstellung bereits zu 80 % fertig. + +Wir haben [Vorlagen](https://github.com/huggingface/transformers/tree/main/templates) hinzugefügt, um Ihnen den Start Ihres Issues zu erleichtern. + +## Möchten Sie ein neues Modell implementieren? + +Es werden ständig neue Modelle veröffentlicht. Wenn Sie ein neues Modell implementieren möchten, geben Sie bitte folgende Informationen an: + +* Eine kurze Beschreibung des Modells und einen Link zum Paper. +* Link zur Implementierung, falls sie Open-Source ist. +* Link zu den Modellgewichten, falls verfügbar. + +Lassen Sie es uns wissen, wenn Sie bereit sind, das Modell selbst beizutragen. Dann können wir Ihnen helfen, es zu 🤗 Transformers hinzuzufügen! + +Wir haben auch einen technischen Leitfaden dazu, [wie man ein Modell zu 🤗 Transformers hinzufügt](https://huggingface.co/docs/transformers/add_new_model). + +## Möchten Sie die Dokumentation erweitern? + +Wir sind immer auf der Suche nach Verbesserungen, die die Dokumentation klarer und präziser machen. Bitte teilen Sie uns Verbesserungsvorschläge mit, wie z. B. Tippfehler und fehlende, unklare oder ungenaue Inhalte. Wir übernehmen gerne die Änderungen oder helfen Ihnen, einen Beitrag zu leisten, wenn Sie daran interessiert sind! + +Für weitere Einzelheiten darüber, wie man die Dokumentation generiert, erstellt und schreibt, werfen Sie einen Blick auf das [README](https://github.com/huggingface/transformers/tree/main/docs) der Dokumentation. + +## Eine Pull-Anfrage erstellen + +Bevor Sie irgendwelchen Code schreiben, empfehlen wir Ihnen dringend, die bestehenden PRs oder Issues zu durchsuchen, um sicherzustellen, dass niemand bereits an diesem Thema arbeitet. Wenn Sie sich unsicher sind, ist es immer eine gute Idee, nach Feedback in einem neuen Issue zu fragen. + +Sie benötigen grundlegende `git`-Kenntnisse, um zu 🤗 Transformers beizutragen. Obwohl `git` nicht das einfachste Werkzeug ist, hat es ein sehr gutes Handbuch. Geben Sie `git --help` in eine Shell ein und genießen Sie es! Wenn Sie Bücher bevorzugen, ist [Pro Git](https://git-scm.com/book/en/v2) eine gute Anlaufstelle. + +Sie benötigen **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L426)** oder höher, um zu 🤗 Transformers beizutragen. Folgen Sie den nachstehenden Schritten, um mit dem Beitrag zu beginnen: + +1. Forken Sie das [Repository](https://github.com/huggingface/transformers), indem Sie auf den **[Fork](https://github.com/huggingface/transformers/fork)**-Button auf der Seite des Repositorys klicken. Dadurch wird eine Kopie des Codes auf Ihrem GitHub-Account erstellt. + +1. Klonen Sie Ihren Fork auf Ihre lokale Festplatte und fügen Sie das ursprüngliche Repository als Remote hinzu: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +1. Erstellen Sie einen neuen Branch, um Ihre Änderungen zu speichern: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 Arbeiten Sie **nicht** auf dem `main` Branch! + +1. Richten Sie eine Entwicklungsumgebung ein, indem Sie den folgenden Befehl in einer virtuellen Umgebung ausführen: + + ```bash + pip install -e ".[dev]" + ``` + + Wenn 🤗 Transformers bereits in der virtuellen Umgebung installiert war, entfernen Sie es mit `pip uninstall transformers`, bevor Sie es im bearbeitbaren Modus mit dem `-e` Flag neu installieren. + + Abhängig von Ihrem Betriebssystem und durch die wachsende Anzahl der optionalen Abhängigkeiten von Transformers könnten Sie mit diesem Befehl einen Fehler verursachen. Wenn das der Fall ist, stellen Sie sicher, dass Sie ihr bevorzugtes Deep-Learning-Framework (PyTorch, TensorFlow und/oder Flax) installieren und anschließend den folgenden Befehl ausführen: + + ```bash + pip install -e ".[quality]" + ``` + + Dies sollte für die meisten Anwendungsfälle ausreichend sein. + +1. Entwickeln Sie die Funktionen in Ihrem Branch. + + Während Sie an Ihrem Code arbeiten, sollten Sie sicherstellen, dass die Test-Suite erfolgreich durchläuft. Führen Sie die von Ihren Änderungen betroffenen Tests wie folgt aus: + + ```bash + pytest tests/.py + ``` + + Weitere Informationen über Tests finden Sie in der Anleitung zum Thema [Testen](https://huggingface.co/docs/transformers/testing). + + 🤗 Transformers stützt sich auf `black` und `ruff`, um seinen Quellcode konsistent zu formatieren. Nachdem Sie Änderungen vorgenommen haben, wenden Sie automatische Stilkorrekturen und Codeprüfungen, die nicht automatisiert werden können, in einem Schritt an: + + ```bash + make fixup + ``` + + Dieser Task ist optimiert, nur mit Dateien zu arbeiten, die von Ihrer PR modifiziert wurden. + + Wenn Sie die Prüfungen nacheinander ausführen möchten, wendet der folgende Befehl die Stilkorrekturen an: + + ```bash + make style + ``` + + 🤗 Transformers verwendet auch `ruff` und einige benutzerdefinierte Skripte, um auf Programmierfehler zu prüfen. Qualitätskontrollen werden von der CI durchgeführt, aber Sie können die gleichen Überprüfungen auch selbst ausführen: + + ```bash + make quality + ``` + + Abschließend haben wir viele Skripte, die sicherstellen, dass wir alle betroffenen Dateien aktualisieren, wenn wir ein neues Modell hinzufügen. Sie können diese wie folgt ausführen: + + ```bash + make repo-consistency + ``` + + Um mehr über diese Prüfungen zu erfahren und wie man mit ihnen Probleme behebt, lesen Sie den Leitfaden zu [Überprüfungen bei einer Pull-Anfrage](https://huggingface.co/docs/transformers/pr_checks). + + Wenn Sie Dokumente im Verzeichnis `docs/source` ändern, stellen Sie sicher, dass die Dokumentation noch generiert werden kann. Diese Prüfung wird auch im CI laufen, wenn Sie eine Pull-Anfrage erstellen. Um eine lokale Prüfung durchzuführen, müssen Sie den Dukumentation-Builder installieren: + + ```bash + pip install ".[docs]" + ``` + + Führen Sie den folgenden Befehl im Hauptverzeichnis des Repositorys aus: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + Dadurch wird die Dokumentation im Ordner `~/tmp/test-build` erstellt, wo Sie die erzeugten Markdown-Dateien mit Ihrem bevorzugten Editor überprüfen können. Sie können auch eine Vorschau der Dokumentation auf GitHub sehen, wenn Sie eine Pull-Anfrage öffnen. + + Wenn Sie mit Ihren Änderungen zufrieden sind, fügen Sie die geänderten Dateien mit `git add` hinzu und speichern Sie Ihre Änderungen lokal mit `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Bitte achten Sie darauf, [gute Commit-Nachrichten](https://chris.beams.io/posts/git-commit/) zu schreiben, um die von Ihnen vorgenommenen Änderungen klar zu kommunizieren! + + Um Ihre Kopie des Codes auf dem aktuellen Stand des ursprünglichen Repositorys zu halten, rebasen Sie Ihren Branch auf `upstream/branch` *bevor* Sie eine Pull-Anfrage öffnen oder falls Sie von einem Maintainer dazu aufgefordert werden: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Pushen Sie Ihre Änderungen in Ihrem Branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + Wenn Sie bereits eine Pull-Anfrage erstellt haben, müssen Sie den Push mit dem `--force` Flag erzwingen. Andernfalls, wenn die Pull-Anfrage noch nicht erstellt wurde, können Sie Ihre Änderungen normal pushen. + +1. Jetzt können Sie zu Ihrem Fork des Repositorys auf GitHub gehen und auf **Pull-Anfrage** klicken, um eine Pull-Anfrage zu erstellen. Stellen Sie sicher, dass Sie alle Punkte auf unserer [Checkliste](#checkliste-für-pull-anfragen) unten abhaken. Wenn Sie fertig sind, können Sie Ihre Änderungen zur Überprüfung an die Projektverantwortlichen senden. + +1. Es ist kein Problem, wenn die Maintainer Änderungen beantragen, das geschieht auch bei unseren Kernmitarbeitern! Damit jeder die Änderungen in der Pull-Anfrage sehen kann, arbeiten Sie in Ihrem lokalen Branch und pushen die Änderungen zu Ihrem Fork. Sie werden automatisch in der Pull-Anfrage erscheinen. + +### Checkliste für Pull-Anfragen + +☐ Der Titel der Pull-Anfrage sollte Ihren Beitrag zusammenfassen.
+☐ Wenn Ihre Pull-Anfrage ein bestimmtes Issue bearbeitet, erwähnen Sie bitte die zugehörige Nummer in der Beschreibung der Pull-Anfrage, sodass diese verlinkt sind (und Personen, die das Issue lesen, wissen, dass Sie daran arbeiten).
+☐ Um eine fortlaufende Bearbeitung anzuzeigen, versehen Sie bitte den Titel mit einem `[WIP]` Präfix. Diese sind nützlich, um doppelte Arbeit zu verhindern und sie von PRs abzuheben, die bereit zum Zusammenführen sind.
+☐ Stellen Sie sicher, dass existierende Tests bestanden werden.
+☐ Wenn Sie eine neue Funktion hinzufügen, erstellen Sie auch Tests dafür.
+ +* Wenn Sie ein neues Modell hinzufügen, stellen Sie sicher, dass Sie `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` verwenden, um die gemeinsamen Tests auszulösen. +* Wenn Sie neue `@slow` Tests hinzufügen, stellen Sie mit `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py` sicher, dass diese erfolgreich durchlaufen. +* Wenn Sie einen neuen Tokenizer hinzufügen, schreiben Sie Tests und stellen Sie mit `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` sicher, dass diese erfolgreich durchlaufen. +* CircleCI führt die langsamen Tests nicht aus, aber GitHub Actions tut dies jede Nacht!
+ +☐ Alle public Methoden müssen informative Docstrings haben (siehe [`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) als Beispiel).
+☐ Aufgrund des schnell wachsenden Repositorys fügen Sie bitte keine Bilder, Videos oder andere Nicht-Textdateien hinzu, die das Repository erheblich belasten würden. Verwenden Sie stattdessen ein Hub-Repository wie [`hf-internal-testing`](https://huggingface.co/hf-internal-testing), um diese Dateien zu hosten und sie per URL zu verlinken. Wir empfehlen Bilder, die zur Dokumentation gehören, im folgenden Repository abzulegen: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). Sie können eine PR in diesem Datasets-Repository erstellen und ein Hugging-Face-Mitglied bitten, sie zu mergen. + +Um mehr über die Prüfungen zu erfahren, die bei einer Pull-Anfrage ausgelöst werden, lesen Sie unseren Leitfaden zu [Überprüfungen bei einer Pull-Anfrage](https://huggingface.co/docs/transformers/pr_checks). + +### Tests + +Eine umfangreiche Test-Suite ist enthalten, um das Verhalten der Bibliothek und mehrerer Beispiele zu testen. Tests für die Bibliothek und Beispiele finden Sie jeweils im [tests](https://github.com/huggingface/transformers/tree/main/tests) und im [examples](https://github.com/huggingface/transformers/tree/main/examples) Ordner. + +Wir bevorzugen `pytest` und `pytest-xdist`, weil es schneller ist. Geben Sie einen *Pfad zu einem Unterordner oder einer Testdatei* vom Hauptverzeichnis des Repositorys aus an, um den Test auszuführen: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Analog für den `examples` Ordner, geben Sie einen *Pfad zu einem Unterordner oder einer Testdatei* an, um den Test auszuführen. Z. B. führt der folgende Befehl den Test des Unterordners für Textklassifizierung im PyTorch `examples` Ordner durch: + +```bash +pip install -r examples/xxx/requirements.txt # nur beim ersten Mal erforderlich +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Tatsächlich ist dies genau, wie unsere `make test` und `make test-examples` Befehle implementiert sind (abgesehen von `pip install`)! + +Sie können auch eine kleinere Anzahl an Tests angeben, um nur die Funktion, an der Sie arbeiten, zu testen. + +Standardmäßig werden langsame Tests übersprungen, aber Sie können die Umgebungsvariable `RUN_SLOW` auf `yes` setzen, um sie auszuführen. Dies wird den Download vieler Gigabyte an Modellen starten - stellen Sie also sicher, dass Sie sowohl genügend Festplattenspeicher als auch eine gute Internetverbindung oder die nötige Geduld haben! + + + +Vergessen Sie nicht, einen *Pfad zu einem Unterordner oder einer Testdatei* anzugeben, um den Test auszuführen. Sonst führen Sie alle Tests im `tests` oder `examples` Ordner aus, was sehr lange dauern wird! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Wie bei den langsamen Tests gibt es auch andere Umgebungsvariablen, die standardmäßig beim Testen nicht gesetzt sind: + +* `RUN_CUSTOM_TOKENIZERS`: Aktiviert Tests für benutzerdefinierte Tokenizer. + +Weitere Umgebungsvariablen und zusätzliche Informationen finden Sie in der [testing_utils.py](src/transformers/testing_utils.py). + +🤗 Transformers verwendet `pytest` nur als Test-Runner. Es verwendet keine `pytest`-spezifischen Funktionen in der Test-Suite selbst. + +Das bedeutet, `unittest` wird vollständig unterstützt. Folgend wird beschrieben, wie man Tests mit `unittest` ausführt: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Stil-Leitfaden + +Für Docstrings befolgt 🤗 Transformers den [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Lesen Sie unseren [Leitfaden zum Schreiben von Dokumentationen](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) für weitere Informationen. + +### Entwickeln unter Windows + +Unter Windows (falls Sie nicht im [Windows-Subsystem für Linux](https://learn.microsoft.com/en-us/windows/wsl/) oder WSL arbeiten) müssen Sie git so konfigurieren, dass Windows `CRLF` in Linux `LF` Zeilenenden umgewandelt werden: + +```bash +git config core.autocrlf input +``` + +Eine Möglichkeit, den `make`-Befehl unter Windows auszuführen, ist mit MSYS2: + +1. Laden Sie [MSYS2](https://www.msys2.org/) herunter und installieren Sie es nach `C:\msys64`. +1. Öffnen Sie die Kommandozeile `C:\msys64\msys2.exe` (sie sollte vom **Start**-Menü aus verfügbar sein). +1. Führen Sie den Befehl in der Shell aus: `pacman -Syu` und installieren Sie `make` mit `pacman -S make`. +1. Fügen Sie `C:\msys64\usr\bin` an Ihrer PATH-Umgebungsvariable an. + +Sie können nun `make` aus jedem Terminal heraus verwenden (PowerShell, cmd.exe usw.)! 🎉 + +### Ein geforktes Repository mit dem Haupt-Repository von Hugging Face synchronisieren + +Beim Aktualisieren des main-Branches eines geforkten Repositories beachten Sie bitte die folgenden Schritte, um das Anpingen des Haupt-Repositorys zu vermeiden, was unnötige Verweise in abhängigen PRs vermerkt und beteiligte Entwickler benachrichtigt: + +1. Wenn möglich, vermeiden Sie die Synchronisation mit dem Haupt-Repository über einen Branch und PR im geforkten Repository. Mergen Sie stattdessen direkt in den main-Branch des Forks. +1. Wenn ein PR unbedingt notwendig ist, verwenden Sie die folgenden Schritte, nachdem Sie Ihren Branch ausgecheckt haben: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/index.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/index.md new file mode 100644 index 0000000000000000000000000000000000000000..8aaaa5952c07fe55e373091df8b71f4b88974de0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/index.md @@ -0,0 +1,334 @@ + + +# 🤗 Transformers + +Maschinelles Lernen auf dem neuesten Stand der Technik für PyTorch, TensorFlow und JAX. + +🤗 Transformers bietet APIs zum einfachen Herunterladen und Trainieren von vortrainierten Modellen auf dem neuesten Stand der Technik. Die Verwendung von vortrainierten Modellen kann Rechenkosten sparen und den CO2-Fußabdruck reduzieren und Zeit sparen, die für das Training eines Modells von Grund auf benötigt wird. Die Modelle können für verschiedene Modalitäten verwendet werden, wie z. B.: + +* 📝 Text: Textklassifizierung, Informationsextrahierung, Beantwortung von Fragen, Zusammenfassung, Übersetzung und Texterstellung in über 100 Sprachen. +* 🖼️ Bilder: Bildklassifizierung, Objekterkennung und Segmentierung. +* 🗣️ Audio: Spracherkennung und Audioklassifizierung. +* 🐙 Multimodal: Beantwortung von Tabellenfragen, optische Zeichenerkennung, Informationsextraktion aus gescannten Dokumenten, Videoklassifizierung und Beantwortung visueller Fragen. + +Unsere Bibliothek unterstützt die nahtlose Integration von drei der beliebtesten Deep-Learning-Bibliotheken: [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) und [JAX](https://jax.readthedocs.io/en/latest/). Trainieren Sie Ihr Modell in drei Codezeilen in einem Framework und laden Sie es zur Inferenz mit einem anderen. + +Jede 🤗 Transformers-Architektur ist in einem eigenständigen Python-Modul definiert, so dass sie leicht für Forschung und Experimente angepasst werden kann. + +## Wenn Sie auf der Suche nach individueller Unterstützung durch das Hugging Face-Team sind + + + HuggingFace Expert Acceleration Program + + +## Inhalt + +Die Dokumentation ist in fünf Teile gegliedert: + +- **GET STARTED** enthält eine kurze Tour und Installationsanweisungen, um mit 🤗 Transformers loszulegen. +- **TUTORIALS** sind ein hervorragender Ausgangspunkt, wenn Sie neu in unserer Bibliothek sind. Dieser Abschnitt hilft Ihnen, die grundlegenden Fähigkeiten zu erlangen, die Sie benötigen, um mit 🤗 Transformers zu arbeiten. +- **HOW-TO GUIDES** zeigen Ihnen, wie Sie ein bestimmtes Ziel erreichen können, z. B. die Feinabstimmung eines vortrainierten Modells für die Sprachmodellierung oder die Erstellung eines benutzerdefinierten Modellkopfs. +- **KONZEPTUELLE ANLEITUNGEN** bietet weitere Diskussionen und Erklärungen zu den zugrunde liegenden Konzepten und Ideen hinter Modellen, Aufgaben und der Designphilosophie von 🤗 Transformers. +- **API** beschreibt jede Klasse und Funktion, gruppiert in: + + - **MAIN CLASSES** für die Hauptklassen, die die wichtigsten APIs der Bibliothek darstellen. + - MODELLE** für die Klassen und Funktionen, die zu jedem in der Bibliothek implementierten Modell gehören. + - **INTERNAL HELPERS** für die Klassen und Funktionen, die wir intern verwenden. + +Die Bibliothek enthält derzeit JAX-, PyTorch- und TensorFlow-Implementierungen, vortrainierte Modellgewichte, Nutzungsskripte und Konvertierungsprogramme für die folgenden Modelle. + +### Unterstütze Modelle + + + +1. **[ALBERT](model_doc/albert)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut. +1. **[ALIGN](model_doc/align)** (from Google Research) released with the paper [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://arxiv.org/abs/2102.05918) by Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig. +1. **[BART](model_doc/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer. +1. **[BARThez](model_doc/barthez)** (from École polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis. +1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen. +1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei. +1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. +1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. +1. **[BERTweet](model_doc/bertweet)** (from VinAI Research) released with the paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen. +1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed. +1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed. +1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston. +1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/). +1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry. +1. **[ByT5](model_doc/byt5)** (from Google Research) released with the paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel. +1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot. +1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting. +1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever. +1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong. +1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan. +1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie. +1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie. +1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun. +1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher. +1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang. +1. **[Data2Vec](model_doc/data2vec)** (from Facebook) released with the paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli. +1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. +1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch. +1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou. +1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko. +1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan. +1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into [DistilGPT2](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers-research-projects/tree/main/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers-research-projects/tree/main/distillation) and a German version of DistilBERT. +1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei. +1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. +1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun. +1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le. +1. **[ELECTRA](model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning. +1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. +1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab. +1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela. +1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon. +1. **[Funnel Transformer](model_doc/funnel)** (from CMU/Google Brain) released with the paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le. +1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim. +1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://openai.com/research/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever. +1. **[GPT Neo](model_doc/gpt_neo)** (from EleutherAI) released in the repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy. +1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745) by Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, Samuel Weinbach +1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://openai.com/research/better-language-models/) by Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever. +1. **[GPT-J](model_doc/gptj)** (from EleutherAI) released in the repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) by Ben Wang and Aran Komatsuzaki. +1. **[GPTSAN-japanese](model_doc/gptsan-japanese)** released in the repository [tanreinama/GPTSAN](https://github.com/tanreinama/GPTSAN/blob/main/report/model.md) by Toshiyuki Sakamoto(tanreinama). +1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang. +1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed. +1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer. +1. **[ImageGPT](model_doc/imagegpt)** (from OpenAI) released with the paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever. +1. **[LayoutLM](model_doc/layoutlm)** (from Microsoft Research Asia) released with the paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou. +1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou. +1. **[LayoutLMv3](model_doc/layoutlmv3)** (from Microsoft Research Asia) released with the paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei. +1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei. +1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan. +1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze. +1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan. +1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang. +1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto. +1. **[LXMERT](model_doc/lxmert)** (from UNC Chapel Hill) released with the paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal. +1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert. +1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin. +1. **[MarianMT](model_doc/marian)** Machine translation models trained using [OPUS](http://opus.nlpl.eu/) data by Jörg Tiedemann. The [Marian Framework](https://marian-nmt.github.io/) is being developed by the Microsoft Translator Team. +1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. +1. **[MaskFormer](model_doc/maskformer)** (from Meta and UIUC) released with the paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov. +1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. +1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan. +1. **[Megatron-BERT](model_doc/megatron-bert)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro. +1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro. +1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka. +1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou. +1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari. +1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. +1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. +1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen. +1. **[Nezha](model_doc/nezha)** (from Huawei Noah’s Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu. +1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team. +1. **[Nyströmformer](model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. +1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi. +1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al. +1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230) by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby. +1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu. +1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira. +1. **[PhoBERT](model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen. +1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. +1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. +1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. +1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius. +1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela. +1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. +1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya. +1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. +1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder. +1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. +1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. +1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. +1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. +1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi. +1. **[SEW-D](model_doc/sew_d)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi. +1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino. +1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau. +1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy. +1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. +1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. +1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/2111.09883) by Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo. +1. **[T5](model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[T5v1.1](model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. +1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. +1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou. +1. **[Trajectory Transformer](model_doc/trajectory_transformers)** (from the University of California at Berkeley) released with the paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine +1. **[Transformer-XL](model_doc/transfo-xl)** (from Google/CMU) released with the paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov. +1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei. +1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler +1. **[UMT5](model_doc/umt5)** (from Google Research) released with the paper [UniMax: Fairer and More Effective Language Sampling for Large-Scale Multilingual Pretraining](https://openreview.net/forum?id=kXwdL1cWOAi) by Hyung Won Chung, Xavier Garcia, Adam Roberts, Yi Tay, Orhan Firat, Sharan Narang, Noah Constant. +1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang. +1. **[UniSpeechSat](model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu. +1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. +1. **[VideoMAE](model_doc/videomae)** (from Multimedia Computing Group, Nanjing University) released with the paper [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang. +1. **[ViLT](model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. +1. **[Vision Transformer (ViT)](model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. +1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. +1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. +1. **[Wav2Vec2](model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. +1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino. +1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli. +1. **[WavLM](model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. +1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. +1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau. +1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. +1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov. +1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (from Facebook AI), released together with the paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau. +1. **[XLM-V](model_doc/xlm-v)** (from Meta AI) released with the paper [XLM-V: Overcoming the Vocabulary Bottleneck in Multilingual Masked Language Models](https://arxiv.org/abs/2301.10472) by Davis Liang, Hila Gonen, Yuning Mao, Rui Hou, Naman Goyal, Marjan Ghazvininejad, Luke Zettlemoyer, Madian Khabsa. +1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. +1. **[XLS-R](model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli. +1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli. +1. **[YOLOS](model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu. +1. **[YOSO](model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. + + +### Unterstützte Frameworks + +Die folgende Tabelle zeigt die derzeitige Unterstützung in der Bibliothek für jedes dieser Modelle, unabhängig davon, ob sie einen Python +Tokenizer haben (als "langsam" bezeichnet), ein "schneller" Tokenizer, der von der 🤗 Tokenizers Bibliothek unterstützt wird, ob sie Unterstützung in Jax (via +Flax), PyTorch, und/oder TensorFlow haben. + + + +| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support | +|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:| +| ALBERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| BART | ✅ | ✅ | ✅ | ✅ | ✅ | +| BEiT | ❌ | ❌ | ✅ | ❌ | ✅ | +| BERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| Bert Generation | ✅ | ❌ | ✅ | ❌ | ❌ | +| BigBird | ✅ | ✅ | ✅ | ❌ | ✅ | +| BigBird-Pegasus | ❌ | ❌ | ✅ | ❌ | ❌ | +| Blenderbot | ✅ | ✅ | ✅ | ✅ | ✅ | +| BlenderbotSmall | ✅ | ✅ | ✅ | ✅ | ✅ | +| BLOOM | ❌ | ✅ | ✅ | ❌ | ✅ | +| CamemBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| CANINE | ✅ | ❌ | ✅ | ❌ | ❌ | +| CLIP | ✅ | ✅ | ✅ | ✅ | ✅ | +| CodeGen | ✅ | ✅ | ✅ | ❌ | ❌ | +| ConvBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| ConvNeXT | ❌ | ❌ | ✅ | ✅ | ❌ | +| CTRL | ✅ | ❌ | ✅ | ✅ | ❌ | +| CvT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecAudio | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecText | ❌ | ❌ | ✅ | ❌ | ❌ | +| Data2VecVision | ❌ | ❌ | ✅ | ✅ | ❌ | +| DeBERTa | ✅ | ✅ | ✅ | ✅ | ❌ | +| DeBERTa-v2 | ✅ | ✅ | ✅ | ✅ | ❌ | +| Decision Transformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| DeiT | ❌ | ❌ | ✅ | ✅ | ❌ | +| DETR | ❌ | ❌ | ✅ | ❌ | ❌ | +| DistilBERT | ✅ | ✅ | ✅ | ✅ | ✅ | +| DPR | ✅ | ✅ | ✅ | ✅ | ❌ | +| DPT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ELECTRA | ✅ | ✅ | ✅ | ✅ | ✅ | +| Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ | +| FairSeq Machine-Translation | ✅ | ❌ | ✅ | ❌ | ❌ | +| FlauBERT | ✅ | ❌ | ✅ | ✅ | ❌ | +| FLAVA | ❌ | ❌ | ✅ | ❌ | ❌ | +| FNet | ✅ | ✅ | ✅ | ❌ | ❌ | +| Funnel Transformer | ✅ | ✅ | ✅ | ✅ | ❌ | +| GLPN | ❌ | ❌ | ✅ | ❌ | ❌ | +| GPT Neo | ❌ | ❌ | ✅ | ❌ | ✅ | +| GPT NeoX | ❌ | ✅ | ✅ | ❌ | ❌ | +| GPT-J | ❌ | ❌ | ✅ | ✅ | ✅ | +| GroupViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Hubert | ❌ | ❌ | ✅ | ✅ | ❌ | +| I-BERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ImageGPT | ❌ | ❌ | ✅ | ❌ | ❌ | +| LayoutLM | ✅ | ✅ | ✅ | ✅ | ❌ | +| LayoutLMv2 | ✅ | ✅ | ✅ | ❌ | ❌ | +| LayoutLMv3 | ✅ | ✅ | ✅ | ❌ | ❌ | +| LED | ✅ | ✅ | ✅ | ✅ | ❌ | +| LeViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Longformer | ✅ | ✅ | ✅ | ✅ | ❌ | +| LongT5 | ❌ | ❌ | ✅ | ❌ | ✅ | +| LUKE | ✅ | ❌ | ✅ | ❌ | ❌ | +| LXMERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| M-CTC-T | ❌ | ❌ | ✅ | ❌ | ❌ | +| M2M100 | ✅ | ❌ | ✅ | ❌ | ❌ | +| Marian | ✅ | ❌ | ✅ | ✅ | ✅ | +| MaskFormer | ❌ | ❌ | ✅ | ❌ | ❌ | +| mBART | ✅ | ✅ | ✅ | ✅ | ✅ | +| Megatron-BERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| MobileBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| MobileViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| MPNet | ✅ | ✅ | ✅ | ✅ | ❌ | +| MT5 | ✅ | ✅ | ✅ | ✅ | ✅ | +| MVP | ✅ | ✅ | ✅ | ❌ | ❌ | +| Nezha | ❌ | ❌ | ✅ | ❌ | ❌ | +| Nyströmformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| OpenAI GPT | ✅ | ✅ | ✅ | ✅ | ❌ | +| OpenAI GPT-2 | ✅ | ✅ | ✅ | ✅ | ✅ | +| OPT | ❌ | ❌ | ✅ | ✅ | ✅ | +| OWL-ViT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Pegasus | ✅ | ✅ | ✅ | ✅ | ✅ | +| Perceiver | ✅ | ❌ | ✅ | ❌ | ❌ | +| PLBart | ✅ | ❌ | ✅ | ❌ | ❌ | +| PoolFormer | ❌ | ❌ | ✅ | ❌ | ❌ | +| ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ | +| QDQBert | ❌ | ❌ | ✅ | ❌ | ❌ | +| RAG | ✅ | ❌ | ✅ | ✅ | ❌ | +| REALM | ✅ | ✅ | ✅ | ❌ | ❌ | +| Reformer | ✅ | ✅ | ✅ | ❌ | ❌ | +| RegNet | ❌ | ❌ | ✅ | ✅ | ✅ | +| RemBERT | ✅ | ✅ | ✅ | ✅ | ❌ | +| ResNet | ❌ | ❌ | ✅ | ✅ | ✅ | +| RetriBERT | ✅ | ✅ | ✅ | ❌ | ❌ | +| RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ | +| RoFormer | ✅ | ✅ | ✅ | ✅ | ✅ | +| SegFormer | ❌ | ❌ | ✅ | ✅ | ❌ | +| SEW | ❌ | ❌ | ✅ | ❌ | ❌ | +| SEW-D | ❌ | ❌ | ✅ | ❌ | ❌ | +| Speech Encoder decoder | ❌ | ❌ | ✅ | ❌ | ✅ | +| Speech2Text | ✅ | ❌ | ✅ | ✅ | ❌ | +| Speech2Text2 | ✅ | ❌ | ❌ | ❌ | ❌ | +| Splinter | ✅ | ✅ | ✅ | ❌ | ❌ | +| SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ | +| Swin Transformer | ❌ | ❌ | ✅ | ✅ | ❌ | +| Swin Transformer V2 | ❌ | ❌ | ✅ | ❌ | ❌ | +| T5 | ✅ | ✅ | ✅ | ✅ | ✅ | +| TAPAS | ✅ | ❌ | ✅ | ✅ | ❌ | +| Trajectory Transformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| Transformer-XL | ✅ | ❌ | ✅ | ✅ | ❌ | +| TrOCR | ❌ | ❌ | ✅ | ❌ | ❌ | +| UniSpeech | ❌ | ❌ | ✅ | ❌ | ❌ | +| UniSpeechSat | ❌ | ❌ | ✅ | ❌ | ❌ | +| VAN | ❌ | ❌ | ✅ | ❌ | ❌ | +| VideoMAE | ❌ | ❌ | ✅ | ❌ | ❌ | +| ViLT | ❌ | ❌ | ✅ | ❌ | ❌ | +| Vision Encoder decoder | ❌ | ❌ | ✅ | ✅ | ✅ | +| VisionTextDualEncoder | ❌ | ❌ | ✅ | ❌ | ✅ | +| VisualBERT | ❌ | ❌ | ✅ | ❌ | ❌ | +| ViT | ❌ | ❌ | ✅ | ✅ | ✅ | +| ViTMAE | ❌ | ❌ | ✅ | ✅ | ❌ | +| Wav2Vec2 | ✅ | ❌ | ✅ | ✅ | ✅ | +| Wav2Vec2-Conformer | ❌ | ❌ | ✅ | ❌ | ❌ | +| WavLM | ❌ | ❌ | ✅ | ❌ | ❌ | +| XGLM | ✅ | ✅ | ✅ | ❌ | ✅ | +| XLM | ✅ | ❌ | ✅ | ✅ | ❌ | +| XLM-ProphetNet | ✅ | ❌ | ✅ | ❌ | ❌ | +| XLM-RoBERTa | ✅ | ✅ | ✅ | ✅ | ✅ | +| XLM-RoBERTa-XL | ❌ | ❌ | ✅ | ❌ | ❌ | +| XLNet | ✅ | ✅ | ✅ | ✅ | ❌ | +| YOLOS | ❌ | ❌ | ✅ | ❌ | ❌ | +| YOSO | ❌ | ❌ | ✅ | ❌ | ❌ | + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/installation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..44b6f1ed981e1ef3531a344877088290c3e7bdb8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/installation.md @@ -0,0 +1,250 @@ + + +# Installation + +Installieren Sie 🤗 Transformers für die Deep-Learning-Bibliothek, mit der Sie arbeiten, richten Sie Ihren Cache ein und konfigurieren Sie 🤗 Transformers optional für den Offline-Betrieb. + +🤗 Transformers wurde unter Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, und Flax getestet. Folgen Sie den Installationsanweisungen unten für die von Ihnen verwendete Deep-Learning-Bibliothek: + +* [PyTorch](https://pytorch.org/get-started/locally/) installation instructions. +* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) installation instructions. +* [Flax](https://flax.readthedocs.io/en/latest/) installation instructions. + +## Installation mit pip + +Sie sollten 🤗 Transformers in einer [virtuellen Umgebung](https://docs.python.org/3/library/venv.html) installieren. Wenn Sie mit virtuellen Python-Umgebungen nicht vertraut sind, werfen Sie einen Blick auf diese [Anleitung](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). Eine virtuelle Umgebung macht es einfacher, verschiedene Projekte zu verwalten und Kompatibilitätsprobleme zwischen Abhängigkeiten zu vermeiden. + +Beginnen wir mit der Erstellung einer virtuellen Umgebung in Ihrem Projektverzeichnis: + + +```bash +python -m venv .env +``` + +Aktivieren wir die virtuelle Umgebung. Unter Linux und MacOs: + +```bash +source .env/bin/activate +``` +Aktivieren wir die virtuelle Umgebung unter Windows + +```bash +.env/Scripts/activate +``` + +Jetzt können wir die 🤗 Transformers mit dem folgenden Befehl installieren: + +```bash +pip install transformers +``` + +Bei reiner CPU-Unterstützung können wir 🤗 Transformers und eine Deep-Learning-Bibliothek bequem in einer Zeile installieren. Installieren wir zum Beispiel 🤗 Transformers und PyTorch mit: + +```bash +pip install transformers[torch] +``` + +🤗 Transformers und TensorFlow 2.0: + +```bash +pip install transformers[tf-cpu] +``` + +🤗 Transformers und Flax: + +```bash +pip install transformers[flax] +``` + +Überprüfen wir abschließend, ob 🤗 Transformers ordnungsgemäß installiert wurde, indem wir den folgenden Befehl ausführen. Es wird ein vortrainiertes Modell heruntergeladen: + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" +``` + +Dann wird die Kategorie und die Wahrscheinlichkeit ausgegeben: + +```bash +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +## Installation aus dem Code + +Installieren wir 🤗 Transformers aus dem Quellcode mit dem folgenden Befehl: + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +Dieser Befehl installiert die aktuelle `main` Version und nicht die neueste `stable` Version. Die `main`-Version ist nützlich, um mit den neuesten Entwicklungen Schritt zu halten. Zum Beispiel, wenn ein Fehler seit der letzten offiziellen Version behoben wurde, aber eine neue Version noch nicht veröffentlicht wurde. Das bedeutet jedoch, dass die "Hauptversion" nicht immer stabil ist. Wir bemühen uns, die Hauptversion einsatzbereit zu halten, und die meisten Probleme werden normalerweise innerhalb weniger Stunden oder eines Tages behoben. Wenn Sie auf ein Problem stoßen, öffnen Sie bitte ein [Issue](https://github.com/huggingface/transformers/issues), damit wir es noch schneller beheben können! + +Überprüfen wir, ob 🤗 Transformers richtig installiert wurde, indem Sie den folgenden Befehl ausführen: + + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" +``` + +## Editierbare Installation + +Sie benötigen eine bearbeitbare Installation, wenn Sie: + +* die "Haupt"-Version des Quellcodes verwenden möchten. +* Zu 🤗 Transformers beitragen und Änderungen am Code testen wollen. + +Klonen Sie das Repository und installieren 🤗 Transformers mit den folgenden Befehlen: + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + +Diese Befehle verknüpfen den Ordner, in den Sie das Repository geklont haben, mit den Pfaden Ihrer Python-Bibliotheken. Python wird nun in dem Ordner suchen, in den Sie geklont haben, zusätzlich zu den normalen Bibliothekspfaden. Wenn zum Beispiel Ihre Python-Pakete normalerweise in `~/anaconda3/envs/main/lib/python3.7/site-packages/` installiert sind, wird Python auch den Ordner durchsuchen, in den Sie geklont haben: `~/transformers/`. + + + + +Sie müssen den Ordner `transformers` behalten, wenn Sie die Bibliothek weiter verwenden wollen. + + + +Jetzt können Sie Ihren Klon mit dem folgenden Befehl ganz einfach auf die neueste Version von 🤗 Transformers aktualisieren: + + +```bash +cd ~/transformers/ +git pull +``` + +Ihre Python-Umgebung wird beim nächsten Ausführen die `main`-Version von 🤗 Transformers finden. + +## Installation mit conda + +Installation von dem conda Kanal `conda-forge`: + +```bash +conda install conda-forge::transformers +``` + +## Cache Einrichtung + +Vorgefertigte Modelle werden heruntergeladen und lokal zwischengespeichert unter: `~/.cache/huggingface/hub`. Dies ist das Standardverzeichnis, das durch die Shell-Umgebungsvariable "TRANSFORMERS_CACHE" vorgegeben ist. Unter Windows wird das Standardverzeichnis durch `C:\Benutzer\Benutzername\.cache\huggingface\hub` angegeben. Sie können die unten aufgeführten Shell-Umgebungsvariablen - in der Reihenfolge ihrer Priorität - ändern, um ein anderes Cache-Verzeichnis anzugeben: + +1. Shell-Umgebungsvariable (Standard): `HF_HUB_CACHE` oder `TRANSFORMERS_CACHE`. +2. Shell-Umgebungsvariable: `HF_HOME`. +3. Shell-Umgebungsvariable: `XDG_CACHE_HOME` + `/huggingface`. + + + + +Transformers verwendet die Shell-Umgebungsvariablen `PYTORCH_TRANSFORMERS_CACHE` oder `PYTORCH_PRETRAINED_BERT_CACHE`, wenn Sie von einer früheren Iteration dieser Bibliothek kommen und diese Umgebungsvariablen gesetzt haben, sofern Sie nicht die Shell-Umgebungsvariable `TRANSFORMERS_CACHE` angeben. + + + +## Offline Modus + +Transformers ist in der Lage, in einer Firewall- oder Offline-Umgebung zu laufen, indem es nur lokale Dateien verwendet. Setzen Sie die Umgebungsvariable `HF_HUB_OFFLINE=1`, um dieses Verhalten zu aktivieren. + + + +Fügen sie [🤗 Datasets](https://huggingface.co/docs/datasets/) zu Ihrem Offline-Trainingsworkflow hinzufügen, indem Sie die Umgebungsvariable `HF_DATASETS_OFFLINE=1` setzen. + + + +So würden Sie beispielsweise ein Programm in einem normalen Netzwerk mit einer Firewall für externe Instanzen mit dem folgenden Befehl ausführen: + +```bash +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +Führen Sie das gleiche Programm in einer Offline-Instanz mit aus: + +```bash +HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ +python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... +``` + +Das Skript sollte nun laufen, ohne sich aufzuhängen oder eine Zeitüberschreitung abzuwarten, da es weiß, dass es nur nach lokalen Dateien suchen soll. + + +### Abrufen von Modellen und Tokenizern zur Offline-Verwendung + +Eine andere Möglichkeit, 🤗 Transformers offline zu verwenden, besteht darin, die Dateien im Voraus herunterzuladen und dann auf ihren lokalen Pfad zu verweisen, wenn Sie sie offline verwenden müssen. Es gibt drei Möglichkeiten, dies zu tun: + +* Laden Sie eine Datei über die Benutzeroberfläche des [Model Hub](https://huggingface.co/models) herunter, indem Sie auf das ↓-Symbol klicken. + + ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png) + +* Verwenden Sie den [PreTrainedModel.from_pretrained] und [PreTrainedModel.save_pretrained] Workflow: + + 1. Laden Sie Ihre Dateien im Voraus mit [`PreTrainedModel.from_pretrained`] herunter: + + ```py + >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM + + >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") + >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") + ``` + + 2. Speichern Sie Ihre Dateien in einem bestimmten Verzeichnis mit [`PreTrainedModel.save_pretrained`]: + + ```py + >>> tokenizer.save_pretrained("./your/path/bigscience_t0") + >>> model.save_pretrained("./your/path/bigscience_t0") + ``` + + 3. Wenn Sie nun offline sind, laden Sie Ihre Dateien mit [`PreTrainedModel.from_pretrained`] aus dem bestimmten Verzeichnis: + + ```py + >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") + >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0") + ``` + +* Programmatisches Herunterladen von Dateien mit der [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) Bibliothek: + + 1. Installieren Sie die "huggingface_hub"-Bibliothek in Ihrer virtuellen Umgebung: + + ```bash + python -m pip install huggingface_hub + ``` + + 2. Verwenden Sie die Funktion [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub), um eine Datei in einen bestimmten Pfad herunterzuladen. Der folgende Befehl lädt zum Beispiel die Datei "config.json" aus dem Modell [T0](https://huggingface.co/bigscience/T0_3B) in den gewünschten Pfad herunter: + + ```py + >>> from huggingface_hub import hf_hub_download + + >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") + ``` + +Sobald Ihre Datei heruntergeladen und lokal zwischengespeichert ist, geben Sie den lokalen Pfad an, um sie zu laden und zu verwenden: + +```py +>>> from transformers import AutoConfig + +>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") +``` + + + +Weitere Informationen zum Herunterladen von Dateien, die auf dem Hub gespeichert sind, finden Sie im Abschnitt [Wie man Dateien vom Hub herunterlädt](https://huggingface.co/docs/hub/how-to-downstream). + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/llm_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..ea4a96632cb1de97864c88a9107b262325c5618c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/llm_tutorial.md @@ -0,0 +1,221 @@ + + + +# Generation with LLMs + +[[open-in-colab]] + +LLMs (Large Language Models) sind die Schlüsselkomponente bei der Texterstellung. Kurz gesagt, bestehen sie aus großen, vortrainierten Transformationsmodellen, die darauf trainiert sind, das nächste Wort (oder genauer gesagt Token) aus einem Eingabetext vorherzusagen. Da sie jeweils ein Token vorhersagen, müssen Sie etwas Aufwändigeres tun, um neue Sätze zu generieren, als nur das Modell aufzurufen - Sie müssen eine autoregressive Generierung durchführen. + +Die autoregressive Generierung ist ein Verfahren zur Inferenzzeit, bei dem ein Modell mit seinen eigenen generierten Ausgaben iterativ aufgerufen wird, wenn einige anfängliche Eingaben vorliegen. In 🤗 Transformers wird dies von der Methode [`~generation.GenerationMixin.generate`] übernommen, die allen Modellen mit generativen Fähigkeiten zur Verfügung steht. + +Dieses Tutorial zeigt Ihnen, wie Sie: + +* Text mit einem LLM generieren +* Vermeiden Sie häufige Fallstricke +* Nächste Schritte, damit Sie das Beste aus Ihrem LLM herausholen können + +Bevor Sie beginnen, stellen Sie sicher, dass Sie alle erforderlichen Bibliotheken installiert haben: + +```bash +pip install transformers bitsandbytes>=0.39.0 -q +``` + + +## Text generieren + +Ein Sprachmodell, das für [causal language modeling](tasks/language_modeling) trainiert wurde, nimmt eine Folge von Text-Token als Eingabe und gibt die Wahrscheinlichkeitsverteilung für das nächste Token zurück. + + +
+ +
"Forward pass of an LLM"
+
+ +Ein wichtiger Aspekt der autoregressiven Generierung mit LLMs ist die Auswahl des nächsten Tokens aus dieser Wahrscheinlichkeitsverteilung. In diesem Schritt ist alles möglich, solange Sie am Ende ein Token für die nächste Iteration haben. Das heißt, es kann so einfach sein wie die Auswahl des wahrscheinlichsten Tokens aus der Wahrscheinlichkeitsverteilung oder so komplex wie die Anwendung von einem Dutzend Transformationen vor der Stichprobenziehung aus der resultierenden Verteilung. + + +
+ +
"Die autoregressive Generierung wählt iterativ das nächste Token aus einer Wahrscheinlichkeitsverteilung aus, um Text zu erzeugen"
+
+ +Der oben dargestellte Prozess wird iterativ wiederholt, bis eine bestimmte Abbruchbedingung erreicht ist. Im Idealfall wird die Abbruchbedingung vom Modell vorgegeben, das lernen sollte, wann es ein Ende-der-Sequenz-Token (EOS) ausgeben muss. Ist dies nicht der Fall, stoppt die Generierung, wenn eine vordefinierte Maximallänge erreicht ist. + +Damit sich Ihr Modell so verhält, wie Sie es für Ihre Aufgabe erwarten, müssen Sie den Schritt der Token-Auswahl und die Abbruchbedingung richtig einstellen. Aus diesem Grund haben wir zu jedem Modell eine [`~generation.GenerationConfig`]-Datei, die eine gute generative Standardparametrisierung enthält und zusammen mit Ihrem Modell geladen wird. + +Lassen Sie uns über Code sprechen! + + + +Wenn Sie an der grundlegenden Verwendung von LLMs interessiert sind, ist unsere High-Level-Schnittstelle [`Pipeline`](pipeline_tutorial) ein guter Ausgangspunkt. LLMs erfordern jedoch oft fortgeschrittene Funktionen wie Quantisierung und Feinsteuerung des Token-Auswahlschritts, was am besten über [`~generation.GenerationMixin.generate`] erfolgt. Die autoregressive Generierung mit LLMs ist ebenfalls ressourcenintensiv und sollte für einen angemessenen Durchsatz auf einer GPU ausgeführt werden. + + + + +Zunächst müssen Sie das Modell laden. + +```py +>>> from transformers import AutoModelForCausalLM + +>>> model = AutoModelForCausalLM.from_pretrained( +... "openlm-research/open_llama_7b", device_map="auto", load_in_4bit=True +... ) +``` + +Sie werden zwei Flags in dem Aufruf `from_pretrained` bemerken: + + - `device_map` stellt sicher, dass das Modell auf Ihre GPU(s) übertragen wird + - `load_in_4bit` wendet [dynamische 4-Bit-Quantisierung](main_classes/quantization) an, um die Ressourcenanforderungen massiv zu reduzieren + +Es gibt noch andere Möglichkeiten, ein Modell zu initialisieren, aber dies ist eine gute Grundlage, um mit einem LLM zu beginnen. + +Als nächstes müssen Sie Ihre Texteingabe mit einem [tokenizer](tokenizer_summary) vorverarbeiten. + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b") +>>> model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +Die Variable `model_inputs` enthält die tokenisierte Texteingabe sowie die Aufmerksamkeitsmaske. Obwohl [`~generation.GenerationMixin.generate`] sein Bestes tut, um die Aufmerksamkeitsmaske abzuleiten, wenn sie nicht übergeben wird, empfehlen wir, sie für optimale Ergebnisse wann immer möglich zu übergeben. + +Rufen Sie schließlich die Methode [`~generation.GenerationMixin.generate`] auf, um die generierten Token zurückzugeben, die vor dem Drucken in Text umgewandelt werden sollten. + +```py +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A list of colors: red, blue, green, yellow, black, white, and brown' +``` + +Und das war's! Mit ein paar Zeilen Code können Sie sich die Macht eines LLM zunutze machen. + + +## Häufige Fallstricke + +Es gibt viele [Generierungsstrategien](generation_strategies), und manchmal sind die Standardwerte für Ihren Anwendungsfall vielleicht nicht geeignet. Wenn Ihre Ausgaben nicht mit dem übereinstimmen, was Sie erwarten, haben wir eine Liste der häufigsten Fallstricke erstellt und wie Sie diese vermeiden können. + +```py +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b") +>>> tokenizer.pad_token = tokenizer.eos_token # Llama has no pad token by default +>>> model = AutoModelForCausalLM.from_pretrained( +... "openlm-research/open_llama_7b", device_map="auto", load_in_4bit=True +... ) +``` + +### Generierte Ausgabe ist zu kurz/lang + +Wenn in der Datei [`~generation.GenerationConfig`] nichts angegeben ist, gibt `generate` standardmäßig bis zu 20 Token zurück. Wir empfehlen dringend, `max_new_tokens` in Ihrem `generate`-Aufruf manuell zu setzen, um die maximale Anzahl neuer Token zu kontrollieren, die zurückgegeben werden können. Beachten Sie, dass LLMs (genauer gesagt, [decoder-only models](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)) auch die Eingabeaufforderung als Teil der Ausgabe zurückgeben. + + +```py +>>> model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") + +>>> # By default, the output will contain up to 20 tokens +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' + +>>> # Setting `max_new_tokens` allows you to control the maximum length +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=50) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + +### Falscher Generierungsmodus + +Standardmäßig und sofern nicht in der Datei [`~generation.GenerationConfig`] angegeben, wählt `generate` bei jeder Iteration das wahrscheinlichste Token aus (gierige Dekodierung). Je nach Aufgabe kann dies unerwünscht sein; kreative Aufgaben wie Chatbots oder das Schreiben eines Aufsatzes profitieren vom Sampling. Andererseits profitieren Aufgaben, bei denen es auf die Eingabe ankommt, wie z.B. Audiotranskription oder Übersetzung, von der gierigen Dekodierung. Aktivieren Sie das Sampling mit `do_sample=True`. Mehr zu diesem Thema erfahren Sie in diesem [Blogbeitrag](https://huggingface.co/blog/how-to-generate). + +```py +>>> # Set seed or reproducibility -- you don't need this unless you want full reproducibility +>>> from transformers import set_seed +>>> set_seed(0) + +>>> model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") + +>>> # LLM + greedy decoding = repetitive, boring output +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat. I am a cat. I am a cat. I am a cat' + +>>> # With sampling, the output becomes more creative! +>>> generated_ids = model.generate(**model_inputs, do_sample=True) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'I am a cat.\nI just need to be. I am always.\nEvery time' +``` + +### Falsche Auffüllseite + +LLMs sind [decoder-only](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)-Architekturen, d.h. sie iterieren weiter über Ihre Eingabeaufforderung. Wenn Ihre Eingaben nicht die gleiche Länge haben, müssen sie aufgefüllt werden. Da LLMs nicht darauf trainiert sind, mit aufgefüllten Token fortzufahren, muss Ihre Eingabe links aufgefüllt werden. Vergessen Sie auch nicht, die Aufmerksamkeitsmaske an generate zu übergeben! + +```py +>>> # The tokenizer initialized above has right-padding active by default: the 1st sequence, +>>> # which is shorter, has padding on the right side. Generation fails. +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids[0], skip_special_tokens=True)[0] +'' + +>>> # With left-padding, it works as expected! +>>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b", padding_side="left") +>>> tokenizer.pad_token = tokenizer.eos_token # Llama has no pad token by default +>>> model_inputs = tokenizer( +... ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +... ).to("cuda") +>>> generated_ids = model.generate(**model_inputs) +>>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + + + +## Weitere Ressourcen + +Während der Prozess der autoregressiven Generierung relativ einfach ist, kann die optimale Nutzung Ihres LLM ein schwieriges Unterfangen sein, da es viele bewegliche Teile gibt. Für Ihre nächsten Schritte, die Ihnen helfen, tiefer in die LLM-Nutzung und das Verständnis einzutauchen: + + +### Fortgeschrittene Nutzung generieren + +1. [Leitfaden](generation_strategies) zur Steuerung verschiedener Generierungsmethoden, zur Einrichtung der Generierungskonfigurationsdatei und zum Streaming der Ausgabe; +2. API-Referenz zu [`~generation.GenerationConfig`], [`~generation.GenerationMixin.generate`] und [generate-bezogene Klassen](internal/generation_utils). + +### LLM-Ranglisten + +1. [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), das sich auf die Qualität der Open-Source-Modelle konzentriert; +2. [Open LLM-Perf Leaderboard](https://huggingface.co/spaces/optimum/llm-perf-leaderboard), das sich auf den LLM-Durchsatz konzentriert. + +### Latenz und Durchsatz + +1. [Leitfaden](main_classes/quantization) zur dynamischen Quantisierung, der Ihnen zeigt, wie Sie Ihren Speicherbedarf drastisch reduzieren können. + +### Verwandte Bibliotheken + +1. [text-generation-inference](https://github.com/huggingface/text-generation-inference), ein produktionsreifer Server für LLMs; +2. [`optimum`](https://github.com/huggingface/optimum), eine Erweiterung von 🤗 Transformers, die für bestimmte Hardware-Geräte optimiert. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/model_sharing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/model_sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..850d9a3454a9c194d47989cf2e42bbb29f093642 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/model_sharing.md @@ -0,0 +1,232 @@ + + +# Ein Modell teilen + +Die letzten beiden Tutorials haben gezeigt, wie man ein Modell mit PyTorch, Keras und 🤗 Accelerate für verteilte Setups feinabstimmen kann. Der nächste Schritt besteht darin, Ihr Modell mit der Community zu teilen! Bei Hugging Face glauben wir an den offenen Austausch von Wissen und Ressourcen, um künstliche Intelligenz für alle zu demokratisieren. Wir ermutigen Sie, Ihr Modell mit der Community zu teilen, um anderen zu helfen, Zeit und Ressourcen zu sparen. + +In diesem Tutorial lernen Sie zwei Methoden kennen, wie Sie ein trainiertes oder verfeinertes Modell auf dem [Model Hub](https://huggingface.co/models) teilen können: + +- Programmgesteuertes Übertragen Ihrer Dateien auf den Hub. +- Ziehen Sie Ihre Dateien per Drag-and-Drop über die Weboberfläche in den Hub. + + + + + +Um ein Modell mit der Öffentlichkeit zu teilen, benötigen Sie ein Konto auf [huggingface.co](https://huggingface.co/join). Sie können auch einer bestehenden Organisation beitreten oder eine neue Organisation gründen. + + + +## Repository-Funktionen + +Jedes Repository im Model Hub verhält sich wie ein typisches GitHub-Repository. Unsere Repositorys bieten Versionierung, Commit-Historie und die Möglichkeit, Unterschiede zu visualisieren. + +Die integrierte Versionierung des Model Hub basiert auf Git und [git-lfs](https://git-lfs.github.com/). Mit anderen Worten: Sie können ein Modell als ein Repository behandeln, was eine bessere Zugriffskontrolle und Skalierbarkeit ermöglicht. Die Versionskontrolle ermöglicht *Revisionen*, eine Methode zum Anheften einer bestimmten Version eines Modells mit einem Commit-Hash, Tag oder Branch. + +Folglich können Sie eine bestimmte Modellversion mit dem Parameter "Revision" laden: + +```py +>>> model = AutoModel.from_pretrained( +... "julien-c/EsperBERTo-small", revision="4c77982" # tag name, or branch name, or commit hash +... ) +``` + +Dateien lassen sich auch in einem Repository leicht bearbeiten, und Sie können die Commit-Historie sowie die Unterschiede einsehen: + +![vis_diff](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vis_diff.png) + +## Einrichtung + +Bevor Sie ein Modell für den Hub freigeben, benötigen Sie Ihre Hugging Face-Anmeldedaten. Wenn Sie Zugang zu einem Terminal haben, führen Sie den folgenden Befehl in der virtuellen Umgebung aus, in der 🤗 Transformers installiert ist. Dadurch werden Ihre Zugangsdaten in Ihrem Hugging Face-Cache-Ordner (standardmäßig `~/.cache/`) gespeichert: + +```bash +huggingface-cli login +``` + +Wenn Sie ein Notebook wie Jupyter oder Colaboratory verwenden, stellen Sie sicher, dass Sie die [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) Bibliothek installiert haben. Diese Bibliothek ermöglicht Ihnen die programmatische Interaktion mit dem Hub. + +```bash +pip install huggingface_hub +``` + +Verwenden Sie dann `notebook_login`, um sich beim Hub anzumelden, und folgen Sie dem Link [hier](https://huggingface.co/settings/token), um ein Token für die Anmeldung zu generieren: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## Ein Modell für alle Frameworks konvertieren + +Um sicherzustellen, dass Ihr Modell von jemandem verwendet werden kann, der mit einem anderen Framework arbeitet, empfehlen wir Ihnen, Ihr Modell sowohl mit PyTorch- als auch mit TensorFlow-Checkpoints zu konvertieren und hochzuladen. Während Benutzer immer noch in der Lage sind, Ihr Modell von einem anderen Framework zu laden, wenn Sie diesen Schritt überspringen, wird es langsamer sein, weil 🤗 Transformers den Checkpoint on-the-fly konvertieren müssen. + +Die Konvertierung eines Checkpoints für ein anderes Framework ist einfach. Stellen Sie sicher, dass Sie PyTorch und TensorFlow installiert haben (siehe [hier](installation) für Installationsanweisungen), und finden Sie dann das spezifische Modell für Ihre Aufgabe in dem anderen Framework. + + + +Geben Sie `from_tf=True` an, um einen Prüfpunkt von TensorFlow nach PyTorch zu konvertieren: + +```py +>>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True) +>>> pt_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +Geben Sie `from_pt=True` an, um einen Prüfpunkt von PyTorch nach TensorFlow zu konvertieren: + +```py +>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True) +``` + +Dann können Sie Ihr neues TensorFlow-Modell mit seinem neuen Checkpoint speichern: + +```py +>>> tf_model.save_pretrained("path/to/awesome-name-you-picked") +``` + + +Wenn ein Modell in Flax verfügbar ist, können Sie auch einen Kontrollpunkt von PyTorch nach Flax konvertieren: + +```py +>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained( +... "path/to/awesome-name-you-picked", from_pt=True +... ) +``` + + + +## Ein Modell während des Trainings hochladen + + + + + +Die Weitergabe eines Modells an den Hub ist so einfach wie das Hinzufügen eines zusätzlichen Parameters oder Rückrufs. Erinnern Sie sich an das [Feinabstimmungs-Tutorial](training), in der Klasse [`TrainingArguments`] geben Sie Hyperparameter und zusätzliche Trainingsoptionen an. Eine dieser Trainingsoptionen beinhaltet die Möglichkeit, ein Modell direkt an den Hub zu pushen. Setzen Sie `push_to_hub=True` in Ihrer [`TrainingArguments`]: + +```py +>>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True) +``` + +Übergeben Sie Ihre Trainingsargumente wie gewohnt an [`Trainer`]: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +Nach der Feinabstimmung Ihres Modells rufen Sie [`~transformers.Trainer.push_to_hub`] auf [`Trainer`] auf, um das trainierte Modell an den Hub zu übertragen. Transformers fügt sogar automatisch Trainings-Hyperparameter, Trainingsergebnisse und Framework-Versionen zu Ihrer Modellkarte hinzu! + +```py +>>> trainer.push_to_hub() +``` + + +Geben Sie ein Modell mit [`PushToHubCallback`] an den Hub weiter. In der [`PushToHubCallback`] Funktion, fügen Sie hinzu: + +- Ein Ausgabeverzeichnis für Ihr Modell. +- Einen Tokenizer. +- Die `hub_model_id`, die Ihr Hub-Benutzername und Modellname ist. + +```py +>>> from transformers import PushToHubCallback + +>>> push_to_hub_callback = PushToHubCallback( +... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model" +... ) +``` + +Fügen Sie den Callback zu [`fit`](https://keras.io/api/models/model_training_apis/) hinzu, und 🤗 Transformers wird das trainierte Modell an den Hub weiterleiten: + +```py +>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback) +``` + + + +## Verwenden Sie die Funktion `push_to_hub`. + +Sie können `push_to_hub` auch direkt für Ihr Modell aufrufen, um es in den Hub hochzuladen. + +Geben Sie den Namen Ihres Modells in "push_to_hub" an: + +```py +>>> pt_model.push_to_hub("my-awesome-model") +``` + +Dadurch wird ein Repository unter Ihrem Benutzernamen mit dem Modellnamen `my-awesome-model` erstellt. Benutzer können nun Ihr Modell mit der Funktion `from_pretrained` laden: + +```py +>>> from transformers import AutoModel + +>>> model = AutoModel.from_pretrained("your_username/my-awesome-model") +``` + +Wenn Sie zu einer Organisation gehören und Ihr Modell stattdessen unter dem Namen der Organisation pushen wollen, fügen Sie diesen einfach zur `repo_id` hinzu: + +```py +>>> pt_model.push_to_hub("my-awesome-org/my-awesome-model") +``` + +Die Funktion "push_to_hub" kann auch verwendet werden, um andere Dateien zu einem Modell-Repository hinzuzufügen. Zum Beispiel kann man einen Tokenizer zu einem Modell-Repository hinzufügen: + +```py +>>> tokenizer.push_to_hub("my-awesome-model") +``` + +Oder vielleicht möchten Sie die TensorFlow-Version Ihres fein abgestimmten PyTorch-Modells hinzufügen: + +```py +>>> tf_model.push_to_hub("my-awesome-model") +``` + +Wenn Sie nun zu Ihrem Hugging Face-Profil navigieren, sollten Sie Ihr neu erstelltes Modell-Repository sehen. Wenn Sie auf die Registerkarte **Dateien** klicken, werden alle Dateien angezeigt, die Sie in das Repository hochgeladen haben. + +Weitere Einzelheiten zum Erstellen und Hochladen von Dateien in ein Repository finden Sie in der Hub-Dokumentation [hier](https://huggingface.co/docs/hub/how-to-upstream). + +## Hochladen mit der Weboberfläche + +Benutzer, die einen no-code Ansatz bevorzugen, können ein Modell über das Webinterface des Hubs hochladen. Besuchen Sie [huggingface.co/new](https://huggingface.co/new) um ein neues Repository zu erstellen: + +![new_model_repo](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/new_model_repo.png) + +Fügen Sie von hier aus einige Informationen über Ihr Modell hinzu: + +- Wählen Sie den **Besitzer** des Repositorys. Dies können Sie selbst oder eine der Organisationen sein, denen Sie angehören. +- Wählen Sie einen Namen für Ihr Modell, der auch der Name des Repositorys sein wird. +- Wählen Sie, ob Ihr Modell öffentlich oder privat ist. +- Geben Sie die Lizenzverwendung für Ihr Modell an. + +Klicken Sie nun auf die Registerkarte **Dateien** und klicken Sie auf die Schaltfläche **Datei hinzufügen**, um eine neue Datei in Ihr Repository hochzuladen. Ziehen Sie dann eine Datei per Drag-and-Drop hoch und fügen Sie eine Übergabemeldung hinzu. + +![upload_file](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/upload_file.png) + +## Hinzufügen einer Modellkarte + +Um sicherzustellen, dass die Benutzer die Fähigkeiten, Grenzen, möglichen Verzerrungen und ethischen Aspekte Ihres Modells verstehen, fügen Sie bitte eine Modellkarte zu Ihrem Repository hinzu. Die Modellkarte wird in der Datei `README.md` definiert. Sie können eine Modellkarte hinzufügen, indem Sie: + +* Manuelles Erstellen und Hochladen einer "README.md"-Datei. +* Klicken Sie auf die Schaltfläche **Modellkarte bearbeiten** in Ihrem Modell-Repository. + +Werfen Sie einen Blick auf die DistilBert [model card](https://huggingface.co/distilbert/distilbert-base-uncased) als gutes Beispiel für die Art von Informationen, die eine Modellkarte enthalten sollte. Weitere Details über andere Optionen, die Sie in der Datei "README.md" einstellen können, wie z.B. den Kohlenstoff-Fußabdruck eines Modells oder Beispiele für Widgets, finden Sie in der Dokumentation [hier](https://huggingface.co/docs/hub/models-cards). \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/peft.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..eda8ce9435a0556a7bcbd9cdf432d8fc23fe67eb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/peft.md @@ -0,0 +1,216 @@ + + +# Adapter mit 🤗 PEFT laden + +[[open-in-colab]] + +Die [Parameter-Efficient Fine Tuning (PEFT)](https://huggingface.co/blog/peft) Methoden frieren die vorab trainierten Modellparameter während der Feinabstimmung ein und fügen eine kleine Anzahl trainierbarer Parameter (die Adapter) hinzu. Die Adapter werden trainiert, um aufgabenspezifische Informationen zu lernen. Es hat sich gezeigt, dass dieser Ansatz sehr speichereffizient ist und weniger Rechenleistung beansprucht, während die Ergebnisse mit denen eines vollständig feinabgestimmten Modells vergleichbar sind. + +Adapter, die mit PEFT trainiert wurden, sind in der Regel um eine Größenordnung kleiner als das vollständige Modell, so dass sie bequem gemeinsam genutzt, gespeichert und geladen werden können. + +
+ +
Die Adaptergewichte für ein OPTForCausalLM-Modell, die auf dem Hub gespeichert sind, sind nur ~6MB groß, verglichen mit der vollen Größe der Modellgewichte, die ~700MB betragen können.
+
+ +Wenn Sie mehr über die 🤗 PEFT-Bibliothek erfahren möchten, sehen Sie sich die [Dokumentation](https://huggingface.co/docs/peft/index) an. + +## Setup + +Starten Sie mit der Installation von 🤗 PEFT: + +```bash +pip install peft +``` + +Wenn Sie die brandneuen Funktionen ausprobieren möchten, sollten Sie die Bibliothek aus dem Quellcode installieren: + +```bash +pip install git+https://github.com/huggingface/peft.git +``` + +## Unterstützte PEFT-Modelle + +Transformers unterstützt nativ einige PEFT-Methoden, d.h. Sie können lokal oder auf dem Hub gespeicherte Adaptergewichte laden und sie mit wenigen Zeilen Code einfach ausführen oder trainieren. Die folgenden Methoden werden unterstützt: + +- [Low Rank Adapters](https://huggingface.co/docs/peft/conceptual_guides/lora) +- [IA3](https://huggingface.co/docs/peft/conceptual_guides/ia3) +- [AdaLoRA](https://arxiv.org/abs/2303.10512) + +Wenn Sie andere PEFT-Methoden, wie z.B. Prompt Learning oder Prompt Tuning, verwenden möchten, oder über die 🤗 PEFT-Bibliothek im Allgemeinen, lesen Sie bitte die [Dokumentation](https://huggingface.co/docs/peft/index). + + +## Laden Sie einen PEFT-Adapter + +Um ein PEFT-Adaptermodell von 🤗 Transformers zu laden und zu verwenden, stellen Sie sicher, dass das Hub-Repository oder das lokale Verzeichnis eine `adapter_config.json`-Datei und die Adaptergewichte enthält, wie im obigen Beispielbild gezeigt. Dann können Sie das PEFT-Adaptermodell mit der Klasse `AutoModelFor` laden. Um zum Beispiel ein PEFT-Adaptermodell für die kausale Sprachmodellierung zu laden: + +1. Geben Sie die PEFT-Modell-ID an. +2. übergeben Sie es an die Klasse [`AutoModelForCausalLM`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id) +``` + + + +Sie können einen PEFT-Adapter entweder mit einer `AutoModelFor`-Klasse oder der Basismodellklasse wie `OPTForCausalLM` oder `LlamaForCausalLM` laden. + + + +Sie können einen PEFT-Adapter auch laden, indem Sie die Methode `load_adapter` aufrufen: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "facebook/opt-350m" +peft_model_id = "ybelkada/opt-350m-lora" + +model = AutoModelForCausalLM.from_pretrained(model_id) +model.load_adapter(peft_model_id) +``` + +## Laden in 8bit oder 4bit + +Die `bitsandbytes`-Integration unterstützt Datentypen mit 8bit und 4bit Genauigkeit, was für das Laden großer Modelle nützlich ist, weil es Speicher spart (lesen Sie den `bitsandbytes`-Integrations [guide](./quantization#bitsandbytes-integration), um mehr zu erfahren). Fügen Sie die Parameter `load_in_8bit` oder `load_in_4bit` zu [`~PreTrainedModel.from_pretrained`] hinzu und setzen Sie `device_map="auto"`, um das Modell effektiv auf Ihre Hardware zu verteilen: + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +peft_model_id = "ybelkada/opt-350m-lora" +model = AutoModelForCausalLM.from_pretrained(peft_model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True)) +``` + +## Einen neuen Adapter hinzufügen + +Sie können [`~peft.PeftModel.add_adapter`] verwenden, um einen neuen Adapter zu einem Modell mit einem bestehenden Adapter hinzuzufügen, solange der neue Adapter vom gleichen Typ ist wie der aktuelle Adapter. Wenn Sie zum Beispiel einen bestehenden LoRA-Adapter an ein Modell angehängt haben: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +model = AutoModelForCausalLM.from_pretrained(model_id) + +lora_config = LoraConfig( + target_modules=["q_proj", "k_proj"], + init_lora_weights=False +) + +model.add_adapter(lora_config, adapter_name="adapter_1") +``` + +Um einen neuen Adapter hinzuzufügen: + +```py +# attach new adapter with same config +model.add_adapter(lora_config, adapter_name="adapter_2") +``` + +Jetzt können Sie mit [`~peft.PeftModel.set_adapter`] festlegen, welcher Adapter verwendet werden soll: + +```py +# use adapter_1 +model.set_adapter("adapter_1") +output = model.generate(**inputs) +print(tokenizer.decode(output_disabled[0], skip_special_tokens=True)) + +# use adapter_2 +model.set_adapter("adapter_2") +output_enabled = model.generate(**inputs) +print(tokenizer.decode(output_enabled[0], skip_special_tokens=True)) +``` + +## Aktivieren und Deaktivieren von Adaptern + +Sobald Sie einen Adapter zu einem Modell hinzugefügt haben, können Sie das Adaptermodul aktivieren oder deaktivieren. So aktivieren Sie das Adaptermodul: + +```py +from transformers import AutoModelForCausalLM, OPTForCausalLM, AutoTokenizer +from peft import PeftConfig + +model_id = "facebook/opt-350m" +adapter_model_id = "ybelkada/opt-350m-lora" +tokenizer = AutoTokenizer.from_pretrained(model_id) +text = "Hello" +inputs = tokenizer(text, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(model_id) +peft_config = PeftConfig.from_pretrained(adapter_model_id) + +# to initiate with random weights +peft_config.init_lora_weights = False + +model.add_adapter(peft_config) +model.enable_adapters() +output = model.generate(**inputs) +``` + +So deaktivieren Sie das Adaptermodul: + +```py +model.disable_adapters() +output = model.generate(**inputs) +``` + +## PEFT-Adapter trainieren + +PEFT-Adapter werden von der Klasse [`Trainer`] unterstützt, so dass Sie einen Adapter für Ihren speziellen Anwendungsfall trainieren können. Dazu müssen Sie nur ein paar weitere Codezeilen hinzufügen. Zum Beispiel, um einen LoRA-Adapter zu trainieren: + + + +Wenn Sie mit der Feinabstimmung eines Modells mit [`Trainer`] noch nicht vertraut sind, werfen Sie einen Blick auf das Tutorial [Feinabstimmung eines vortrainierten Modells](Training). + + + +1. Definieren Sie Ihre Adapterkonfiguration mit dem Aufgabentyp und den Hyperparametern (siehe [`~peft.LoraConfig`] für weitere Details darüber, was die Hyperparameter tun). + +```py +from peft import LoraConfig + +peft_config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=64, + bias="none", + task_type="CAUSAL_LM", +) +``` + +2. Fügen Sie dem Modell einen Adapter hinzu. + +```py +model.add_adapter(peft_config) +``` + +3. Jetzt können Sie das Modell an [`Trainer`] übergeben! + +```py +trainer = Trainer(model=model, ...) +trainer.train() +``` + +So speichern Sie Ihren trainierten Adapter und laden ihn wieder: + +```py +model.save_pretrained(save_dir) +model = AutoModelForCausalLM.from_pretrained(save_dir) +``` + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pipeline_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pipeline_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..5106af9b2fafc76564f8e895c53d3b8146e45aeb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pipeline_tutorial.md @@ -0,0 +1,175 @@ + + +# Pipelines für Inferenzen + +Die [`pipeline`] macht es einfach, jedes beliebige Modell aus dem [Hub](https://huggingface.co/models) für die Inferenz auf jede Sprache, Computer Vision, Sprache und multimodale Aufgaben zu verwenden. Selbst wenn Sie keine Erfahrung mit einer bestimmten Modalität haben oder nicht mit dem zugrundeliegenden Code hinter den Modellen vertraut sind, können Sie sie mit der [`pipeline`] für Inferenzen verwenden! In diesem Beispiel lernen Sie, wie: + +* Eine [`pipeline`] für Inferenz zu verwenden. +* Einen bestimmten Tokenizer oder ein bestimmtes Modell zu verwenden. +* Eine [`pipeline`] für Audio-, Vision- und multimodale Aufgaben zu verwenden. + + + +Eine vollständige Liste der unterstützten Aufgaben und verfügbaren Parameter finden Sie in der [`pipeline`]-Dokumentation. + + + +## Verwendung von Pipelines + +Obwohl jede Aufgabe eine zugehörige [`pipeline`] hat, ist es einfacher, die allgemeine [`pipeline`]-Abstraktion zu verwenden, die alle aufgabenspezifischen Pipelines enthält. Die [`pipeline`] lädt automatisch ein Standardmodell und eine Vorverarbeitungsklasse, die für Ihre Aufgabe inferenzfähig ist. + +1. Beginnen Sie mit der Erstellung einer [`pipeline`] und geben Sie eine Inferenzaufgabe an: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline(task="text-generation") +``` + +2. Übergeben Sie Ihren Eingabetext an die [`pipeline`]: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone" +... ) # doctest: +SKIP +[{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Iron-priests at the door to the east, and thirteen for the Lord Kings at the end of the mountain'}] +``` + +Wenn Sie mehr als eine Eingabe haben, übergeben Sie die Eingabe als Liste: + +```py +>>> generator( +... [ +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", +... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne", +... ] +... ) # doctest: +SKIP +``` + +Alle zusätzlichen Parameter für Ihre Aufgabe können auch in die [`pipeline`] aufgenommen werden. Die Aufgabe `Text-Generierung` hat eine [`~generation.GenerationMixin.generate`]-Methode mit mehreren Parametern zur Steuerung der Ausgabe. Wenn Sie zum Beispiel mehr als eine Ausgabe erzeugen wollen, setzen Sie den Parameter `num_return_sequences`: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone", +... num_return_sequences=2, +... ) # doctest: +SKIP +``` + +### Wählen Sie ein Modell und einen Tokenizer + +Die [`pipeline`] akzeptiert jedes Modell aus dem [Hub](https://huggingface.co/models). Auf dem Hub gibt es Tags, mit denen Sie nach einem Modell filtern können, das Sie für Ihre Aufgabe verwenden möchten. Sobald Sie ein passendes Modell ausgewählt haben, laden Sie es mit der entsprechenden `AutoModelFor` und [`AutoTokenizer`] Klasse. Laden Sie zum Beispiel die Klasse [`AutoModelForCausalLM`] für eine kausale Sprachmodellierungsaufgabe: + +```py +>>> from transformers import AutoTokenizer, AutoModelForCausalLM + +>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") +>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") +``` + +Erstellen Sie eine [`pipeline`] für Ihre Aufgabe, und geben Sie das Modell und den Tokenizer an, die Sie geladen haben: + +```py +>>> from transformers import pipeline + +>>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer) +``` + +Übergeben Sie Ihren Eingabetext an die [`pipeline`] , um einen Text zu erzeugen: + +```py +>>> generator( +... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone" +... ) # doctest: +SKIP +[{'generated_text': 'Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone, Seven for the Dragon-lords (for them to rule in a world ruled by their rulers, and all who live within the realm'}] +``` + +## Audio-Pipeline + +Die [`pipeline`] unterstützt auch Audioaufgaben wie Audioklassifizierung und automatische Spracherkennung. + +Lassen Sie uns zum Beispiel die Emotion in diesem Audioclip klassifizieren: + +```py +>>> from datasets import load_dataset +>>> import torch + +>>> torch.manual_seed(42) # doctest: +IGNORE_RESULT +>>> ds = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") +>>> audio_file = ds[0]["audio"]["path"] +``` + +Finden Sie ein [Audioklassifikation](https://huggingface.co/models?pipeline_tag=audio-classification) Modell auf dem Model Hub für Emotionserkennung und laden Sie es in die [`pipeline`]: + +```py +>>> from transformers import pipeline + +>>> audio_classifier = pipeline( +... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition" +... ) +``` + +Übergeben Sie die Audiodatei an die [`pipeline`]: + +```py +>>> preds = audio_classifier(audio_file) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.1315, 'label': 'calm'}, {'score': 0.1307, 'label': 'neutral'}, {'score': 0.1274, 'label': 'sad'}, {'score': 0.1261, 'label': 'fearful'}, {'score': 0.1242, 'label': 'happy'}] +``` + +## Bildverarbeitungs-Pipeline + +Die Verwendung einer [`pipeline`] für Bildverarbeitungsaufgaben ist praktisch identisch. + +Geben Sie Ihre Aufgabe an und übergeben Sie Ihr Bild an den Klassifikator. Das Bild kann ein Link oder ein lokaler Pfad zu dem Bild sein. Zum Beispiel: Welche Katzenart ist unten abgebildet? + +![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) + +```py +>>> from transformers import pipeline + +>>> vision_classifier = pipeline(task="image-classification") +>>> preds = vision_classifier( +... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +... ) +>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] +>>> preds +[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}] +``` + +## Multimodale Pipeline + +Die [`pipeline`] unterstützt mehr als eine Modalität. Eine Aufgabe zur Beantwortung visueller Fragen (VQA) kombiniert zum Beispiel Text und Bild. Verwenden Sie einen beliebigen Bildlink und eine Frage, die Sie zu dem Bild stellen möchten. Das Bild kann eine URL oder ein lokaler Pfad zu dem Bild sein. + +Wenn Sie zum Beispiel das gleiche Bild wie in der obigen Vision-Pipeline verwenden: + +```py +>>> image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" +>>> question = "Where is the cat?" +``` + +Erstellen Sie eine Pipeline für "vqa" und übergeben Sie ihr das Bild und die Frage: + +```py +>>> from transformers import pipeline + +>>> vqa = pipeline(task="vqa") +>>> preds = vqa(image=image, question=question) +>>> preds = [{"score": round(pred["score"], 4), "answer": pred["answer"]} for pred in preds] +>>> preds +[{'score': 0.9112, 'answer': 'snow'}, {'score': 0.8796, 'answer': 'in snow'}, {'score': 0.6717, 'answer': 'outside'}, {'score': 0.0291, 'answer': 'on ground'}, {'score': 0.027, 'answer': 'ground'}] +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pr_checks.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pr_checks.md new file mode 100644 index 0000000000000000000000000000000000000000..ee2bbf489b8e7535f277e6f95ab7062c2e52020c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/pr_checks.md @@ -0,0 +1,199 @@ + + +# Überprüfungen bei einer Pull-Anfrage + +Wenn Sie eine Pull-Anfrage für 🤗 Transformers öffnen, wird eine ganze Reihe von Prüfungen durchgeführt, um sicherzustellen, dass der Patch, den Sie hinzufügen, nichts Bestehendes zerstört. Es gibt vier Arten von Prüfungen: +- reguläre Tests +- Erstellung der Dokumentation +- Stil von Code und Dokumentation +- allgemeine Konsistenz des Repository + +In diesem Dokument werden wir versuchen zu erklären, worum es sich bei diesen verschiedenen Prüfungen handelt und wie Sie sie lokal debuggen können, wenn eine der Prüfungen in Ihrer PR fehlschlägt. + +Beachten Sie, dass Sie im Idealfall eine Dev-Installation benötigen: + +```bash +pip install transformers[dev] +``` + +oder für eine bearbeitbare Installation: + +```bash +pip install -e .[dev] +``` + +innerhalb des Transformers Repo. Da die Anzahl der optionalen Abhängigkeiten von Transformers stark zugenommen hat, ist es möglich, dass Sie nicht alle davon bekommen können. Wenn die Dev-Installation fehlschlägt, stellen Sie sicher, dass Sie das Deep Learning-Framework, mit dem Sie arbeiten, installieren (PyTorch, TensorFlow und/oder Flax). + +```bash +pip install transformers[quality] +``` + +oder für eine bearbeitbare Installation: + +```bash +pip install -e .[quality] +``` + + +## Tests + +Alle Jobs, die mit `ci/circleci: run_tests_` beginnen, führen Teile der Transformers-Testsuite aus. Jeder dieser Jobs konzentriert sich auf einen Teil der Bibliothek in einer bestimmten Umgebung: `ci/circleci: run_tests_pipelines_tf` zum Beispiel führt den Pipelines-Test in einer Umgebung aus, in der nur TensorFlow installiert ist. + +Beachten Sie, dass nur ein Teil der Testsuite jedes Mal ausgeführt wird, um zu vermeiden, dass Tests ausgeführt werden, wenn es keine wirkliche Änderung in den Modulen gibt, die sie testen: ein Dienstprogramm wird ausgeführt, um die Unterschiede in der Bibliothek zwischen vor und nach dem PR zu ermitteln (was GitHub Ihnen auf der Registerkarte "Files changes" anzeigt) und die Tests auszuwählen, die von diesem Unterschied betroffen sind. Dieses Dienstprogramm kann lokal mit ausgeführt werden: + +```bash +python utils/tests_fetcher.py +``` + +aus dem Stammverzeichnis des Transformers-Repositoriums. Es wird: + +1. Überprüfen Sie für jede Datei im Diff, ob die Änderungen im Code oder nur in Kommentaren oder Docstrings enthalten sind. Nur die Dateien mit echten Codeänderungen werden beibehalten. +2. Erstellen Sie eine interne Map, die für jede Datei des Quellcodes der Bibliothek alle Dateien angibt, auf die sie rekursiv Einfluss nimmt. Von Modul A wird gesagt, dass es sich auf Modul B auswirkt, wenn Modul B Modul A importiert. Für die rekursive Auswirkung benötigen wir eine Kette von Modulen, die von Modul A zu Modul B führt und in der jedes Modul das vorherige importiert. +3. Wenden Sie diese Zuordnung auf die in Schritt 1 gesammelten Dateien an. So erhalten wir die Liste der Modelldateien, die von der PR betroffen sind. +4. Ordnen Sie jede dieser Dateien der/den entsprechenden Testdatei(en) zu und erhalten Sie die Liste der auszuführenden Tests. + +Wenn Sie das Skript lokal ausführen, sollten Sie die Ergebnisse von Schritt 1, 3 und 4 ausgegeben bekommen und somit wissen, welche Tests ausgeführt werden. Das Skript erstellt außerdem eine Datei namens `test_list.txt`, die die Liste der auszuführenden Tests enthält, die Sie mit dem folgenden Befehl lokal ausführen können: + +```bash +python -m pytest -n 8 --dist=loadfile -rA -s $(cat test_list.txt) +``` + +Für den Fall, dass Ihnen etwas entgangen ist, wird die komplette Testreihe ebenfalls täglich ausgeführt. + +## Dokumentation erstellen + +Der Job `build_pr_documentation` erstellt und generiert eine Vorschau der Dokumentation, um sicherzustellen, dass alles in Ordnung ist, wenn Ihr PR zusammengeführt wird. Ein Bot fügt einen Link zur Vorschau der Dokumentation zu Ihrem PR hinzu. Alle Änderungen, die Sie an dem PR vornehmen, werden automatisch in der Vorschau aktualisiert. Wenn die Dokumentation nicht erstellt werden kann, klicken Sie auf **Details** neben dem fehlgeschlagenen Auftrag, um zu sehen, wo der Fehler liegt. Oft ist der Fehler so einfach wie eine fehlende Datei im `toctree`. + +Wenn Sie daran interessiert sind, die Dokumentation lokal zu erstellen oder in der Vorschau anzusehen, werfen Sie einen Blick in die [`README.md`](https://github.com/huggingface/transformers/tree/main/docs) im Ordner docs. + +## Code und Dokumentationsstil + +Die Formatierung des Codes erfolgt für alle Quelldateien, die Beispiele und die Tests mit `black` und `ruff`. Wir haben auch ein benutzerdefiniertes Tool, das sich um die Formatierung von docstrings und `rst`-Dateien kümmert (`utils/style_doc.py`), sowie um die Reihenfolge der Lazy-Importe, die in den Transformers `__init__.py`-Dateien durchgeführt werden (`utils/custom_init_isort.py`). All dies können Sie starten, indem Sie Folgendes ausführen + +```bash +make style +``` + +Das CI prüft, ob diese innerhalb der Prüfung `ci/circleci: check_code_quality` angewendet wurden. Es führt auch `ruff` aus, das einen grundlegenden Blick auf Ihren Code wirft und sich beschwert, wenn es eine undefinierte Variable findet oder eine, die nicht verwendet wird. Um diese Prüfung lokal auszuführen, verwenden Sie + +```bash +make quality +``` + +Dies kann sehr viel Zeit in Anspruch nehmen. Um dasselbe nur für die Dateien zu tun, die Sie im aktuellen Zweig geändert haben, führen Sie + +```bash +make fixup +``` + +Dieser letzte Befehl führt auch alle zusätzlichen Prüfungen für die Konsistenz des Repositorys durch. Schauen wir uns diese an. + +## Repository-Konsistenz + +Dies fasst alle Tests zusammen, die sicherstellen, dass Ihr PR das Repository in einem guten Zustand verlässt. Sie können diese Prüfung lokal durchführen, indem Sie Folgendes ausführen: + +```bash +make repo-consistency +``` + +Dies überprüft, ob: + +- Alle zum Init hinzugefügten Objekte sind dokumentiert (ausgeführt von `utils/check_repo.py`) +- Alle `__init__.py`-Dateien haben in ihren beiden Abschnitten den gleichen Inhalt (ausgeführt von `utils/check_inits.py`) +- Der gesamte Code, der als Kopie eines anderen Moduls identifiziert wurde, stimmt mit dem Original überein (ausgeführt von `utils/check_copies.py`) +- Alle Konfigurationsklassen haben mindestens einen gültigen Prüfpunkt, der in ihren Dokumentationen erwähnt wird (ausgeführt von `utils/check_config_docstrings.py`) +- Alle Konfigurationsklassen enthalten nur Attribute, die in den entsprechenden Modellierungsdateien verwendet werden (ausgeführt von `utils/check_config_attributes.py`) +- Die Übersetzungen der READMEs und der Index des Dokuments haben die gleiche Modellliste wie die Haupt-README (durchgeführt von `utils/check_copies.py`) +- Die automatisch generierten Tabellen in der Dokumentation sind auf dem neuesten Stand (ausgeführt von `utils/check_table.py`) +- Die Bibliothek verfügt über alle Objekte, auch wenn nicht alle optionalen Abhängigkeiten installiert sind (ausgeführt von `utils/check_dummies.py`) + +Sollte diese Prüfung fehlschlagen, müssen die ersten beiden Punkte manuell korrigiert werden, die letzten vier können automatisch für Sie korrigiert werden, indem Sie den Befehl + +```bash +make fix-copies +``` + +Zusätzliche Prüfungen betreffen PRs, die neue Modelle hinzufügen, vor allem, dass: + +- Alle hinzugefügten Modelle befinden sich in einer Auto-Zuordnung (durchgeführt von `utils/check_repo.py`) + +- Alle Modelle werden ordnungsgemäß getestet (ausgeführt von `utils/check_repo.py`) + + + +### Kopien prüfen + +Da die Transformers-Bibliothek in Bezug auf den Modellcode sehr eigenwillig ist und jedes Modell vollständig in einer einzigen Datei implementiert sein sollte, ohne sich auf andere Modelle zu stützen, haben wir einen Mechanismus hinzugefügt, der überprüft, ob eine Kopie des Codes einer Ebene eines bestimmten Modells mit dem Original übereinstimmt. Auf diese Weise können wir bei einer Fehlerbehebung alle anderen betroffenen Modelle sehen und entscheiden, ob wir die Änderung weitergeben oder die Kopie zerstören. + + + +Wenn eine Datei eine vollständige Kopie einer anderen Datei ist, sollten Sie sie in der Konstante `FULL_COPIES` von `utils/check_copies.py` registrieren. + + + +Dieser Mechanismus stützt sich auf Kommentare der Form `# Kopiert von xxx`. Das `xxx` sollte den gesamten Pfad zu der Klasse der Funktion enthalten, die darunter kopiert wird. Zum Beispiel ist `RobertaSelfOutput` eine direkte Kopie der Klasse `BertSelfOutput`. Sie können also [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L289) sehen, dass sie einen Kommentar hat: + +```py +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +``` + +Beachten Sie, dass Sie dies nicht auf eine ganze Klasse anwenden, sondern auf die entsprechenden Methoden, von denen kopiert wird. Zum Beispiel [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L598) können Sie sehen, wie `RobertaPreTrainedModel._init_weights` von der gleichen Methode in `BertPreTrainedModel` mit dem Kommentar kopiert wird: + +```py +# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights +``` + +Manchmal ist die Kopie bis auf die Namen genau gleich: zum Beispiel verwenden wir in `RobertaAttention` `RobertaSelfAttention` anstelle von `BertSelfAttention`, aber ansonsten ist der Code genau derselbe. Aus diesem Grund unterstützt `#Copied from` einfache String-Ersetzungen mit der folgenden Syntax: `Kopiert von xxx mit foo->bar`. Das bedeutet, dass der Code kopiert wird, wobei alle Instanzen von "foo" durch "bar" ersetzt werden. Sie können sehen, wie es [hier](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L304C1-L304C86) in `RobertaAttention` mit dem Kommentar verwendet wird: + +```py +# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta +``` + +Beachten Sie, dass um den Pfeil herum keine Leerzeichen stehen sollten (es sei denn, das Leerzeichen ist Teil des zu ersetzenden Musters, natürlich). + +Sie können mehrere Muster durch ein Komma getrennt hinzufügen. Zum Beispiel ist hier `CamemberForMaskedLM` eine direkte Kopie von `RobertaForMaskedLM` mit zwei Ersetzungen: `Roberta` zu `Camembert` und `ROBERTA` zu `CAMEMBERT`. Sie können [hier](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/camembert/modeling_camembert.py#L929) sehen, wie dies mit dem Kommentar gemacht wird: + +```py +# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT +``` + +Wenn die Reihenfolge eine Rolle spielt (weil eine der Ersetzungen mit einer vorherigen in Konflikt geraten könnte), werden die Ersetzungen von links nach rechts ausgeführt. + + + +Wenn die Ersetzungen die Formatierung ändern (wenn Sie z.B. einen kurzen Namen durch einen sehr langen Namen ersetzen), wird die Kopie nach Anwendung des automatischen Formats überprüft. + + + +Eine andere Möglichkeit, wenn es sich bei den Mustern nur um verschiedene Umschreibungen derselben Ersetzung handelt (mit einer groß- und einer kleingeschriebenen Variante), besteht darin, die Option `all-casing` hinzuzufügen. [Hier](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/mobilebert/modeling_mobilebert.py#L1237) ist ein Beispiel in `MobileBertForSequenceClassification` mit dem Kommentar: + +```py +# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing +``` + +In diesem Fall wird der Code von `BertForSequenceClassification` kopiert, indem er ersetzt wird: +- `Bert` durch `MobileBert` (zum Beispiel bei der Verwendung von `MobileBertModel` in der Init) +- `bert` durch `mobilebert` (zum Beispiel bei der Definition von `self.mobilebert`) +- `BERT` durch `MOBILEBERT` (in der Konstante `MOBILEBERT_INPUTS_DOCSTRING`) diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/preprocessing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/preprocessing.md new file mode 100644 index 0000000000000000000000000000000000000000..b56a5c0ae4ca1cf64137d6331d10d20cae698769 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/preprocessing.md @@ -0,0 +1,506 @@ + + +# Vorverarbeiten + +[[open-in-colab]] + +Bevor Sie Ihre Daten in einem Modell verwenden können, müssen die Daten in ein für das Modell akzeptables Format gebracht werden. Ein Modell versteht keine Rohtexte, Bilder oder Audiodaten. Diese Eingaben müssen in Zahlen umgewandelt und zu Tensoren zusammengesetzt werden. In dieser Anleitung werden Sie: + +* Textdaten mit einem Tokenizer vorverarbeiten. +* Bild- oder Audiodaten mit einem Feature Extractor vorverarbeiten. +* Daten für eine multimodale Aufgabe mit einem Prozessor vorverarbeiten. + +## NLP + + + +Das wichtigste Werkzeug zur Verarbeitung von Textdaten ist ein [Tokenizer](main_classes/tokenizer). Ein Tokenizer zerlegt Text zunächst nach einer Reihe von Regeln in *Token*. Die Token werden in Zahlen umgewandelt, die zum Aufbau von Tensoren als Eingabe für ein Modell verwendet werden. Alle zusätzlichen Eingaben, die ein Modell benötigt, werden ebenfalls vom Tokenizer hinzugefügt. + + + +Wenn Sie ein vortrainiertes Modell verwenden möchten, ist es wichtig, den zugehörigen vortrainierten Tokenizer zu verwenden. Dadurch wird sichergestellt, dass der Text auf die gleiche Weise aufgeteilt wird wie das Pretraining-Korpus und die gleichen entsprechenden Token-zu-Index (in der Regel als *vocab* bezeichnet) während des Pretrainings verwendet werden. + + + +Laden Sie einen vortrainierten Tokenizer mit der Klasse [AutoTokenizer], um schnell loszulegen. Damit wird das *vocab* heruntergeladen, das verwendet wird, wenn ein Modell vortrainiert wird. + +### Tokenize + +Laden Sie einen vortrainierten Tokenizer mit [`AutoTokenizer.from_pretrained`]: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +``` + +Dann übergeben Sie Ihren Satz an den Tokenizer: + +```py +>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.") +>>> print(encoded_input) +{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +Der Tokenizer gibt ein Wörterbuch mit drei wichtigen Elementen zurück: + +* [input_ids](glossary#input-ids) sind die Indizes, die den einzelnen Token im Satz entsprechen. +* [attention_mask](glossary#attention-mask) gibt an, ob ein Token beachtet werden soll oder nicht. +* [token_type_ids](glossary#token-type-ids) gibt an, zu welcher Sequenz ein Token gehört, wenn es mehr als eine Sequenz gibt. + +Sie können die `input_ids` dekodieren, um die ursprüngliche Eingabe zurückzugeben: + +```py +>>> tokenizer.decode(encoded_input["input_ids"]) +'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]' +``` + +Wie Sie sehen können, hat der Tokenisierer zwei spezielle Token - `CLS` und `SEP` (Klassifikator und Separator) - zum Satz hinzugefügt. Nicht alle Modelle benötigen +spezielle Token, aber wenn dies der Fall ist, fügt der Tokenisierer sie automatisch für Sie hinzu. + +Wenn Sie mehrere Sätze verarbeiten wollen, übergeben Sie die Sätze als Liste an den Tokenizer: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_inputs = tokenizer(batch_sentences) +>>> print(encoded_inputs) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]]} +``` + +### Pad + +Dies bringt uns zu einem wichtigen Thema. Wenn Sie einen Haufen von Sätzen verarbeiten, sind diese nicht immer gleich lang. Das ist ein Problem, weil Tensoren, die Eingabe für das Modell, eine einheitliche Form haben müssen. Padding ist eine Strategie, die sicherstellt, dass Tensoren rechteckig sind, indem ein spezielles *Padding-Token* zu Sätzen mit weniger Token hinzugefügt wird. + +Setzen Sie den Parameter "padding" auf "true", um die kürzeren Sequenzen im Stapel so aufzufüllen, dass sie der längsten Sequenz entsprechen: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]} +``` + +Beachten Sie, dass der Tokenizer den ersten und den dritten Satz mit einer "0" aufgefüllt hat, weil sie kürzer sind! + +### Kürzung + +Auf der anderen Seite des Spektrums kann es vorkommen, dass eine Sequenz zu lang für ein Modell ist. In diesem Fall müssen Sie die Sequenz auf eine kürzere Länge kürzen. + +Setzen Sie den Parameter "truncation" auf "true", um eine Sequenz auf die vom Modell akzeptierte Höchstlänge zu kürzen: + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True) +>>> print(encoded_input) +{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]], + 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]} +``` + +### Tensoren erstellen + +Schließlich möchten Sie, dass der Tokenizer die tatsächlichen Tensoren zurückgibt, die dem Modell zugeführt werden. + +Setzen Sie den Parameter `return_tensors` entweder auf `pt` für PyTorch, oder `tf` für TensorFlow: + + + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt") +>>> print(encoded_input) +{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0], + [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102], + [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])} +``` + + +```py +>>> batch_sentences = [ +... "But what about second breakfast?", +... "Don't think he knows about second breakfast, Pip.", +... "What about elevensies?", +... ] +>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf") +>>> print(encoded_input) +{'input_ids': , + 'token_type_ids': , + 'attention_mask': } +``` + + + +## Audio + +Audioeingaben werden anders vorverarbeitet als Texteingaben, aber das Endziel bleibt dasselbe: numerische Sequenzen zu erstellen, die das Modell verstehen kann. Ein [feature extractor](main_classes/feature_extractor) dient dem ausdrücklichen Zweck, Merkmale aus Rohbild- oder Audiodaten zu extrahieren und in Tensoren zu konvertieren. Bevor Sie beginnen, installieren Sie 🤗 Datasets, um einen Audio-Datensatz zu laden, mit dem Sie experimentieren können: + +```bash +pip install datasets +``` + +Laden Sie den [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) Datensatz (weitere Informationen zum Laden eines Datensatzes finden Sie im 🤗 [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub)): + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +``` + +Greifen Sie auf das erste Element der `audio`-Spalte zu, um einen Blick auf die Eingabe zu werfen. Durch den Aufruf der Spalte "audio" wird die Audiodatei automatisch geladen und neu gesampelt: + +```py +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +Dies gibt drei Elemente zurück: + +* "array" ist das Sprachsignal, das als 1D-Array geladen - und möglicherweise neu gesampelt - wurde. +* Pfad" zeigt auf den Speicherort der Audiodatei. +* `sampling_rate` bezieht sich darauf, wie viele Datenpunkte im Sprachsignal pro Sekunde gemessen werden. + +### Resample + +Für dieses Tutorial werden Sie das Modell [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) verwenden. Wie Sie aus der Modellkarte ersehen können, ist das Wav2Vec2-Modell auf 16kHz abgetastetes Sprachaudio vortrainiert. Es ist wichtig, dass die Abtastrate Ihrer Audiodaten mit der Abtastrate des Datensatzes übereinstimmt, der für das Pre-Training des Modells verwendet wurde. Wenn die Abtastrate Ihrer Daten nicht dieselbe ist, müssen Sie Ihre Audiodaten neu abtasten. + +Der Datensatz [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) hat zum Beispiel eine Abtastrate von 8000 kHz. Um das Wav2Vec2-Modell mit diesem Datensatz verwenden zu können, müssen Sie die Abtastrate auf 16 kHz erhöhen: + +```py +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +>>> dataset[0]["audio"] +{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 8000} +``` + +1. Verwenden Sie die Methode [`~datasets.Dataset.cast_column`] von 🤗 Datasets, um die Abtastrate auf 16kHz zu erhöhen: + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +2. Laden Sie die Audiodatei: + +```py +>>> dataset[0]["audio"] +{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., + 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'sampling_rate': 16000} +``` + +Wie Sie sehen können, ist die Abtastrate jetzt 16kHz! + +### Merkmalsextraktor + +Der nächste Schritt ist das Laden eines Merkmalsextraktors, um die Eingabe zu normalisieren und aufzufüllen. Beim Auffüllen von Textdaten wird für kürzere Sequenzen ein `0` hinzugefügt. Die gleiche Idee gilt für Audiodaten, und der Audio-Feature-Extraktor fügt eine `0` - interpretiert als Stille - zu `array` hinzu. + +Laden Sie den Merkmalsextraktor mit [`AutoFeatureExtractor.from_pretrained`]: + +```py +>>> from transformers import AutoFeatureExtractor + +>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +Übergeben Sie das Audio-"Array" an den Feature-Extraktor. Wir empfehlen auch, das Argument `sampling_rate` im Feature Extractor hinzuzufügen, um eventuell auftretende stille Fehler besser zu beheben. + +```py +>>> audio_input = [dataset[0]["audio"]["array"]] +>>> feature_extractor(audio_input, sampling_rate=16000) +{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ..., + 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]} +``` + +### Auffüllen und Kürzen + +Genau wie beim Tokenizer können Sie variable Sequenzen in einem Stapel durch Auffüllen oder Abschneiden behandeln. Werfen Sie einen Blick auf die Sequenzlänge dieser beiden Audiobeispiele: + +```py +>>> dataset[0]["audio"]["array"].shape +(173398,) + +>>> dataset[1]["audio"]["array"].shape +(106496,) +``` + +Wie Sie sehen können, hat das erste Beispiel eine längere Sequenz als das zweite Beispiel. Lassen Sie uns eine Funktion erstellen, die den Datensatz vorverarbeitet. Geben Sie eine maximale Länge der Probe an, und der Feature-Extraktor wird die Sequenzen entweder auffüllen oder abschneiden, damit sie dieser Länge entsprechen: + +```py +>>> def preprocess_function(examples): +... audio_arrays = [x["array"] for x in examples["audio"]] +... inputs = feature_extractor( +... audio_arrays, +... sampling_rate=16000, +... padding=True, +... max_length=100000, +... truncation=True, +... ) +... return inputs +``` + +Wenden Sie die Funktion auf die ersten paar Beispiele im Datensatz an: + +```py +>>> processed_dataset = preprocess_function(dataset[:5]) +``` + +Schauen Sie sich nun noch einmal die verarbeiteten Beispiel-Längen an: + +```py +>>> processed_dataset["input_values"][0].shape +(100000,) + +>>> processed_dataset["input_values"][1].shape +(100000,) +``` + +Die Länge der ersten beiden Beispiele entspricht nun der von Ihnen angegebenen Maximallänge. + +## Bildverarbeitung + +Ein Merkmalsextraktor wird auch verwendet, um Bilder für Bildverarbeitungsaufgaben zu verarbeiten. Auch hier besteht das Ziel darin, das Rohbild in eine Reihe von Tensoren als Eingabe zu konvertieren. + +Laden wir den [food101](https://huggingface.co/datasets/food101) Datensatz für dieses Tutorial. Verwenden Sie den Parameter 🤗 Datasets `split`, um nur eine kleine Stichprobe aus dem Trainingssplit zu laden, da der Datensatz recht groß ist: + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("food101", split="train[:100]") +``` + +Als Nächstes sehen Sie sich das Bild mit dem Merkmal 🤗 Datensätze [Bild](https://huggingface.co/docs/datasets/package_reference/main_classes?highlight=image#datasets.Image) an: + +```py +>>> dataset[0]["image"] +``` + +![vision-preprocess-tutorial.png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vision-preprocess-tutorial.png) + +### Merkmalsextraktor + +Laden Sie den Merkmalsextraktor mit [`AutoImageProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoImageProcessor + +>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +### Datenerweiterung + +Bei Bildverarbeitungsaufgaben ist es üblich, den Bildern als Teil der Vorverarbeitung eine Art von Datenerweiterung hinzuzufügen. Sie können Erweiterungen mit jeder beliebigen Bibliothek hinzufügen, aber in diesem Tutorial werden Sie das Modul [`transforms`](https://pytorch.org/vision/stable/transforms.html) von torchvision verwenden. + +1. Normalisieren Sie das Bild und verwenden Sie [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html), um einige Transformationen - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) und [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) - miteinander zu verknüpfen: + +```py +>>> from torchvision.transforms import Compose, Normalize, RandomResizedCrop, ColorJitter, ToTensor + +>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std) +>>> _transforms = Compose( +... [RandomResizedCrop(image_processor.size["height"]), ColorJitter(brightness=0.5, hue=0.5), ToTensor(), normalize] +... ) +``` + +2. Das Modell akzeptiert [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) als Eingabe. Dieser Wert wird vom Merkmalsextraktor erzeugt. Erstellen Sie eine Funktion, die `pixel_values` aus den Transformationen erzeugt: + +```py +>>> def transforms(examples): +... examples["pixel_values"] = [_transforms(image.convert("RGB")) for image in examples["image"]] +... return examples +``` + +3. Dann verwenden Sie 🤗 Datasets [`set_transform`](https://huggingface.co/docs/datasets/process#format-transform), um die Transformationen im laufenden Betrieb anzuwenden: + +```py +>>> dataset.set_transform(transforms) +``` + +4. Wenn Sie nun auf das Bild zugreifen, werden Sie feststellen, dass der Feature Extractor die Modelleingabe "pixel_values" hinzugefügt hat: + +```py +>>> dataset[0]["image"] +{'image': , + 'label': 6, + 'pixel_values': tensor([[[ 0.0353, 0.0745, 0.1216, ..., -0.9922, -0.9922, -0.9922], + [-0.0196, 0.0667, 0.1294, ..., -0.9765, -0.9843, -0.9922], + [ 0.0196, 0.0824, 0.1137, ..., -0.9765, -0.9686, -0.8667], + ..., + [ 0.0275, 0.0745, 0.0510, ..., -0.1137, -0.1216, -0.0824], + [ 0.0667, 0.0824, 0.0667, ..., -0.0588, -0.0745, -0.0980], + [ 0.0353, 0.0353, 0.0431, ..., -0.0039, -0.0039, -0.0588]], + + [[ 0.2078, 0.2471, 0.2863, ..., -0.9451, -0.9373, -0.9451], + [ 0.1608, 0.2471, 0.3098, ..., -0.9373, -0.9451, -0.9373], + [ 0.2078, 0.2706, 0.3020, ..., -0.9608, -0.9373, -0.8275], + ..., + [-0.0353, 0.0118, -0.0039, ..., -0.2392, -0.2471, -0.2078], + [ 0.0196, 0.0353, 0.0196, ..., -0.1843, -0.2000, -0.2235], + [-0.0118, -0.0039, -0.0039, ..., -0.0980, -0.0980, -0.1529]], + + [[ 0.3961, 0.4431, 0.4980, ..., -0.9216, -0.9137, -0.9216], + [ 0.3569, 0.4510, 0.5216, ..., -0.9059, -0.9137, -0.9137], + [ 0.4118, 0.4745, 0.5216, ..., -0.9137, -0.8902, -0.7804], + ..., + [-0.2314, -0.1922, -0.2078, ..., -0.4196, -0.4275, -0.3882], + [-0.1843, -0.1686, -0.2000, ..., -0.3647, -0.3804, -0.4039], + [-0.1922, -0.1922, -0.1922, ..., -0.2941, -0.2863, -0.3412]]])} +``` + +Hier sehen Sie, wie das Bild nach der Vorverarbeitung aussieht. Wie von den angewandten Transformationen zu erwarten, wurde das Bild willkürlich beschnitten und seine Farbeigenschaften sind anders. + +```py +>>> import numpy as np +>>> import matplotlib.pyplot as plt + +>>> img = dataset[0]["pixel_values"] +>>> plt.imshow(img.permute(1, 2, 0)) +``` + +![preprocessed_image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/preprocessed_image.png) + +## Multimodal + +Für multimodale Aufgaben werden Sie eine Kombination aus allem, was Sie bisher gelernt haben, verwenden und Ihre Fähigkeiten auf eine Aufgabe der automatischen Spracherkennung (ASR) anwenden. Dies bedeutet, dass Sie einen: + +* Feature Extractor zur Vorverarbeitung der Audiodaten. +* Tokenizer, um den Text zu verarbeiten. + +Kehren wir zum [LJ Speech](https://huggingface.co/datasets/lj_speech) Datensatz zurück: + +```py +>>> from datasets import load_dataset + +>>> lj_speech = load_dataset("lj_speech", split="train") +``` + +Da Sie hauptsächlich an den Spalten "Audio" und "Text" interessiert sind, entfernen Sie die anderen Spalten: + +```py +>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"]) +``` + +Schauen Sie sich nun die Spalten "Audio" und "Text" an: + +```py +>>> lj_speech[0]["audio"] +{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ..., + 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32), + 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav', + 'sampling_rate': 22050} + +>>> lj_speech[0]["text"] +'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition' +``` + +Erinnern Sie sich an den früheren Abschnitt über die Verarbeitung von Audiodaten: Sie sollten immer die Abtastrate Ihrer Audiodaten [resample](preprocessing#audio), damit sie mit der Abtastrate des Datensatzes übereinstimmt, der für das Vortraining eines Modells verwendet wird: + +```py +>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000)) +``` + +### Prozessor + +Ein Processor kombiniert einen Feature-Extraktor und einen Tokenizer. Laden Sie einen Processor mit [`AutoProcessor.from_pretrained`]: + +```py +>>> from transformers import AutoProcessor + +>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") +``` + +1. Erstellen Sie eine Funktion, die die Audiodaten zu `input_values` verarbeitet und den Text zu `labels` tokenisiert. Dies sind Ihre Eingaben für das Modell: + +```py +>>> def prepare_dataset(example): +... audio = example["audio"] + +... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000)) + +... return example +``` + +2. Wenden Sie die Funktion "prepare_dataset" auf ein Beispiel an: + +```py +>>> prepare_dataset(lj_speech[0]) +``` + +Beachten Sie, dass der Processor `input_values` und `labels` hinzugefügt hat. Auch die Abtastrate wurde korrekt auf 16kHz heruntergerechnet. + +Toll, Sie sollten jetzt in der Lage sein, Daten für jede Modalität vorzuverarbeiten und sogar verschiedene Modalitäten zu kombinieren! Im nächsten Kurs lernen Sie, wie Sie ein Modell mit Ihren neu aufbereiteten Daten feinabstimmen können. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/quicktour.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/quicktour.md new file mode 100644 index 0000000000000000000000000000000000000000..c01609207fec2a1da1c643bdd38f8146a0308657 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/quicktour.md @@ -0,0 +1,438 @@ + + +# Schnellstart + +[[open-in-colab]] + +Mit 🤗 Transformers können Sie sofort loslegen! Verwenden Sie die [`pipeline`] für schnelle Inferenz und laden Sie schnell ein vortrainiertes Modell und einen Tokenizer mit einer [AutoClass](./model_doc/auto), um Ihre Text-, Bild- oder Audioaufgabe zu lösen. + + + +Alle in der Dokumentation vorgestellten Codebeispiele haben oben links einen Umschalter für PyTorch und TensorFlow. Wenn +nicht, wird erwartet, dass der Code für beide Backends ohne Änderungen funktioniert. + + + +## Pipeline + +[`pipeline`] ist der einfachste Weg, ein vortrainiertes Modell für eine bestimmte Aufgabe zu verwenden. + + + +Die [`pipeline`] unterstützt viele gängige Aufgaben: + +**Text**: +* Stimmungsanalyse: Klassifizierung der Polarität eines gegebenen Textes. +* Textgenerierung (auf Englisch): Generierung von Text aus einer gegebenen Eingabe. +* Name-Entity-Recognition (NER): Kennzeichnung jedes Worts mit der Entität, die es repräsentiert (Person, Datum, Ort usw.). +* Beantwortung von Fragen: Extrahieren der Antwort aus dem Kontext, wenn ein gewisser Kontext und eine Frage gegeben sind. +* Fill-mask: Ausfüllen von Lücken in einem Text mit maskierten Wörtern. +* Zusammenfassung: Erstellung einer Zusammenfassung einer langen Text- oder Dokumentensequenz. +* Übersetzung: Übersetzen eines Textes in eine andere Sprache. +* Merkmalsextraktion: Erstellen einer Tensordarstellung des Textes. + +**Bild**: +* Bildklassifizierung: Klassifizierung eines Bildes. +* Bildsegmentierung: Klassifizierung jedes Pixels in einem Bild. +* Objekterkennung: Erkennen von Objekten innerhalb eines Bildes. + +**Audio**: +* Audioklassifizierung: Zuweisung eines Labels zu einem bestimmten Audiosegment. +* Automatische Spracherkennung (ASR): Transkription von Audiodaten in Text. + + + +Für mehr Details über die [`pipeline`] und assoziierte Aufgaben, schauen Sie in die Dokumentation [hier](./main_classes/pipelines). + + + +### Verwendung der Pipeline + +Im folgenden Beispiel werden Sie die [`pipeline`] für die Stimmungsanalyse verwenden. + +Installieren Sie die folgenden Abhängigkeiten, falls Sie dies nicht bereits getan haben: + + + + +```bash +pip install torch +``` + + + +```bash +pip install tensorflow +``` + + + +Importieren sie die [`pipeline`] und spezifizieren sie die Aufgabe, welche sie lösen möchten: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("sentiment-analysis") +``` + +Die Pipeline lädt ein standardmäßiges [vortrainiertes Modell](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) und einen Tokenizer für die Stimmungs-Analyse herunter und speichert sie. Jetzt können Sie den "Klassifikator" auf Ihren Zieltext anwenden: + +```py +>>> classifier("We are very happy to show you the 🤗 Transformers library.") +[{'label': 'POSITIVE', 'score': 0.9998}] +``` + +For more than one sentence, pass a list of sentences to the [`pipeline`] which returns a list of dictionaries: + +```py +>>> results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."]) +>>> for result in results: +... print(f"label: {result['label']}, with score: {round(result['score'], 4)}") +label: POSITIVE, with score: 0.9998 +label: NEGATIVE, with score: 0.5309 +``` + +Die [`pipeline`] kann auch über einen ganzen Datensatz iterieren. Starten wir mit der Installation der [🤗 Datasets](https://huggingface.co/docs/datasets/) Bibliothek: + +```bash +pip install datasets +``` + +Erstellen wir eine [`pipeline`] mit der Aufgabe die wir lösen und dem Modell welches wir nutzen möchten. + +```py +>>> import torch +>>> from transformers import pipeline + +>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h") +``` + +Als nächstes laden wir den Datensatz (siehe 🤗 Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart) für mehr Details) welches wir nutzen möchten. Zum Beispiel laden wir den [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) Datensatz: + +```py +>>> from datasets import load_dataset, Audio + +>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT +``` + +Wir müssen sicherstellen, dass die Abtastrate des Datensatzes der Abtastrate entspricht, mit der `facebook/wav2vec2-base-960h` trainiert wurde. + +```py +>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate)) +``` + +Audiodateien werden automatisch geladen und neu abgetastet, wenn die Spalte "audio" aufgerufen wird. +Extrahieren wir die rohen Wellenform-Arrays der ersten 4 Beispiele und übergeben wir sie als Liste an die Pipeline: + +```py +>>> result = speech_recognizer(dataset[:4]["audio"]) +>>> print([d["text"] for d in result]) +['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FODING HOW I'D SET UP A JOIN TO HET WITH MY WIFE AND WHERE THE AP MIGHT BE", "I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE AP SO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AND I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS", 'HOW DO I THURN A JOIN A COUNT'] +``` + +Bei einem größeren Datensatz mit vielen Eingaben (wie bei Sprache oder Bildverarbeitung) sollten Sie einen Generator anstelle einer Liste übergeben, der alle Eingaben in den Speicher lädt. Weitere Informationen finden Sie in der [Pipeline-Dokumentation](./main_classes/pipelines). + +### Ein anderes Modell und einen anderen Tokenizer in der Pipeline verwenden + +Die [`pipeline`] kann jedes Modell aus dem [Model Hub](https://huggingface.co/models) verwenden, wodurch es einfach ist, die [`pipeline`] für andere Anwendungsfälle anzupassen. Wenn Sie beispielsweise ein Modell wünschen, das französischen Text verarbeiten kann, verwenden Sie die Tags im Model Hub, um nach einem geeigneten Modell zu filtern. Das oberste gefilterte Ergebnis liefert ein mehrsprachiges [BERT-Modell](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment), das auf die Stimmungsanalyse abgestimmt ist. Großartig, verwenden wir dieses Modell! + +```py +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +``` + + + +Use the [`AutoModelForSequenceClassification`] and [`AutoTokenizer`] to load the pretrained model and it's associated tokenizer (more on an `AutoClass` below): + +```py +>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + +Use the [`TFAutoModelForSequenceClassification`] and [`AutoTokenizer`] to load the pretrained model and it's associated tokenizer (more on an `TFAutoClass` below): + +```py +>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + +>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + + + +Dann können Sie das Modell und den Tokenizer in der [`pipeline`] angeben und den `Klassifikator` auf Ihren Zieltext anwenden: + +```py +>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) +>>> classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.") +[{'label': '5 stars', 'score': 0.7273}] +``` + +Wenn Sie kein Modell für Ihren Anwendungsfall finden können, müssen Sie ein vortrainiertes Modell auf Ihren Daten feinabstimmen. Schauen Sie sich unser [Feinabstimmungs-Tutorial](./training) an, um zu erfahren, wie das geht. Und schließlich, nachdem Sie Ihr trainiertes Modell verfeinert haben, sollten Sie es mit der Community im Model Hub teilen (siehe Tutorial [hier](./model_sharing)), um NLP für alle zu demokratisieren! 🤗 + +## AutoClass + + + +Unter der Haube arbeiten die Klassen [`AutoModelForSequenceClassification`] und [`AutoTokenizer`] zusammen, um die [`pipeline`] zu betreiben. Eine [`AutoClass`](./model_doc/auto) ist eine Abkürzung, die automatisch die Architektur eines trainierten Modells aus dessen Namen oder Pfad abruft. Sie müssen nur die passende `AutoClass` für Ihre Aufgabe und den zugehörigen Tokenizer mit [`AutoTokenizer`] auswählen. + +Kehren wir zu unserem Beispiel zurück und sehen wir uns an, wie Sie die `AutoClass` verwenden können, um die Ergebnisse der [`pipeline`] zu replizieren. + +### AutoTokenizer + +Ein Tokenizer ist für die Vorverarbeitung von Text in ein für das Modell verständliches Format zuständig. Zunächst zerlegt der Tokenisierer den Text in Wörter, die *Token* genannt werden. Es gibt mehrere Regeln für den Tokenisierungsprozess, z. B. wie und auf welcher Ebene ein Wort aufgespalten wird (weitere Informationen über Tokenisierung [hier](./tokenizer_summary)). Das Wichtigste ist jedoch, dass Sie den Tokenizer mit demselben Modellnamen instanziieren müssen, um sicherzustellen, dass Sie dieselben Tokenisierungsregeln verwenden, mit denen ein Modell zuvor trainiert wurde. +Laden sie einen Tokenizer mit [`AutoTokenizer`]: + +```py +>>> from transformers import AutoTokenizer + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +``` + +Anschließend wandelt der Tokenizer die Token in Zahlen um, um einen Tensor als Eingabe für das Modell zu konstruieren. Dieser wird als *Vokabular* des Modells bezeichnet. + +Übergeben Sie Ihren Text an den Tokenizer: + +```py +>>> encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.") +>>> print(encoding) +{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102], + 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} +``` + +Der Tokenizer gibt ein Wörterbuch zurück, das Folgendes enthält: + +* [input_ids](./glossary#input-ids): numerische Repräsentationen Ihrer Token. +* [atttention_mask](.glossary#attention-mask): gibt an, welche Token beachtet werden sollen. + +Genau wie die [`pipeline`] akzeptiert der Tokenizer eine Liste von Eingaben. Darüber hinaus kann der Tokenizer den Text auch auffüllen und kürzen, um einen Stapel mit einheitlicher Länge zurückzugeben: + + + + +```py +>>> pt_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="pt", +... ) +``` + + + +```py +>>> tf_batch = tokenizer( +... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."], +... padding=True, +... truncation=True, +... max_length=512, +... return_tensors="tf", +... ) +``` + + + +Lesen Sie das Tutorial [preprocessing](./preprocessing) für weitere Details zur Tokenisierung. + +### AutoModel + + + +🤗 Transformers bietet eine einfache und einheitliche Möglichkeit, vortrainierte Instanzen zu laden. Das bedeutet, dass Sie ein [`AutoModel`] laden können, wie Sie einen [`AutoTokenizer`] laden würden. Der einzige Unterschied ist die Auswahl des richtigen [`AutoModel`] für die Aufgabe. Da Sie eine Text- oder Sequenzklassifizierung vornehmen, laden Sie [`AutoModelForSequenceClassification`]: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +In der [Aufgabenzusammenfassung](./task_summary) steht, welche [AutoModel]-Klasse für welche Aufgabe zu verwenden ist. + + + +Jetzt können Sie Ihren vorverarbeiteten Stapel von Eingaben direkt an das Modell übergeben. Sie müssen nur das Wörterbuch entpacken, indem Sie `**` hinzufügen: + +```py +>>> pt_outputs = pt_model(**pt_batch) +``` + +Das Modell gibt die endgültigen Aktivierungen in dem Attribut "logits" aus. Wenden Sie die Softmax-Funktion auf die "logits" an, um die Wahrscheinlichkeiten zu erhalten: + +```py +>>> from torch import nn + +>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1) +>>> print(pt_predictions) +tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725], + [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=) +``` + + +🤗 Transformers bietet eine einfache und einheitliche Methode zum Laden von vortrainierten Instanzen. Das bedeutet, dass Sie ein [`TFAutoModel`] genauso laden können, wie Sie einen [`AutoTokenizer`] laden würden. Der einzige Unterschied ist die Auswahl des richtigen [`TFAutoModel`] für die Aufgabe. Da Sie Text - oder Sequenz - Klassifizierung machen, laden Sie [`TFAutoModelForSequenceClassification`]: + +```py +>>> from transformers import TFAutoModelForSequenceClassification + +>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment" +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name) +``` + + + +In der [Aufgabenzusammenfassung](./task_summary) steht, welche [AutoModel]-Klasse für welche Aufgabe zu verwenden ist. + + + +Jetzt können Sie Ihren vorverarbeiteten Stapel von Eingaben direkt an das Modell übergeben, indem Sie die Wörterbuchschlüssel direkt an die Tensoren übergeben: + +```py +>>> tf_outputs = tf_model(tf_batch) +``` + +Das Modell gibt die endgültigen Aktivierungen in dem Attribut "logits" aus. Wenden Sie die Softmax-Funktion auf die "logits" an, um die Wahrscheinlichkeiten zu erhalten: + +```py +>>> import tensorflow as tf + +>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1) +>>> tf_predictions # doctest: +IGNORE_RESULT +``` + + + + + +Alle 🤗 Transformers-Modelle (PyTorch oder TensorFlow) geben die Tensoren *vor* der endgültigen Aktivierungsfunktion +Funktion (wie Softmax) aus, da die endgültige Aktivierungsfunktion oft mit dem Verlusten verschmolzen ist. + + + +Modelle sind ein standardmäßiges [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) oder ein [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model), sodass Sie sie in Ihrer üblichen Trainingsschleife verwenden können. Um jedoch die Dinge einfacher zu machen, bietet 🤗 Transformers eine [`Trainer`]-Klasse für PyTorch, die Funktionalität für verteiltes Training, gemischte Präzision und mehr bietet. Für TensorFlow können Sie die Methode `fit` aus [Keras](https://keras.io/) verwenden. Siehe das [training tutorial](./training) für weitere Details. + + + +Transformers-Modellausgaben sind spezielle Datenklassen, so dass ihre Attribute in einer IDE automatisch vervollständigt werden. +Die Modellausgänge verhalten sich auch wie ein Tupel oder ein Wörterbuch (z.B. können Sie mit einem Integer, einem Slice oder einem String indexieren), wobei die Attribute, die "None" sind, ignoriert werden. + + + +### Modell speichern + + + +Sobald Ihr Modell feinabgestimmt ist, können Sie es mit seinem Tokenizer speichern, indem Sie [`PreTrainedModel.save_pretrained`] verwenden: + +```py +>>> pt_save_directory = "./pt_save_pretrained" +>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT +>>> pt_model.save_pretrained(pt_save_directory) +``` + +Wenn Sie bereit sind, das Modell erneut zu verwenden, laden Sie es mit [`PreTrainedModel.from_pretrained`]: + +```py +>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained") +``` + + +Sobald Ihr Modell feinabgestimmt ist, können Sie es mit seinem Tokenizer unter Verwendung von [`TFPreTrainedModel.save_pretrained`] speichern: + +```py +>>> tf_save_directory = "./tf_save_pretrained" +>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT +>>> tf_model.save_pretrained(tf_save_directory) +``` + +Wenn Sie bereit sind, das Modell wieder zu verwenden, laden Sie es mit [`TFPreTrainedModel.from_pretrained`]: + +```py +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained") +``` + + + +Ein besonders cooles 🤗 Transformers-Feature ist die Möglichkeit, ein Modell zu speichern und es entweder als PyTorch- oder TensorFlow-Modell wieder zu laden. Der Parameter "from_pt" oder "from_tf" kann das Modell von einem Framework in das andere konvertieren: + + + + +```py +>>> from transformers import AutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory) +>>> pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True) +``` + + + +```py +>>> from transformers import TFAutoModel + +>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory) +>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True) +``` + + + +## Custom model builds + +Sie können die Konfigurationsklasse des Modells ändern, um zu bestimmen, wie ein Modell aufgebaut ist. Die Konfiguration legt die Attribute eines Modells fest, z. B. die Anzahl der verborgenen Schichten oder der Aufmerksamkeitsköpfe. Wenn Sie ein Modell aus einer benutzerdefinierten Konfigurationsklasse initialisieren, beginnen Sie bei Null. Die Modellattribute werden zufällig initialisiert, und Sie müssen das Modell trainieren, bevor Sie es verwenden können, um aussagekräftige Ergebnisse zu erhalten. + +Beginnen Sie mit dem Import von [`AutoConfig`] und laden Sie dann das trainierte Modell, das Sie ändern möchten. Innerhalb von [`AutoConfig.from_pretrained`] können Sie das Attribut angeben, das Sie ändern möchten, z. B. die Anzahl der Aufmerksamkeitsköpfe: + +```py +>>> from transformers import AutoConfig + +>>> my_config = AutoConfig.from_pretrained("distilbert/distilbert-base-uncased", n_heads=12) +``` + + + +Create a model from your custom configuration with [`AutoModel.from_config`]: + +```py +>>> from transformers import AutoModel + +>>> my_model = AutoModel.from_config(my_config) +``` + + +Create a model from your custom configuration with [`TFAutoModel.from_config`]: + +```py +>>> from transformers import TFAutoModel + +>>> my_model = TFAutoModel.from_config(my_config) +``` + + + +Weitere Informationen zur Erstellung von benutzerdefinierten Konfigurationen finden Sie in der Anleitung [Erstellen einer benutzerdefinierten Architektur](./create_a_model). + +## Wie geht es weiter? + +Nachdem Sie nun die 🤗 Transformers-Kurztour abgeschlossen haben, schauen Sie sich unsere Anleitungen an und erfahren Sie, wie Sie spezifischere Dinge tun können, wie das Schreiben eines benutzerdefinierten Modells, die Feinabstimmung eines Modells für eine Aufgabe und wie man ein Modell mit einem Skript trainiert. Wenn Sie mehr über die Kernkonzepte von 🤗 Transformers erfahren möchten, nehmen Sie sich eine Tasse Kaffee und werfen Sie einen Blick auf unsere konzeptionellen Leitfäden! diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/run_scripts.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/run_scripts.md new file mode 100644 index 0000000000000000000000000000000000000000..4b62c73276e0cb75b9956e9055075d3c644e00f0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/run_scripts.md @@ -0,0 +1,351 @@ + + +# Trainieren mit einem Skript + +Neben den 🤗 Transformers [notebooks](./notebooks) gibt es auch Beispielskripte, die zeigen, wie man ein Modell für eine Aufgabe mit [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow) oder [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax) trainiert. + +Sie werden auch Skripte finden, die wir in unseren [Forschungsprojekten](https://github.com/huggingface/transformers-research-projects/) und [Legacy-Beispielen](https://github.com/huggingface/transformers/tree/main/examples/legacy) verwendet haben und die größtenteils von der Community stammen. Diese Skripte werden nicht aktiv gepflegt und erfordern eine bestimmte Version von 🤗 Transformers, die höchstwahrscheinlich nicht mit der neuesten Version der Bibliothek kompatibel ist. + +Es wird nicht erwartet, dass die Beispielskripte bei jedem Problem sofort funktionieren. Möglicherweise müssen Sie das Skript an das Problem anpassen, das Sie zu lösen versuchen. Um Ihnen dabei zu helfen, legen die meisten Skripte vollständig offen, wie die Daten vorverarbeitet werden, so dass Sie sie nach Bedarf für Ihren Anwendungsfall bearbeiten können. + +Für jede Funktion, die Sie in einem Beispielskript implementieren möchten, diskutieren Sie bitte im [Forum](https://discuss.huggingface.co/) oder in einem [issue](https://github.com/huggingface/transformers/issues), bevor Sie einen Pull Request einreichen. Wir freuen uns zwar über Fehlerkorrekturen, aber es ist unwahrscheinlich, dass wir einen Pull Request zusammenführen, der mehr Funktionalität auf Kosten der Lesbarkeit hinzufügt. + +Diese Anleitung zeigt Ihnen, wie Sie ein Beispiel für ein Trainingsskript zur Zusammenfassung in [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) und [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) ausführen können. Sofern nicht anders angegeben, sollten alle Beispiele mit beiden Frameworks funktionieren. + +## Einrichtung + +Um die neueste Version der Beispielskripte erfolgreich auszuführen, **müssen Sie 🤗 Transformers aus dem Quellcode** in einer neuen virtuellen Umgebung installieren: + +```bash +git clone https://github.com/huggingface/transformers +cd transformers +pip install . +``` + +Für ältere Versionen der Beispielskripte klicken Sie auf die Umschalttaste unten: + +
+ Beispiele für ältere Versionen von 🤗 Transformers + +
+ +Dann stellen Sie Ihren aktuellen Klon von 🤗 Transformers auf eine bestimmte Version um, z.B. v3.5.1: + +```bash +git checkout tags/v3.5.1 +``` + +Nachdem Sie die richtige Bibliotheksversion eingerichtet haben, navigieren Sie zu dem Beispielordner Ihrer Wahl und installieren die beispielspezifischen Anforderungen: + +```bash +pip install -r requirements.txt +``` + +## Ein Skript ausführen + + + +Das Beispielskript lädt einen Datensatz aus der 🤗 [Datasets](https://huggingface.co/docs/datasets/) Bibliothek herunter und verarbeitet ihn vor. Dann nimmt das Skript eine Feinabstimmung eines Datensatzes mit dem [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) auf einer Architektur vor, die eine Zusammenfassung unterstützt. Das folgende Beispiel zeigt, wie die Feinabstimmung von [T5-small](https://huggingface.co/google-t5/t5-small) auf dem Datensatz [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) durchgeführt wird. Das T5-Modell benötigt aufgrund der Art und Weise, wie es trainiert wurde, ein zusätzliches Argument `source_prefix`. Mit dieser Eingabeaufforderung weiß T5, dass es sich um eine Zusammenfassungsaufgabe handelt. + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + +Das Beispielskript lädt einen Datensatz aus der 🤗 [Datasets](https://huggingface.co/docs/datasets/) Bibliothek herunter und verarbeitet ihn vor. Anschließend nimmt das Skript die Feinabstimmung eines Datensatzes mit Keras auf einer Architektur vor, die die Zusammenfassung unterstützt. Das folgende Beispiel zeigt, wie die Feinabstimmung von [T5-small](https://huggingface.co/google-t5/t5-small) auf dem [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) Datensatz durchgeführt wird. Das T5-Modell benötigt aufgrund der Art und Weise, wie es trainiert wurde, ein zusätzliches Argument `source_prefix`. Mit dieser Eingabeaufforderung weiß T5, dass es sich um eine Zusammenfassungsaufgabe handelt. + +```bash +python examples/tensorflow/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## Verteiltes Training und gemischte Präzision + +Der [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) unterstützt verteiltes Training und gemischte Präzision, d.h. Sie können ihn auch in einem Skript verwenden. So aktivieren Sie diese beiden Funktionen: + +- Fügen Sie das Argument `fp16` hinzu, um gemischte Genauigkeit zu aktivieren. +- Legen Sie die Anzahl der zu verwendenden GPUs mit dem Argument `nproc_per_node` fest. + +```bash +torchrun \ + --nproc_per_node 8 pytorch/summarization/run_summarization.py \ + --fp16 \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +TensorFlow-Skripte verwenden eine [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) für verteiltes Training, und Sie müssen dem Trainingsskript keine zusätzlichen Argumente hinzufügen. Das TensorFlow-Skript verwendet standardmäßig mehrere GPUs, wenn diese verfügbar sind. + +## Ein Skript auf einer TPU ausführen + + + +Tensor Processing Units (TPUs) sind speziell für die Beschleunigung der Leistung konzipiert. PyTorch unterstützt TPUs mit dem [XLA](https://www.tensorflow.org/xla) Deep Learning Compiler (siehe [hier](https://github.com/pytorch/xla/blob/master/README.md) für weitere Details). Um eine TPU zu verwenden, starten Sie das Skript `xla_spawn.py` und verwenden das Argument `num_cores`, um die Anzahl der TPU-Kerne festzulegen, die Sie verwenden möchten. + +```bash +python xla_spawn.py --num_cores 8 \ + summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + + +Tensor Processing Units (TPUs) sind speziell für die Beschleunigung der Leistung konzipiert. TensorFlow Skripte verwenden eine [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) für das Training auf TPUs. Um eine TPU zu verwenden, übergeben Sie den Namen der TPU-Ressource an das Argument `tpu`. + +```bash +python run_summarization.py \ + --tpu name_of_tpu_resource \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 16 \ + --num_train_epochs 3 \ + --do_train \ + --do_eval +``` + + + +## Führen Sie ein Skript mit 🤗 Accelerate aus. + +🤗 [Accelerate](https://huggingface.co/docs/accelerate) ist eine reine PyTorch-Bibliothek, die eine einheitliche Methode für das Training eines Modells auf verschiedenen Arten von Setups (nur CPU, mehrere GPUs, TPUs) bietet und dabei die vollständige Transparenz der PyTorch-Trainingsschleife beibehält. Stellen Sie sicher, dass Sie 🤗 Accelerate installiert haben, wenn Sie es nicht bereits haben: + +> Hinweis: Da Accelerate schnell weiterentwickelt wird, muss die Git-Version von Accelerate installiert sein, um die Skripte auszuführen. +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +Anstelle des Skripts `run_summarization.py` müssen Sie das Skript `run_summarization_no_trainer.py` verwenden. Die von Accelerate unterstützten Skripte haben eine Datei `task_no_trainer.py` im Ordner. Beginnen Sie mit dem folgenden Befehl, um eine Konfigurationsdatei zu erstellen und zu speichern: + +```bash +accelerate config +``` + +Testen Sie Ihre Einrichtung, um sicherzustellen, dass sie korrekt konfiguriert ist: + +```bash +accelerate test +``` + +Jetzt sind Sie bereit, das Training zu starten: + +```bash +accelerate launch run_summarization_no_trainer.py \ + --model_name_or_path google-t5/t5-small \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir ~/tmp/tst-summarization +``` + +## Verwenden Sie einen benutzerdefinierten Datensatz + +Das Verdichtungsskript unterstützt benutzerdefinierte Datensätze, solange es sich um eine CSV- oder JSON-Line-Datei handelt. Wenn Sie Ihren eigenen Datensatz verwenden, müssen Sie mehrere zusätzliche Argumente angeben: + +- `train_file` und `validation_file` geben den Pfad zu Ihren Trainings- und Validierungsdateien an. +- `text_column` ist der Eingabetext, der zusammengefasst werden soll. +- Summary_column" ist der auszugebende Zieltext. + +Ein Zusammenfassungsskript, das einen benutzerdefinierten Datensatz verwendet, würde wie folgt aussehen: + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --train_file path_to_csv_or_jsonlines_file \ + --validation_file path_to_csv_or_jsonlines_file \ + --text_column text_column_name \ + --summary_column summary_column_name \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --overwrite_output_dir \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate +``` + +## Testen Sie ein Skript + +Es ist oft eine gute Idee, Ihr Skript an einer kleineren Anzahl von Beispielen für Datensätze auszuführen, um sicherzustellen, dass alles wie erwartet funktioniert, bevor Sie sich auf einen ganzen Datensatz festlegen, dessen Fertigstellung Stunden dauern kann. Verwenden Sie die folgenden Argumente, um den Datensatz auf eine maximale Anzahl von Stichproben zu beschränken: + +- `max_train_samples` +- `max_eval_samples` +- `max_predict_samples` + +```bash +python examples/pytorch/summarization/run_summarization.py \ + --model_name_or_path google-t5/t5-small \ + --max_train_samples 50 \ + --max_eval_samples 50 \ + --max_predict_samples 50 \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` + +Nicht alle Beispielskripte unterstützen das Argument `max_predict_samples`. Wenn Sie sich nicht sicher sind, ob Ihr Skript dieses Argument unterstützt, fügen Sie das Argument `-h` hinzu, um dies zu überprüfen: + +```bash +examples/pytorch/summarization/run_summarization.py -h +``` + +## Training vom Kontrollpunkt fortsetzen + +Eine weitere hilfreiche Option, die Sie aktivieren können, ist die Wiederaufnahme des Trainings von einem früheren Kontrollpunkt aus. Auf diese Weise können Sie im Falle einer Unterbrechung Ihres Trainings dort weitermachen, wo Sie aufgehört haben, ohne von vorne beginnen zu müssen. Es gibt zwei Methoden, um das Training von einem Kontrollpunkt aus wieder aufzunehmen. + +Die erste Methode verwendet das Argument `output_dir previous_output_dir`, um das Training ab dem letzten in `output_dir` gespeicherten Kontrollpunkt wieder aufzunehmen. In diesem Fall sollten Sie `overwrite_output_dir` entfernen: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --output_dir previous_output_dir \ + --predict_with_generate +``` + +Die zweite Methode verwendet das Argument `Resume_from_checkpoint path_to_specific_checkpoint`, um das Training ab einem bestimmten Checkpoint-Ordner wieder aufzunehmen. + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --resume_from_checkpoint path_to_specific_checkpoint \ + --predict_with_generate +``` + +## Teilen Sie Ihr Modell + +Alle Skripte können Ihr endgültiges Modell in den [Model Hub](https://huggingface.co/models) hochladen. Stellen Sie sicher, dass Sie bei Hugging Face angemeldet sind, bevor Sie beginnen: + +```bash +huggingface-cli login +``` + +Dann fügen Sie dem Skript das Argument `push_to_hub` hinzu. Mit diesem Argument wird ein Repository mit Ihrem Hugging Face-Benutzernamen und dem in `output_dir` angegebenen Ordnernamen erstellt. + +Wenn Sie Ihrem Repository einen bestimmten Namen geben möchten, fügen Sie ihn mit dem Argument `push_to_hub_model_id` hinzu. Das Repository wird automatisch unter Ihrem Namensraum aufgeführt. + +Das folgende Beispiel zeigt, wie Sie ein Modell mit einem bestimmten Repository-Namen hochladen können: + +```bash +python examples/pytorch/summarization/run_summarization.py + --model_name_or_path google-t5/t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --push_to_hub \ + --push_to_hub_model_id finetuned-t5-cnn_dailymail \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --overwrite_output_dir \ + --predict_with_generate +``` \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/testing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/testing.md new file mode 100644 index 0000000000000000000000000000000000000000..100151e58c3da7a8695615782f9f537d7d93b0e5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/testing.md @@ -0,0 +1,1293 @@ + + +# Testen + + +Werfen wir einen Blick darauf, wie 🤗 Transformers-Modelle getestet werden und wie Sie neue Tests schreiben und die vorhandenen verbessern können. + +Es gibt 2 Testsuiten im Repository: + +1. `tests` -- Tests für die allgemeine API +2. `examples` -- Tests hauptsächlich für verschiedene Anwendungen, die nicht Teil der API sind + +## Wie Transformatoren getestet werden + +1. Sobald ein PR eingereicht wurde, wird er mit 9 CircleCi Jobs getestet. Jeder neue Commit zu diesem PR wird erneut getestet. Diese Aufträge + sind in dieser [Konfigurationsdatei](https://github.com/huggingface/transformers/tree/main/.circleci/config.yml) definiert, so dass Sie bei Bedarf die gleiche Umgebung auf Ihrem Rechner reproduzieren können. + Umgebung auf Ihrem Rechner reproduzieren können. + + Diese CI-Jobs führen keine `@slow`-Tests durch. + +2. Es gibt 3 Jobs, die von [github actions](https://github.com/huggingface/transformers/actions) ausgeführt werden: + + - [torch hub integration](https://github.com/huggingface/transformers/tree/main/.github/workflows/github-torch-hub.yml): prüft, ob die torch hub + Integration funktioniert. + + - [self-hosted (push)](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-push.yml): führt schnelle Tests auf der GPU nur bei Commits auf + `main`. Es wird nur ausgeführt, wenn ein Commit auf `main` den Code in einem der folgenden Ordner aktualisiert hat: `src`, + `tests`, `.github` (um zu verhindern, dass er auf hinzugefügten Modellkarten, Notebooks usw. läuft) + + - [self-hosted runner](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-scheduled.yml): führt normale und langsame Tests auf GPU in + `tests` und `examples`: + +```bash +RUN_SLOW=1 pytest tests/ +RUN_SLOW=1 pytest examples/ +``` + + Die Ergebnisse können Sie [hier](https://github.com/huggingface/transformers/actions) sehen. + + + +## Tests ausführen + + + + + +### Auswahl der auszuführenden Tests + +In diesem Dokument wird ausführlich erläutert, wie Tests ausgeführt werden können. Wenn Sie nach der Lektüre noch mehr Details benötigen +finden Sie diese [hier](https://docs.pytest.org/en/latest/usage.html). + +Hier sind einige der nützlichsten Möglichkeiten, Tests auszuführen. + +Alle ausführen: + +```console +pytest +``` + +oder: + +```bash +make test +``` + +Beachten Sie, dass Letzteres wie folgt definiert ist: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/ +``` + +was pytest anweist: + +- so viele Testprozesse laufen zu lassen, wie es CPU-Kerne gibt (was zu viele sein könnten, wenn Sie nicht über eine Menge RAM verfügen!) +- sicherzustellen, dass alle Tests aus derselben Datei von demselben Testprozess ausgeführt werden +- Erfassen Sie keine Ausgaben +- im ausführlichen Modus laufen lassen + + + +### Abrufen der Liste aller Tests + +Alle Tests der Testsuite: + +```bash +pytest --collect-only -q +``` + +Alle Tests einer bestimmten Testdatei: + +```bash +pytest tests/test_optimization.py --collect-only -q +``` + +### Führen Sie ein bestimmtes Testmodul aus + +Um ein einzelnes Testmodul auszuführen: + +```bash +pytest tests/utils/test_logging.py +``` + +### Spezifische Tests ausführen + +Da unittest in den meisten Tests verwendet wird, müssen Sie, um bestimmte Untertests auszuführen, den Namen der unittest +Klasse, die diese Tests enthält. Er könnte zum Beispiel lauten: + +```bash +pytest tests/test_optimization.py::OptimizationTest::test_adam_w +``` + +Hier: + +- `tests/test_optimization.py` - die Datei mit den Tests +- `OptimizationTest` - der Name der Klasse +- `test_adam_w` - der Name der spezifischen Testfunktion + +Wenn die Datei mehrere Klassen enthält, können Sie auswählen, dass nur die Tests einer bestimmten Klasse ausgeführt werden sollen. Zum Beispiel: + +```bash +pytest tests/test_optimization.py::OptimizationTest +``` + +führt alle Tests innerhalb dieser Klasse aus. + +Wie bereits erwähnt, können Sie sehen, welche Tests in der Klasse `OptimizationTest` enthalten sind, indem Sie sie ausführen: + +```bash +pytest tests/test_optimization.py::OptimizationTest --collect-only -q +``` + +Sie können Tests mit Hilfe von Schlüsselwortausdrücken ausführen. + +Um nur Tests auszuführen, deren Name `adam` enthält: + +```bash +pytest -k adam tests/test_optimization.py +``` + +Die logischen `und` und `oder` können verwendet werden, um anzugeben, ob alle Schlüsselwörter übereinstimmen sollen oder nur eines. `nicht` kann verwendet werden, um +negieren. + +Um alle Tests auszuführen, außer denen, deren Name `adam` enthält: + +```bash +pytest -k "not adam" tests/test_optimization.py +``` + +Und Sie können die beiden Muster in einem kombinieren: + +```bash +pytest -k "ada and not adam" tests/test_optimization.py +``` + +Um zum Beispiel sowohl `test_adafactor` als auch `test_adam_w` auszuführen, können Sie verwenden: + +```bash +pytest -k "test_adam_w or test_adam_w" tests/test_optimization.py +``` + +Beachten Sie, dass wir hier `oder` verwenden, da wir wollen, dass eines der Schlüsselwörter übereinstimmt, um beide einzuschließen. + +Wenn Sie nur Tests einschließen möchten, die beide Muster enthalten, müssen Sie `und` verwenden: + +```bash +pytest -k "test and ada" tests/test_optimization.py +``` + +### Führen Sie `accelerate` Tests durch + +Manchmal müssen Sie `accelerate` Tests für Ihre Modelle ausführen. Dazu fügen Sie einfach `-m accelerate_tests` zu Ihrem Befehl hinzu, wenn Sie diese Tests bei einem `OPT`-Lauf ausführen möchten: +```bash +RUN_SLOW=1 pytest -m accelerate_tests tests/models/opt/test_modeling_opt.py +``` + + +### Dokumentationstests ausführen + +Um zu testen, ob die Dokumentationsbeispiele korrekt sind, sollten Sie überprüfen, ob die `doctests` erfolgreich sind. +Lassen Sie uns als Beispiel den docstring von [WhisperModel.forward](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1017-L1035) verwenden: + +```python +r""" +Returns: + +Example: + ```python + >>> import torch + >>> from transformers import WhisperModel, WhisperFeatureExtractor + >>> from datasets import load_dataset + + >>> model = WhisperModel.from_pretrained("openai/whisper-base") + >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base") + >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt") + >>> input_features = inputs.input_features + >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id + >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + >>> list(last_hidden_state.shape) + [1, 2, 512] + ```""" + +``` + +Führen Sie einfach die folgende Zeile aus, um automatisch jedes docstring-Beispiel in der gewünschten Datei zu testen: +```bash +pytest --doctest-modules +``` +Wenn die Datei eine Markdown-Erweiterung hat, sollten Sie das Argument `--doctest-glob="*.md"` hinzufügen. + +### Nur geänderte Tests ausführen + +Mit [pytest-picked](https://github.com/anapaulagomes/pytest-picked) können Sie die Tests ausführen, die sich auf die unstaged Dateien oder den aktuellen Zweig (gemäß Git) beziehen. Auf diese Weise können Sie schnell testen, ob Ihre Änderungen nichts kaputt gemacht haben. +nichts kaputt gemacht haben, da die Tests für Dateien, die Sie nicht verändert haben, nicht ausgeführt werden. + +```bash +pip install pytest-picked +``` + +```bash +pytest --picked +``` + +Alle Tests werden von Dateien und Ordnern ausgeführt, die geändert, aber noch nicht übergeben wurden. + +### Fehlgeschlagene Tests bei Änderung der Quelle automatisch wiederholen + +[pytest-xdist](https://github.com/pytest-dev/pytest-xdist) bietet eine sehr nützliche Funktion zur Erkennung aller fehlgeschlagenen +Tests zu erkennen und dann darauf zu warten, dass Sie Dateien ändern, um die fehlgeschlagenen Tests so lange zu wiederholen, bis sie erfolgreich sind, während Sie die +sie reparieren. So müssen Sie pytest nicht erneut starten, nachdem Sie die Korrektur vorgenommen haben. Dies wird so lange wiederholt, bis alle Tests bestanden sind. +Danach wird erneut ein vollständiger Durchlauf durchgeführt. + +```bash +pip install pytest-xdist +``` + +So rufen Sie den Modus auf: `pytest -f` oder `pytest --looponfail` + +Datei-Änderungen werden erkannt, indem die Wurzelverzeichnisse von `looponfailroots` und alle ihre Inhalte (rekursiv) untersucht werden. +Wenn die Vorgabe für diesen Wert für Sie nicht funktioniert, können Sie ihn in Ihrem Projekt ändern, indem Sie eine Konfigurations +Option in der Datei `setup.cfg` ändern: + +```ini +[tool:pytest] +looponfailroots = transformers tests +``` + +oder die Dateien `pytest.ini`/`tox.ini``: + +```ini +[pytest] +looponfailroots = transformers tests +``` + +Dies würde dazu führen, dass nur nach Dateiänderungen in den jeweiligen Verzeichnissen gesucht wird, die relativ zum Verzeichnis der ini-Datei angegeben sind. +Verzeichnis. + +[pytest-watch](https://github.com/joeyespo/pytest-watch) ist eine alternative Implementierung dieser Funktionalität. + + +### Überspringen eines Testmoduls + +Wenn Sie alle Testmodule ausführen möchten, mit Ausnahme einiger weniger, können Sie diese ausschließen, indem Sie eine explizite Liste der auszuführenden Tests angeben. Für +Beispiel: Um alle Tests außer `test_modeling_*.py` auszuführen: + +```bash +pytest *ls -1 tests/*py | grep -v test_modeling* +``` + +### Status leeren + +CI-Builds und wenn Isolation wichtig ist (gegen Geschwindigkeit), sollte der Cache geleert werden: + +```bash +pytest --cache-clear tests +``` + +### Tests parallel ausführen + +Wie bereits erwähnt, führt `make test` über das Plugin `pytest-xdist` Tests parallel aus (Argument `-n X`, z.B. `-n 2` +um 2 Jobs parallel laufen zu lassen). + +Mit der Option `--dist=` von `pytest-xdist` können Sie steuern, wie die Tests gruppiert werden. Mit `--dist=loadfile` werden die +Tests, die sich in einer Datei befinden, in denselben Prozess. + +Da die Reihenfolge der ausgeführten Tests unterschiedlich und nicht vorhersehbar ist, kann die Ausführung der Testsuite mit `pytest-xdist` +zu Fehlern führt (was bedeutet, dass wir einige unentdeckte gekoppelte Tests haben), verwenden Sie [pytest-replay](https://github.com/ESSS/pytest-replay), um die Tests in der gleichen Reihenfolge abzuspielen, was dabei helfen sollte +diese fehlgeschlagene Sequenz auf ein Minimum zu reduzieren. + +### Testreihenfolge und Wiederholung + +Es ist gut, die Tests mehrmals zu wiederholen, nacheinander, zufällig oder in Gruppen, um mögliche +Abhängigkeiten und zustandsbezogene Fehler zu erkennen (Abriss). Und die einfache, mehrfache Wiederholung ist einfach gut, um +einige Probleme zu erkennen, die durch die Zufälligkeit von DL aufgedeckt werden. + + +#### Wiederholungstests + +- [pytest-flakefinder](https://github.com/dropbox/pytest-flakefinder): + +```bash +pip install pytest-flakefinder +``` + +Und führen Sie dann jeden Test mehrmals durch (standardmäßig 50): + +```bash +pytest --flake-finder --flake-runs=5 tests/test_failing_test.py +``` + + + +Dieses Plugin funktioniert nicht mit dem `-n` Flag von `pytest-xdist`. + + + + + +Es gibt noch ein anderes Plugin `pytest-repeat`, aber es funktioniert nicht mit `unittest`. + + + +#### Run tests in a random order + +```bash +pip install pytest-random-order +``` + +Wichtig: Das Vorhandensein von `pytest-random-order` sorgt für eine automatische Zufallsanordnung der Tests, es sind keine Konfigurationsänderungen oder +Befehlszeilenoptionen sind nicht erforderlich. + +Wie bereits erläutert, ermöglicht dies die Erkennung von gekoppelten Tests - bei denen der Zustand eines Tests den Zustand eines anderen beeinflusst. Wenn +`pytest-random-order` installiert ist, gibt es den Zufallswert aus, der für diese Sitzung verwendet wurde, z.B: + +```bash +pytest tests +[...] +Using --random-order-bucket=module +Using --random-order-seed=573663 +``` + +Wenn eine bestimmte Sequenz fehlschlägt, können Sie sie reproduzieren, indem Sie genau diesen Seed hinzufügen, z.B: + +```bash +pytest --random-order-seed=573663 +[...] +Using --random-order-bucket=module +Using --random-order-seed=573663 +``` + +Es wird nur dann die exakte Reihenfolge reproduzieren, wenn Sie genau dieselbe Liste von Tests (oder gar keine Liste) verwenden. Sobald Sie beginnen, die Liste +die Liste manuell einzugrenzen, können Sie sich nicht mehr auf den Seed verlassen, sondern müssen die Tests manuell in der genauen Reihenfolge auflisten +auflisten und pytest anweisen, sie nicht zu randomisieren, indem Sie `--random-order-bucket=none` verwenden, z.B.: + +```bash +pytest --random-order-bucket=none tests/test_a.py tests/test_c.py tests/test_b.py +``` + +So deaktivieren Sie das Shuffling für alle Tests: + +```bash +pytest --random-order-bucket=none +``` + +Standardmäßig ist `--random-order-bucket=module` impliziert, wodurch die Dateien auf den Modulebenen gemischt werden. Es kann auch +auf den Ebenen `class`, `package`, `global` und `none` mischen. Die vollständigen Details entnehmen Sie bitte der +[Dokumentation](https://github.com/jbasko/pytest-random-order). + +Eine weitere Alternative zur Randomisierung ist: [`pytest-random`](https://github.com/pytest-dev/pytest-randomly). Dieses +Modul hat eine sehr ähnliche Funktionalität/Schnittstelle, aber es hat nicht die Eimermodi, die in +`pytest-random-order` zur Verfügung. Es hat das gleiche Problem, dass es sich nach der Installation aufdrängt. + +### Variationen von Aussehen und Bedienung + +#### pytest-zucker + +[pytest-sugar](https://github.com/Frozenball/pytest-sugar) ist ein Plugin, das das Erscheinungsbild verbessert, eine +Fortschrittsbalken hinzufügt und Tests, die fehlschlagen, sowie die Bestätigung sofort anzeigt. Es wird bei der Installation automatisch aktiviert. + +```bash +pip install pytest-sugar +``` + +Um Tests ohne sie durchzuführen, führen Sie aus: + +```bash +pytest -p no:sugar +``` + +oder deinstallieren Sie es. + + + +#### Melden Sie den Namen jedes Subtests und seinen Fortschritt + +Für einen einzelnen oder eine Gruppe von Tests über `pytest` (nach `pip install pytest-pspec`): + +```bash +pytest --pspec tests/test_optimization.py +``` + +#### Zeigt fehlgeschlagene Tests sofort an + +[pytest-instafail](https://github.com/pytest-dev/pytest-instafail) zeigt Fehlschläge und Fehler sofort an, anstatt +bis zum Ende der Testsitzung zu warten. + +```bash +pip install pytest-instafail +``` + +```bash +pytest --instafail +``` + +### Zu GPU oder nicht zu GPU + +Bei einem GPU-aktivierten Setup fügen Sie zum Testen im reinen CPU-Modus `CUDA_VISIBLE_DEVICES=""` hinzu: + +```bash +CUDA_VISIBLE_DEVICES="" pytest tests/utils/test_logging.py +``` + +oder wenn Sie mehrere Grafikprozessoren haben, können Sie angeben, welcher von `pytest` verwendet werden soll. Wenn Sie zum Beispiel nur den +zweiten Grafikkarte zu verwenden, wenn Sie die Grafikkarten `0` und `1` haben, können Sie folgendes ausführen: + +```bash +CUDA_VISIBLE_DEVICES="1" pytest tests/utils/test_logging.py +``` + +Dies ist praktisch, wenn Sie verschiedene Aufgaben auf verschiedenen GPUs ausführen möchten. + +Einige Tests müssen nur auf der CPU ausgeführt werden, andere entweder auf der CPU, der GPU oder der TPU und wieder andere auf mehreren GPUs. Die folgenden skip +Dekorateure werden verwendet, um die Anforderungen von Tests in Bezug auf CPU/GPU/TPU festzulegen: + +- `require_torch` - dieser Test wird nur unter Torch ausgeführt +- `require_torch_gpu` - wie `require_torch` plus erfordert mindestens 1 GPU +- `require_torch_multi_gpu` - wie `require_torch` und zusätzlich mindestens 2 GPUs erforderlich +- `require_torch_non_multi_gpu` - wie `require_torch` plus benötigt 0 oder 1 GPUs +- `require_torch_up_to_2_gpus` - wie `require_torch` plus erfordert 0 oder 1 oder 2 GPUs +- `require_torch_xla` - wie `require_torch` plus erfordert mindestens 1 TPU + +Lassen Sie uns die GPU-Anforderungen in der folgenden Tabelle darstellen: + + +| n gpus | decorator | +|--------|--------------------------------| +| `>= 0` | `@require_torch` | +| `>= 1` | `@require_torch_gpu` | +| `>= 2` | `@require_torch_multi_gpu` | +| `< 2` | `@require_torch_non_multi_gpu` | +| `< 3` | `@require_torch_up_to_2_gpus` | + + +Hier ist zum Beispiel ein Test, der nur ausgeführt werden muss, wenn 2 oder mehr GPUs verfügbar sind und pytorch installiert ist: + +```python no-style +@require_torch_multi_gpu +def test_example_with_multi_gpu(): +``` + +Wenn ein Test `tensorflow` benötigt, verwenden Sie den Dekorator `require_tf`. Zum Beispiel: + +```python no-style +@require_tf +def test_tf_thing_with_tensorflow(): +``` + +Diese Dekors können gestapelt werden. Wenn zum Beispiel ein Test langsam ist und mindestens eine GPU unter pytorch benötigt, können Sie +wie Sie ihn einrichten können: + +```python no-style +@require_torch_gpu +@slow +def test_example_slow_on_gpu(): +``` + +Einige Dekoratoren wie `@parametrized` schreiben Testnamen um, daher müssen `@require_*`-Sprungdekoratoren als letztes aufgeführt werden. +zuletzt aufgeführt werden, damit sie korrekt funktionieren. Hier ist ein Beispiel für die korrekte Verwendung: + +```python no-style +@parameterized.expand(...) +@require_torch_multi_gpu +def test_integration_foo(): +``` + +Dieses Problem mit der Reihenfolge gibt es bei `@pytest.mark.parametrize` nicht, Sie können es an den Anfang oder an den Schluss setzen und es wird trotzdem funktionieren. +funktionieren. Aber es funktioniert nur bei Nicht-Unittests. + +Innerhalb von Tests: + +- Wie viele GPUs sind verfügbar: + +```python +from transformers.testing_utils import get_gpu_count + +n_gpu = get_gpu_count() # works with torch and tf +``` + +### Testen mit einem bestimmten PyTorch-Backend oder Gerät + +Um die Testsuite auf einem bestimmten Torch-Gerät auszuführen, fügen Sie `TRANSFORMERS_TEST_DEVICE="$Gerät"` hinzu, wobei `$Gerät` das Ziel-Backend ist. Zum Beispiel, um nur auf der CPU zu testen: +```bash +TRANSFORMERS_TEST_DEVICE="cpu" pytest tests/utils/test_logging.py +``` + +Diese Variable ist nützlich, um benutzerdefinierte oder weniger verbreitete PyTorch-Backends wie `mps` zu testen. Sie kann auch verwendet werden, um den gleichen Effekt wie `CUDA_VISIBLE_DEVICES` zu erzielen, indem Sie bestimmte GPUs anvisieren oder im reinen CPU-Modus testen. + +Bestimmte Geräte erfordern einen zusätzlichen Import, nachdem Sie `torch` zum ersten Mal importiert haben. Dies kann über die Umgebungsvariable `TRANSFORMERS_TEST_BACKEND` festgelegt werden: +```bash +TRANSFORMERS_TEST_BACKEND="torch_npu" pytest tests/utils/test_logging.py +``` + + +### Verteiltes Training + +`pytest` kann nicht direkt mit verteiltem Training umgehen. Wenn dies versucht wird, tun die Unterprozesse nicht das Richtige +und denken am Ende, sie seien `pytest` und beginnen, die Testsuite in Schleifen auszuführen. Es funktioniert jedoch, wenn man +einen normalen Prozess erzeugt, der dann mehrere Worker erzeugt und die IO-Pipes verwaltet. + +Hier sind einige Tests, die dies verwenden: + +- [test_trainer_distributed.py](https://github.com/huggingface/transformers/tree/main/tests/trainer/test_trainer_distributed.py) +- [test_deepspeed.py](https://github.com/huggingface/transformers/tree/main/tests/deepspeed/test_deepspeed.py) + +Um direkt mit der Ausführung zu beginnen, suchen Sie in diesen Tests nach dem Aufruf `execute_subprocess_async`. + +Sie benötigen mindestens 2 GPUs, um diese Tests in Aktion zu sehen: + +```bash +CUDA_VISIBLE_DEVICES=0,1 RUN_SLOW=1 pytest -sv tests/test_trainer_distributed.py +``` + +### Erfassung von Ausgaben + +Während der Testausführung werden alle Ausgaben, die an `stdout` und `stderr` gesendet werden, aufgezeichnet. Wenn ein Test oder eine Setup-Methode fehlschlägt, wird die +wird die entsprechende aufgezeichnete Ausgabe in der Regel zusammen mit dem Fehler-Traceback angezeigt. + +Um die Aufzeichnung von Ausgaben zu deaktivieren und `stdout` und `stderr` normal zu erhalten, verwenden Sie `-s` oder `--capture=no`: + +```bash +pytest -s tests/utils/test_logging.py +``` + +So senden Sie Testergebnisse an die JUnit-Formatausgabe: + +```bash +py.test tests --junitxml=result.xml +``` + +### Farbsteuerung + +Keine Farbe zu haben (z.B. gelb auf weißem Hintergrund ist nicht lesbar): + +```bash +pytest --color=no tests/utils/test_logging.py +``` + +### Testbericht an den Online-Dienst pastebin senden + +Erstellen Sie eine URL für jeden Testfehler: + +```bash +pytest --pastebin=failed tests/utils/test_logging.py +``` + +Dadurch werden Informationen über den Testlauf an einen entfernten Paste-Dienst übermittelt und eine URL für jeden Fehlschlag bereitgestellt. Sie können die +Tests wie gewohnt auswählen oder z.B. -x hinzufügen, wenn Sie nur einen bestimmten Fehler senden möchten. + +Erstellen einer URL für ein ganzes Testsitzungsprotokoll: + +```bash +pytest --pastebin=all tests/utils/test_logging.py +``` + +## Tests schreiben + +🤗 Die Tests von Transformers basieren auf `unittest`, werden aber von `pytest` ausgeführt, so dass die meiste Zeit Funktionen aus beiden Systemen +verwendet werden können. + +Sie können [hier](https://docs.pytest.org/en/stable/unittest.html) nachlesen, welche Funktionen unterstützt werden, aber das Wichtigste ist +Wichtig ist, dass die meisten `pytest`-Fixtures nicht funktionieren. Auch die Parametrisierung nicht, aber wir verwenden das Modul +`parametrisiert`, das auf ähnliche Weise funktioniert. + + +### Parametrisierung + +Oft besteht die Notwendigkeit, denselben Test mehrmals auszuführen, aber mit unterschiedlichen Argumenten. Das könnte innerhalb des Tests geschehen +des Tests gemacht werden, aber dann gibt es keine Möglichkeit, den Test mit nur einem Satz von Argumenten auszuführen. + +```python +# test_this1.py +import unittest +from parameterized import parameterized + + +class TestMathUnitTest(unittest.TestCase): + @parameterized.expand( + [ + ("negative", -1.5, -2.0), + ("integer", 1, 1.0), + ("large fraction", 1.6, 1), + ] + ) + def test_floor(self, name, input, expected): + assert_equal(math.floor(input), expected) +``` + +Nun wird dieser Test standardmäßig 3 Mal ausgeführt, wobei jedes Mal die letzten 3 Argumente von `test_floor` den entsprechenden Argumenten in der Parameterliste zugeordnet werden. +die entsprechenden Argumente in der Parameterliste. + +Sie können auch nur die Parameter `negativ` und `ganzzahlig` mit ausführen: + +```bash +pytest -k "negative and integer" tests/test_mytest.py +``` + +oder alle Untertests außer `negativ`, mit: + +```bash +pytest -k "not negative" tests/test_mytest.py +``` + +Neben der Verwendung des gerade erwähnten Filters `-k` können Sie auch den genauen Namen jedes Untertests herausfinden und jeden +oder alle unter Verwendung ihrer genauen Namen ausführen. + +```bash +pytest test_this1.py --collect-only -q +``` + +und es wird aufgelistet: + +```bash +test_this1.py::TestMathUnitTest::test_floor_0_negative +test_this1.py::TestMathUnitTest::test_floor_1_integer +test_this1.py::TestMathUnitTest::test_floor_2_large_fraction +``` + +Jetzt können Sie also nur 2 spezifische Untertests durchführen: + +```bash +pytest test_this1.py::TestMathUnitTest::test_floor_0_negative test_this1.py::TestMathUnitTest::test_floor_1_integer +``` + +Das Modul [parametrisiert](https://pypi.org/project/parameterized/), das sich bereits in den Entwickler-Abhängigkeiten befindet +von `transformers` befindet, funktioniert sowohl für `unittests` als auch für `pytest` Tests. + +Wenn es sich bei dem Test jedoch nicht um einen `Unittest` handelt, können Sie `pytest.mark.parametrize` verwenden (oder Sie können sehen, dass es in +einigen bestehenden Tests verwendet wird, meist unter `Beispiele`). + +Hier ist das gleiche Beispiel, diesmal unter Verwendung der `parametrize`-Markierung von `pytest`: + +```python +# test_this2.py +import pytest + + +@pytest.mark.parametrize( + "name, input, expected", + [ + ("negative", -1.5, -2.0), + ("integer", 1, 1.0), + ("large fraction", 1.6, 1), + ], +) +def test_floor(name, input, expected): + assert_equal(math.floor(input), expected) +``` + +Genau wie bei `parametrisiert` können Sie mit `pytest.mark.parametrize` genau steuern, welche Subtests ausgeführt werden +ausgeführt werden, wenn der Filter `-k` nicht ausreicht. Allerdings erzeugt diese Parametrisierungsfunktion einen etwas anderen Satz von +Namen für die Untertests. Sie sehen folgendermaßen aus: + +```bash +pytest test_this2.py --collect-only -q +``` + +und es wird aufgelistet: + +```bash +test_this2.py::test_floor[integer-1-1.0] +test_this2.py::test_floor[negative--1.5--2.0] +test_this2.py::test_floor[large fraction-1.6-1] +``` + +Jetzt können Sie also nur den spezifischen Test durchführen: + +```bash +pytest test_this2.py::test_floor[negative--1.5--2.0] test_this2.py::test_floor[integer-1-1.0] +``` + +wie im vorherigen Beispiel. + + + +### Dateien und Verzeichnisse + +In Tests müssen wir oft wissen, wo sich Dinge relativ zur aktuellen Testdatei befinden, und das ist nicht trivial, da der Test +von mehreren Verzeichnissen aus aufgerufen werden kann oder sich in Unterverzeichnissen mit unterschiedlicher Tiefe befinden kann. Eine Hilfsklasse +`transformers.test_utils.TestCasePlus` löst dieses Problem, indem sie alle grundlegenden Pfade sortiert und einfache +Zugriffsmöglichkeiten auf sie bietet: + +- `pathlib`-Objekte (alle vollständig aufgelöst): + + - `test_file_path` - der aktuelle Testdateipfad, d.h. `__file__` + - `test_file_dir` - das Verzeichnis, das die aktuelle Testdatei enthält + - `tests_dir` - das Verzeichnis der `tests` Testreihe + - `examples_dir` - das Verzeichnis der `examples` Test-Suite + - `repo_root_dir` - das Verzeichnis des Repositorys + - `src_dir` - das Verzeichnis von `src` (d.h. wo sich das Unterverzeichnis `transformers` befindet) + +- stringifizierte Pfade - wie oben, aber diese geben Pfade als Strings zurück, anstatt als `pathlib`-Objekte: + + - `test_file_path_str` + - `test_file_dir_str` + - `tests_dir_str` + - `examples_dir_str` + - `repo_root_dir_str` + - `src_dir_str` + +Um diese zu verwenden, müssen Sie lediglich sicherstellen, dass der Test in einer Unterklasse von +`transformers.test_utils.TestCasePlus` befindet. Zum Beispiel: + +```python +from transformers.testing_utils import TestCasePlus + + +class PathExampleTest(TestCasePlus): + def test_something_involving_local_locations(self): + data_dir = self.tests_dir / "fixtures/tests_samples/wmt_en_ro" +``` + +Wenn Sie Pfade nicht über `pathlib` manipulieren müssen oder nur einen Pfad als String benötigen, können Sie jederzeit +`str()` auf das `pathlib`-Objekt anwenden oder die Accessoren mit der Endung `_str` verwenden. Zum Beispiel: + +```python +from transformers.testing_utils import TestCasePlus + + +class PathExampleTest(TestCasePlus): + def test_something_involving_stringified_locations(self): + examples_dir = self.examples_dir_str +``` + +### Temporäre Dateien und Verzeichnisse + +Die Verwendung eindeutiger temporärer Dateien und Verzeichnisse ist für die parallele Durchführung von Tests unerlässlich, damit sich die Tests nicht gegenseitig überschreiben. +Daten gegenseitig überschreiben. Außerdem möchten wir, dass die temporären Dateien und Verzeichnisse am Ende jedes Tests, der sie erstellt hat, gelöscht werden. +erstellt hat. Daher ist die Verwendung von Paketen wie `tempfile`, die diese Anforderungen erfüllen, unerlässlich. + +Beim Debuggen von Tests müssen Sie jedoch sehen können, was in der temporären Datei oder dem temporären Verzeichnis gespeichert wird und Sie möchten +Sie müssen den genauen Pfad kennen und dürfen ihn nicht bei jedem neuen Testdurchlauf zufällig ändern. + +Für solche Zwecke ist die Hilfsklasse `transformers.test_utils.TestCasePlus` am besten geeignet. Sie ist eine Unterklasse von +Unittest.TestCase`, so dass wir in den Testmodulen einfach von ihr erben können. + +Hier ist ein Beispiel für die Verwendung dieser Klasse: + +```python +from transformers.testing_utils import TestCasePlus + + +class ExamplesTests(TestCasePlus): + def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir() +``` + +Dieser Code erstellt ein eindeutiges temporäres Verzeichnis und setzt `tmp_dir` auf dessen Speicherort. + +- Erstellen Sie ein eindeutiges temporäres Verzeichnis: + +```python +def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir() +``` + +tmp_dir" enthält den Pfad zu dem erstellten temporären Verzeichnis. Es wird am Ende des Tests automatisch entfernt. +Tests entfernt. + +- Erstellen Sie ein temporäres Verzeichnis meiner Wahl, stellen Sie sicher, dass es leer ist, bevor der Test beginnt, und leeren Sie es nach dem Test nicht. + +```python +def test_whatever(self): + tmp_dir = self.get_auto_remove_tmp_dir("./xxx") +``` + +Dies ist nützlich für die Fehlersuche, wenn Sie ein bestimmtes Verzeichnis überwachen und sicherstellen möchten, dass die vorherigen Tests keine Daten darin hinterlassen haben. +keine Daten dort hinterlassen haben. + +- Sie können das Standardverhalten außer Kraft setzen, indem Sie die Argumente `before` und `after` direkt überschreiben, was zu einem der folgenden Verhaltensweisen führt + folgenden Verhaltensweisen: + + - `before=True`: das temporäre Verzeichnis wird immer zu Beginn des Tests gelöscht. + - `before=False`: wenn das temporäre Verzeichnis bereits existiert, bleiben alle vorhandenen Dateien dort erhalten. + - `after=True`: das temporäre Verzeichnis wird immer am Ende des Tests gelöscht. + - `after=False`: das temporäre Verzeichnis wird am Ende des Tests immer beibehalten. + + + +Um das Äquivalent von `rm -r` sicher ausführen zu können, sind nur Unterverzeichnisse des Projektarchivs checkout erlaubt, wenn +ein explizites `tmp_dir` verwendet wird, so dass nicht versehentlich ein `/tmp` oder ein ähnlich wichtiger Teil des Dateisystems vernichtet wird. +d.h. geben Sie bitte immer Pfade an, die mit `./` beginnen. + + + + + +Jeder Test kann mehrere temporäre Verzeichnisse registrieren, die alle automatisch entfernt werden, sofern nicht anders gewünscht. +anders. + + + +### Temporäre Überschreibung von sys.path + +Wenn Sie `sys.path` vorübergehend überschreiben müssen, um z.B. von einem anderen Test zu importieren, können Sie den +Kontextmanager `ExtendSysPath` verwenden. Beispiel: + + +```python +import os +from transformers.testing_utils import ExtendSysPath + +bindir = os.path.abspath(os.path.dirname(__file__)) +with ExtendSysPath(f"{bindir}/.."): + from test_trainer import TrainerIntegrationCommon # noqa +``` + +### Überspringen von Tests + +Dies ist nützlich, wenn ein Fehler gefunden und ein neuer Test geschrieben wird, der Fehler aber noch nicht behoben ist. Damit wir ihn +in das Haupt-Repository zu übertragen, müssen wir sicherstellen, dass er bei `make test` übersprungen wird. + +Methoden: + +- Ein **Skip** bedeutet, dass Sie erwarten, dass Ihr Test nur dann erfolgreich ist, wenn einige Bedingungen erfüllt sind, andernfalls sollte pytest den Test überspringen. + die Ausführung des Tests ganz überspringen. Übliche Beispiele sind das Überspringen von Tests, die nur unter Windows laufen, auf Nicht-Windows-Plattformen oder das Überspringen von + Tests, die von einer externen Ressource abhängen, die im Moment nicht verfügbar ist (z.B. eine Datenbank). + +- Ein **xfail** bedeutet, dass Sie erwarten, dass ein Test aus irgendeinem Grund fehlschlägt. Ein gängiges Beispiel ist ein Test für eine Funktion, die noch nicht + noch nicht implementiert oder ein noch nicht behobener Fehler. Wenn ein Test trotz eines erwarteten Fehlschlags bestanden wird (markiert mit + pytest.mark.xfail), ist dies ein xpass und wird in der Testzusammenfassung gemeldet. + +Einer der wichtigsten Unterschiede zwischen den beiden ist, dass `skip` den Test nicht ausführt, während `xfail` dies tut. Wenn also der +Code, der fehlerhaft ist, einen schlechten Zustand verursacht, der sich auf andere Tests auswirkt, sollten Sie also nicht `xfail` verwenden. + +#### Implementierung + +- Hier sehen Sie, wie Sie einen ganzen Test bedingungslos überspringen können: + +```python no-style +@unittest.skip(reason="this bug needs to be fixed") +def test_feature_x(): +``` + +oder mit pytest: + +```python no-style +@pytest.mark.skip(reason="this bug needs to be fixed") +``` + +oder mit dem `xfail` Weg: + +```python no-style +@pytest.mark.xfail +def test_feature_x(): +``` + +- Hier erfahren Sie, wie Sie einen Test aufgrund einer internen Prüfung innerhalb des Tests auslassen können: + +```python +def test_feature_x(): + if not has_something(): + pytest.skip("unsupported configuration") +``` + +oder das ganze Modul: + +```python +import pytest + +if not pytest.config.getoption("--custom-flag"): + pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True) +``` + +oder mit dem `xfail` Weg: + +```python +def test_feature_x(): + pytest.xfail("expected to fail until bug XYZ is fixed") +``` + +- Hier erfahren Sie, wie Sie alle Tests in einem Modul überspringen können, wenn ein Import fehlt: + +```python +docutils = pytest.importorskip("docutils", minversion="0.3") +``` + +- Einen Test aufgrund einer Bedingung überspringen: + +```python no-style +@pytest.mark.skipif(sys.version_info < (3,6), reason="requires python3.6 or higher") +def test_feature_x(): +``` + +oder: + +```python no-style +@unittest.skipIf(torch_device == "cpu", "Can't do half precision") +def test_feature_x(): +``` + +oder überspringen Sie das ganze Modul: + +```python no-style +@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows") +class TestClass(): + def test_feature_x(self): +``` + +Weitere Details, Beispiele und Möglichkeiten finden Sie [hier](https://docs.pytest.org/en/latest/skipping.html). + +### Langsame Tests + +Die Bibliothek der Tests wächst ständig, und einige der Tests brauchen Minuten, um ausgeführt zu werden, daher können wir es uns nicht leisten, eine Stunde zu warten, bis die +eine Stunde auf die Fertigstellung der Testsuite auf CI zu warten. Daher sollten langsame Tests, mit einigen Ausnahmen für wichtige Tests, wie im folgenden Beispiel +wie im folgenden Beispiel markiert werden: + +```python no-style +from transformers.testing_utils import slow +@slow +def test_integration_foo(): +``` + +Sobald ein Test als `@slow` markiert ist, setzen Sie die Umgebungsvariable `RUN_SLOW=1`, um solche Tests auszuführen, z.B: + +```bash +RUN_SLOW=1 pytest tests +``` + +Einige Dekoratoren wie `@parameterized` schreiben Testnamen um, daher müssen `@slow` und die übrigen Skip-Dekoratoren +`@require_*` müssen als letztes aufgeführt werden, damit sie korrekt funktionieren. Hier ist ein Beispiel für die korrekte Verwendung: + +```python no-style +@parameterized.expand(...) +@slow +def test_integration_foo(): +``` + +Wie zu Beginn dieses Dokuments erläutert, werden langsame Tests nach einem Zeitplan ausgeführt und nicht in PRs CI +Prüfungen. Es ist also möglich, dass einige Probleme bei der Einreichung eines PRs übersehen werden und zusammengeführt werden. Solche Probleme werden +werden beim nächsten geplanten CI-Job abgefangen. Das bedeutet aber auch, dass es wichtig ist, die langsamen Tests auf Ihrem +Rechner auszuführen, bevor Sie den PR einreichen. + +Hier ist ein grober Entscheidungsmechanismus für die Auswahl der Tests, die als langsam markiert werden sollen: + +Wenn der Test auf eine der internen Komponenten der Bibliothek ausgerichtet ist (z.B. Modellierungsdateien, Tokenisierungsdateien, +Pipelines), dann sollten wir diesen Test in der nicht langsamen Testsuite ausführen. Wenn er sich auf einen anderen Aspekt der Bibliothek bezieht, +wie z.B. die Dokumentation oder die Beispiele, dann sollten wir diese Tests in der langsamen Testsuite durchführen. Und dann, zur Verfeinerung +Ansatz zu verfeinern, sollten wir Ausnahmen einführen: + +- Alle Tests, die einen umfangreichen Satz von Gewichten oder einen Datensatz mit einer Größe von mehr als ~50MB herunterladen müssen (z.B. Modell- oder + Tokenizer-Integrationstests, Pipeline-Integrationstests) sollten auf langsam gesetzt werden. Wenn Sie ein neues Modell hinzufügen, sollten Sie + sollten Sie eine kleine Version des Modells (mit zufälligen Gewichtungen) für Integrationstests erstellen und in den Hub hochladen. Dies wird + wird in den folgenden Abschnitten erläutert. +- Alle Tests, die ein Training durchführen müssen, das nicht speziell auf Schnelligkeit optimiert ist, sollten auf langsam gesetzt werden. +- Wir können Ausnahmen einführen, wenn einige dieser Tests, die nicht langsam sein sollten, unerträglich langsam sind, und sie auf + `@slow`. Auto-Modellierungstests, die große Dateien auf der Festplatte speichern und laden, sind ein gutes Beispiel für Tests, die als + als `@slow` markiert sind. +- Wenn ein Test in weniger als 1 Sekunde auf CI abgeschlossen wird (einschließlich eventueller Downloads), sollte es sich trotzdem um einen normalen Test handeln. + +Insgesamt müssen alle nicht langsamen Tests die verschiedenen Interna abdecken und dabei schnell bleiben. Zum Beispiel, +kann eine signifikante Abdeckung erreicht werden, indem Sie mit speziell erstellten kleinen Modellen mit zufälligen Gewichten testen. Solche Modelle +haben eine sehr geringe Anzahl von Schichten (z.B. 2), Vokabeln (z.B. 1000), usw. Dann können die `@slow`-Tests große +langsame Modelle verwenden, um qualitative Tests durchzuführen. Um die Verwendung dieser Modelle zu sehen, suchen Sie einfach nach *winzigen* Modellen mit: + +```bash +grep tiny tests examples +``` + +Hier ist ein Beispiel für ein [Skript](https://github.com/huggingface/transformers/tree/main/scripts/fsmt/fsmt-make-tiny-model.py), das das winzige Modell erstellt hat +[stas/tiny-wmt19-en-de](https://huggingface.co/stas/tiny-wmt19-en-de). Sie können es ganz einfach an Ihre eigene +Architektur Ihres Modells anpassen. + +Es ist leicht, die Laufzeit falsch zu messen, wenn zum Beispiel ein großes Modell heruntergeladen wird, aber wenn +Sie es lokal testen, würden die heruntergeladenen Dateien zwischengespeichert und somit die Download-Zeit nicht gemessen werden. Prüfen Sie daher den +Ausführungsgeschwindigkeitsbericht in den CI-Protokollen (die Ausgabe von `pytest --durations=0 tests`). + +Dieser Bericht ist auch nützlich, um langsame Ausreißer zu finden, die nicht als solche gekennzeichnet sind oder die neu geschrieben werden müssen, um schnell zu sein. +Wenn Sie bemerken, dass die Testsuite beim CI langsam wird, zeigt die oberste Liste dieses Berichts die langsamsten +Tests. + + +### Testen der stdout/stderr-Ausgabe + +Um Funktionen zu testen, die in `stdout` und/oder `stderr` schreiben, kann der Test auf diese Ströme zugreifen, indem er die +[capsys system](https://docs.pytest.org/en/latest/capture.html) von `pytest` zugreifen. So wird dies bewerkstelligt: + +```python +import sys + + +def print_to_stdout(s): + print(s) + + +def print_to_stderr(s): + sys.stderr.write(s) + + +def test_result_and_stdout(capsys): + msg = "Hello" + print_to_stdout(msg) + print_to_stderr(msg) + out, err = capsys.readouterr() # consume the captured output streams + # optional: if you want to replay the consumed streams: + sys.stdout.write(out) + sys.stderr.write(err) + # test: + assert msg in out + assert msg in err +``` + +Und natürlich wird `stderr` in den meisten Fällen als Teil einer Ausnahme auftreten, so dass try/except in einem solchen Fall verwendet werden muss +Fall verwendet werden: + +```python +def raise_exception(msg): + raise ValueError(msg) + + +def test_something_exception(): + msg = "Not a good value" + error = "" + try: + raise_exception(msg) + except Exception as e: + error = str(e) + assert msg in error, f"{msg} is in the exception:\n{error}" +``` + +Ein anderer Ansatz zur Erfassung von stdout ist `contextlib.redirect_stdout`: + +```python +from io import StringIO +from contextlib import redirect_stdout + + +def print_to_stdout(s): + print(s) + + +def test_result_and_stdout(): + msg = "Hello" + buffer = StringIO() + with redirect_stdout(buffer): + print_to_stdout(msg) + out = buffer.getvalue() + # optional: if you want to replay the consumed streams: + sys.stdout.write(out) + # test: + assert msg in out +``` + +Ein wichtiges potenzielles Problem beim Erfassen von stdout ist, dass es `r` Zeichen enthalten kann, die bei normalem `print` +alles zurücksetzen, was bisher gedruckt wurde. Mit `pytest` gibt es kein Problem, aber mit `pytest -s` werden diese +werden diese Zeichen in den Puffer aufgenommen. Um den Test mit und ohne `-s` laufen zu lassen, müssen Sie also eine zusätzliche Bereinigung +zusätzliche Bereinigung der erfassten Ausgabe vornehmen, indem Sie `re.sub(r'~.*\r', '', buf, 0, re.M)` verwenden. + +Aber dann haben wir einen Hilfskontextmanager-Wrapper, der sich automatisch um alles kümmert, unabhängig davon, ob er +einige "*.*.*.*" enthält oder nicht: + +```python +from transformers.testing_utils import CaptureStdout + +with CaptureStdout() as cs: + function_that_writes_to_stdout() +print(cs.out) +``` + +Hier ist ein vollständiges Testbeispiel: + +```python +from transformers.testing_utils import CaptureStdout + +msg = "Secret message\r" +final = "Hello World" +with CaptureStdout() as cs: + print(msg + final) +assert cs.out == final + "\n", f"captured: {cs.out}, expecting {final}" +``` + +Wenn Sie `stderr` aufzeichnen möchten, verwenden Sie stattdessen die Klasse `CaptureStderr`: + +```python +from transformers.testing_utils import CaptureStderr + +with CaptureStderr() as cs: + function_that_writes_to_stderr() +print(cs.err) +``` + +Wenn Sie beide Streams auf einmal erfassen müssen, verwenden Sie die übergeordnete Klasse `CaptureStd`: + +```python +from transformers.testing_utils import CaptureStd + +with CaptureStd() as cs: + function_that_writes_to_stdout_and_stderr() +print(cs.err, cs.out) +``` + +Um das Debuggen von Testproblemen zu erleichtern, geben diese Kontextmanager standardmäßig die aufgezeichneten Streams beim Verlassen +aus dem Kontext wieder. + + +### Erfassen von Logger-Streams + +Wenn Sie die Ausgabe eines Loggers validieren müssen, können Sie `CaptureLogger` verwenden: + +```python +from transformers import logging +from transformers.testing_utils import CaptureLogger + +msg = "Testing 1, 2, 3" +logging.set_verbosity_info() +logger = logging.get_logger("transformers.models.bart.tokenization_bart") +with CaptureLogger(logger) as cl: + logger.info(msg) +assert cl.out, msg + "\n" +``` + +### Testen mit Umgebungsvariablen + +Wenn Sie die Auswirkungen von Umgebungsvariablen für einen bestimmten Test testen möchten, können Sie einen Hilfsdekorator verwenden +`transformers.testing_utils.mockenv` + +```python +from transformers.testing_utils import mockenv + + +class HfArgumentParserTest(unittest.TestCase): + @mockenv(TRANSFORMERS_VERBOSITY="error") + def test_env_override(self): + env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) +``` + +Manchmal muss ein externes Programm aufgerufen werden, was die Einstellung von `PYTHONPATH` in `os.environ` erfordert, um mehrere lokale Pfade einzuschließen. +mehrere lokale Pfade. Eine Hilfsklasse `transformers.test_utils.TestCasePlus` hilft Ihnen dabei: + +```python +from transformers.testing_utils import TestCasePlus + + +class EnvExampleTest(TestCasePlus): + def test_external_prog(self): + env = self.get_env() + # now call the external program, passing `env` to it +``` + +Je nachdem, ob die Testdatei in der Testsuite `tests` oder in `examples` war, wird sie korrekt eingerichtet +`env[PYTHONPATH]` eines dieser beiden Verzeichnisse und auch das `src` Verzeichnis, um sicherzustellen, dass der Test gegen das aktuelle +um sicherzustellen, dass der Test mit dem aktuellen Projektarchiv durchgeführt wird, und schließlich mit dem, was in `env[PYTHONPATH]` bereits eingestellt war, bevor der Test aufgerufen wurde. +wenn überhaupt. + +Diese Hilfsmethode erstellt eine Kopie des Objekts `os.environ`, so dass das Original intakt bleibt. + + +### Reproduzierbare Ergebnisse erhalten + +In manchen Situationen möchten Sie vielleicht die Zufälligkeit Ihrer Tests beseitigen. Um identische, reproduzierbare Ergebnisse zu erhalten, müssen Sie +müssen Sie den Seed festlegen: + +```python +seed = 42 + +# python RNG +import random + +random.seed(seed) + +# pytorch RNGs +import torch + +torch.manual_seed(seed) +torch.backends.cudnn.deterministic = True +if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + +# numpy RNG +import numpy as np + +np.random.seed(seed) + +# tf RNG +tf.random.set_seed(seed) +``` + +### Tests debuggen + +Um einen Debugger an der Stelle zu starten, an der die Warnung auftritt, gehen Sie wie folgt vor: + +```bash +pytest tests/utils/test_logging.py -W error::UserWarning --pdb +``` + +## Arbeiten mit Github-Aktionen-Workflows + +Um einen CI-Job für einen Self-Push-Workflow auszulösen, müssen Sie: + +1. Erstellen Sie einen neuen Zweig auf `transformers` Ursprung (keine Gabelung!). +2. Der Name der Verzweigung muss entweder mit `ci_` oder `ci-` beginnen (`main` löst ihn auch aus, aber wir können keine PRs auf + `main`). Es wird auch nur für bestimmte Pfade ausgelöst - Sie können die aktuelle Definition finden, falls sie + falls sie sich seit der Erstellung dieses Dokuments geändert hat [hier](https://github.com/huggingface/transformers/blob/main/.github/workflows/self-push.yml) unter *push:* +3. Erstellen Sie einen PR von diesem Zweig. +4. Dann können Sie sehen, wie der Job erscheint [hier](https://github.com/huggingface/transformers/actions/workflows/self-push.yml). Er wird möglicherweise nicht sofort ausgeführt, wenn es + ein Backlog vorhanden ist. + + + + +## Testen experimenteller CI-Funktionen + +Das Testen von CI-Funktionen kann potenziell problematisch sein, da es die normale CI-Funktion beeinträchtigen kann. Wenn also eine +neue CI-Funktion hinzugefügt werden soll, sollte dies wie folgt geschehen. + +1. Erstellen Sie einen neuen Auftrag, der die zu testende Funktion testet. +2. Der neue Job muss immer erfolgreich sein, so dass er uns ein grünes ✓ gibt (Details unten). +3. Lassen Sie ihn einige Tage lang laufen, um zu sehen, dass eine Vielzahl verschiedener PR-Typen darauf laufen (Benutzer-Gabelzweige, + nicht geforkte Zweige, Zweige, die von github.com UI direct file edit stammen, verschiedene erzwungene Pushes, etc. - es gibt + es gibt so viele), während Sie die Protokolle des experimentellen Jobs überwachen (nicht den gesamten Job grün, da er absichtlich immer + grün) +4. Wenn klar ist, dass alles in Ordnung ist, fügen Sie die neuen Änderungen in die bestehenden Jobs ein. + +Auf diese Weise wird der normale Arbeitsablauf nicht durch Experimente mit der CI-Funktionalität selbst beeinträchtigt. + +Wie können wir nun dafür sorgen, dass der Auftrag immer erfolgreich ist, während die neue CI-Funktion entwickelt wird? + +Einige CIs, wie TravisCI, unterstützen ignore-step-failure und melden den gesamten Job als erfolgreich, aber CircleCI und +Github Actions unterstützen dies zum jetzigen Zeitpunkt nicht. + +Sie können also die folgende Abhilfe verwenden: + +1. Setzen Sie `set +euo pipefail` am Anfang des Ausführungsbefehls, um die meisten potenziellen Fehler im Bash-Skript zu unterdrücken. +2. Der letzte Befehl muss ein Erfolg sein: `echo "done"` oder einfach `true` reicht aus. + +Hier ist ein Beispiel: + +```yaml +- run: + name: run CI experiment + command: | + set +euo pipefail + echo "setting run-all-despite-any-errors-mode" + this_command_will_fail + echo "but bash continues to run" + # emulate another failure + false + # but the last command must be a success + echo "during experiment do not remove: reporting success to CI, even if there were failures" +``` + +Für einfache Befehle können Sie auch Folgendes tun: + +```bash +cmd_that_may_fail || true +``` + +Wenn Sie mit den Ergebnissen zufrieden sind, integrieren Sie den experimentellen Schritt oder Job natürlich in den Rest der normalen Jobs, +Entfernen Sie dabei `set +euo pipefail` oder andere Dinge, die Sie eventuell hinzugefügt haben, um sicherzustellen, dass der experimentelle Auftrag nicht +den normalen CI-Betrieb nicht beeinträchtigt. + +Dieser ganze Prozess wäre viel einfacher gewesen, wenn wir nur etwas wie `allow-failure` für den +experimentellen Schritt festlegen könnten und ihn scheitern lassen würden, ohne den Gesamtstatus der PRs zu beeinträchtigen. Aber wie bereits erwähnt, haben CircleCI und +Github Actions dies im Moment nicht unterstützen. + +Sie können in diesen CI-spezifischen Threads für diese Funktion stimmen und sehen, wo sie steht: + +- [Github Actions:](https://github.com/actions/toolkit/issues/399) +- [CircleCI:](https://ideas.circleci.com/ideas/CCI-I-344) diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/training.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/training.md new file mode 100644 index 0000000000000000000000000000000000000000..806a380b6cebc9e729581e70b5309ade5bf33159 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/training.md @@ -0,0 +1,433 @@ + + +# Optimierung eines vortrainierten Modells + +[[open-in-colab]] + +Die Verwendung eines vorab trainierten Modells hat erhebliche Vorteile. Es reduziert die Rechenkosten und den CO2-Fußabdruck und ermöglicht Ihnen die Verwendung von Modellen, die dem neuesten Stand der Technik entsprechen, ohne dass Sie ein Modell von Grund auf neu trainieren müssen. Transformers bietet Zugang zu Tausenden von vortrainierten Modellen für eine Vielzahl von Aufgaben. Wenn Sie ein vorab trainiertes Modell verwenden, trainieren Sie es auf einem für Ihre Aufgabe spezifischen Datensatz. Dies wird als Feinabstimmung bezeichnet und ist eine unglaublich leistungsfähige Trainingstechnik. In diesem Tutorial werden Sie ein vortrainiertes Modell mit einem Deep-Learning-Framework Ihrer Wahl feinabstimmen: + +* Feinabstimmung eines vorab trainierten Modells mit 🤗 Transformers [`Trainer`]. +* Feinabstimmung eines vorab trainierten Modells in TensorFlow mit Keras. +* Feinabstimmung eines vorab trainierten Modells in nativem PyTorch. + + + +## Vorbereitung eines Datensatzes + + + +Bevor Sie die Feinabstimmung eines vortrainierten Modells vornehmen können, müssen Sie einen Datensatz herunterladen und für das Training vorbereiten. Im vorangegangenen Leitfaden haben Sie gelernt, wie man Daten für das Training aufbereitet, und jetzt haben Sie die Gelegenheit, diese Fähigkeiten zu testen! + +Laden Sie zunächst den Datensatz [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full): + +```py +>>> from datasets import load_dataset + +>>> dataset = load_dataset("yelp_review_full") +>>> dataset["train"][100] +{'label': 0, + 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'} +``` + +Wie Sie nun wissen, benötigen Sie einen Tokenizer, um den Text zu verarbeiten und eine Auffüll- und Abschneidungsstrategie einzubauen, um mit variablen Sequenzlängen umzugehen. Um Ihren Datensatz in einem Schritt zu verarbeiten, verwenden Sie die 🤗 Methode Datasets [`map`](https://huggingface.co/docs/datasets/process#map), um eine Vorverarbeitungsfunktion auf den gesamten Datensatz anzuwenden: + +```py +>>> from transformers import AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + + +>>> def tokenize_function(examples): +... return tokenizer(examples["text"], padding="max_length", truncation=True) + + +>>> tokenized_datasets = dataset.map(tokenize_function, batched=True) +``` + +Wenn Sie möchten, können Sie eine kleinere Teilmenge des gesamten Datensatzes für die Feinabstimmung erstellen, um den Zeitaufwand zu verringern: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + + + +## Training + +An dieser Stelle sollten Sie dem Abschnitt folgen, der dem Rahmen entspricht, den Sie verwenden möchten. Sie können über die Links +in der rechten Seitenleiste können Sie zu dem gewünschten Abschnitt springen - und wenn Sie den gesamten Inhalt eines bestimmten Frameworks ausblenden möchten, +klicken Sie einfach auf die Schaltfläche oben rechts im Block des jeweiligen Frameworks! + + + + + +## Trainieren mit PyTorch Trainer + +🤗 Transformers bietet eine [`Trainer`]-Klasse, die für das Training von 🤗 Transformers-Modellen optimiert ist und es einfacher macht, mit dem Training zu beginnen, ohne manuell eine eigene Trainingsschleife zu schreiben. Die [`Trainer`]-API unterstützt eine breite Palette von Trainingsoptionen und Funktionen wie Logging, Gradientenakkumulation und gemischte Präzision. + +Beginnen Sie mit dem Laden Ihres Modells und geben Sie die Anzahl der erwarteten Labels an. Aus dem Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields) wissen Sie, dass es fünf Labels gibt: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + + + +Es wird eine Warnung angezeigt, dass einige der trainierten Parameter nicht verwendet werden und einige Parameter zufällig +initialisiert werden. Machen Sie sich keine Sorgen, das ist völlig normal! Der vorher trainierte Kopf des BERT-Modells wird verworfen und durch einen zufällig initialisierten Klassifikationskopf ersetzt. Sie werden diesen neuen Modellkopf in Ihrer Sequenzklassifizierungsaufgabe feinabstimmen, indem Sie das Wissen des vortrainierten Modells auf ihn übertragen. + + + +### Hyperparameter für das Training + +Als Nächstes erstellen Sie eine Klasse [`TrainingArguments`], die alle Hyperparameter enthält, die Sie einstellen können, sowie Flags zur Aktivierung verschiedener Trainingsoptionen. Für dieses Lernprogramm können Sie mit den Standard- [Hyperparametern](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) beginnen, aber Sie können mit diesen experimentieren, um Ihre optimalen Einstellungen zu finden. + +Geben Sie an, wo die Kontrollpunkte Ihres Trainings gespeichert werden sollen: + +```py +>>> from transformers import TrainingArguments + +>>> training_args = TrainingArguments(output_dir="test_trainer") +``` + +### Auswerten + +Der [`Trainer`] wertet die Leistung des Modells während des Trainings nicht automatisch aus. Sie müssen [`Trainer`] eine Funktion übergeben, um Metriken zu berechnen und zu berichten. Die [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) Bibliothek bietet eine einfache [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) Funktion, die Sie mit der [`evaluate.load`] Funktion laden können (siehe diese [quicktour](https://huggingface.co/docs/evaluate/a_quick_tour) für weitere Informationen): + +```py +>>> import numpy as np +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +``` + +Rufen Sie [`~evaluate.compute`] auf `metric` auf, um die Genauigkeit Ihrer Vorhersagen zu berechnen. Bevor Sie Ihre Vorhersagen an `compute` übergeben, müssen Sie die Vorhersagen in Logits umwandeln (denken Sie daran, dass alle 🤗 Transformers-Modelle Logits zurückgeben): + +```py +>>> def compute_metrics(eval_pred): +... logits, labels = eval_pred +... predictions = np.argmax(logits, axis=-1) +... return metric.compute(predictions=predictions, references=labels) +``` + +Wenn Sie Ihre Bewertungsmetriken während der Feinabstimmung überwachen möchten, geben Sie den Parameter `eval_strategy` in Ihren Trainingsargumenten an, um die Bewertungsmetrik am Ende jeder Epoche zu ermitteln: + +```py +>>> from transformers import TrainingArguments, Trainer + +>>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch") +``` + +### Trainer + +Erstellen Sie ein [`Trainer`]-Objekt mit Ihrem Modell, Trainingsargumenten, Trainings- und Testdatensätzen und einer Evaluierungsfunktion: + +```py +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=small_train_dataset, +... eval_dataset=small_eval_dataset, +... compute_metrics=compute_metrics, +... ) +``` + +Anschließend können Sie Ihr Modell durch den Aufruf von [`~transformers.Trainer.train`] optimieren: + +```py +>>> trainer.train() +``` + + + + + + +## Trainieren Sie ein TensorFlow-Modell mit Keras + +Sie können auch 🤗 Transformers Modelle in TensorFlow mit der Keras API trainieren! + +### Laden von Daten für Keras + +Wenn Sie ein 🤗 Transformers Modell mit der Keras API trainieren wollen, müssen Sie Ihren Datensatz in ein Format konvertieren, das +Keras versteht. Wenn Ihr Datensatz klein ist, können Sie das Ganze einfach in NumPy-Arrays konvertieren und an Keras übergeben. +Probieren wir das zuerst aus, bevor wir etwas Komplizierteres tun. + +Laden Sie zunächst ein Dataset. Wir werden den CoLA-Datensatz aus dem [GLUE-Benchmark](https://huggingface.co/datasets/glue) verwenden, +da es sich um eine einfache Aufgabe zur Klassifizierung von binärem Text handelt, und nehmen vorerst nur den Trainingssplit. + +```py +from datasets import load_dataset + +dataset = load_dataset("glue", "cola") +dataset = dataset["train"] # Just take the training split for now +``` + +Als nächstes laden Sie einen Tokenizer und tokenisieren die Daten als NumPy-Arrays. Beachten Sie, dass die Beschriftungen bereits eine Liste von 0 und 1en sind, +Wir können sie also ohne Tokenisierung direkt in ein NumPy-Array konvertieren! + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") +tokenized_data = tokenizer(dataset["text"], return_tensors="np", padding=True) +# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras +tokenized_data = dict(tokenized_data) + +labels = np.array(dataset["label"]) # Label is already an array of 0 and 1 +``` + +Schließlich laden, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) und [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) Sie das Modell: + +```py +from transformers import TFAutoModelForSequenceClassification +from tensorflow.keras.optimizers import Adam + +# Load and compile our model +model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased") +# Lower learning rates are often better for fine-tuning transformers +model.compile(optimizer=Adam(3e-5)) + +model.fit(tokenized_data, labels) +``` + + + +Sie müssen Ihren Modellen kein Verlustargument übergeben, wenn Sie sie `compile()`! Hugging-Face-Modelle wählen automatisch +einen Loss, der für ihre Aufgabe und Modellarchitektur geeignet ist, wenn dieses Argument leer gelassen wird. Sie können jederzeit außer Kraft setzen, indem Sie selbst einen Loss angeben, wenn Sie das möchten! + + + +Dieser Ansatz eignet sich hervorragend für kleinere Datensätze, aber bei größeren Datensätzen kann er zu einem Problem werden. Warum? +Weil das tokenisierte Array und die Beschriftungen vollständig in den Speicher geladen werden müssten, und weil NumPy nicht mit +"gezackte" Arrays nicht verarbeiten kann, so dass jedes tokenisierte Sample auf die Länge des längsten Samples im gesamten Datensatz aufgefüllt werden müsste. +Datensatzes aufgefüllt werden. Dadurch wird das Array noch größer, und all die aufgefüllten Token verlangsamen auch das Training! + +### Laden von Daten als tf.data.Dataset + +Wenn Sie eine Verlangsamung des Trainings vermeiden wollen, können Sie Ihre Daten stattdessen als `tf.data.Dataset` laden. Sie können zwar Ihre eigene +tf.data"-Pipeline schreiben können, wenn Sie wollen, haben wir zwei bequeme Methoden, um dies zu tun: + +- [`~TFPreTrainedModel.prepare_tf_dataset`]: Dies ist die Methode, die wir in den meisten Fällen empfehlen. Da es sich um eine Methode +Ihres Modells ist, kann sie das Modell inspizieren, um automatisch herauszufinden, welche Spalten als Modelleingaben verwendet werden können, und +verwirft die anderen, um einen einfacheren, leistungsfähigeren Datensatz zu erstellen. +- [`~datasets.Dataset.to_tf_dataset`]: Diese Methode ist eher auf niedriger Ebene angesiedelt und ist nützlich, wenn Sie genau kontrollieren wollen, wie +Dataset erstellt wird, indem man genau angibt, welche `columns` und `label_cols` einbezogen werden sollen. + +Bevor Sie [`~TFPreTrainedModel.prepare_tf_dataset`] verwenden können, müssen Sie die Tokenizer-Ausgaben als Spalten zu Ihrem Datensatz hinzufügen, wie in +dem folgenden Codebeispiel: + +```py +def tokenize_dataset(data): + # Keys of the returned dictionary will be added to the dataset as columns + return tokenizer(data["text"]) + + +dataset = dataset.map(tokenize_dataset) +``` + +Denken Sie daran, dass Hugging Face-Datensätze standardmäßig auf der Festplatte gespeichert werden, so dass dies nicht zu einem erhöhten Arbeitsspeicherbedarf führen wird! Sobald die +Spalten hinzugefügt wurden, können Sie Batches aus dem Datensatz streamen und zu jedem Batch Auffüllungen hinzufügen, was die Anzahl der Auffüllungs-Token im Vergleich zum Auffüllen des gesamten Datensatzes reduziert. + + +```py +>>> tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer) +``` + +Beachten Sie, dass Sie im obigen Codebeispiel den Tokenizer an `prepare_tf_dataset` übergeben müssen, damit die Stapel beim Laden korrekt aufgefüllt werden können. +Wenn alle Stichproben in Ihrem Datensatz die gleiche Länge haben und kein Auffüllen erforderlich ist, können Sie dieses Argument weglassen. +Wenn Sie etwas Komplexeres als nur das Auffüllen von Stichproben benötigen (z. B. das Korrumpieren von Token für die maskierte Sprachmodellierung), können Sie das Argument +Modellierung), können Sie stattdessen das Argument `collate_fn` verwenden, um eine Funktion zu übergeben, die aufgerufen wird, um die +Liste von Stichproben in einen Stapel umwandelt und alle gewünschten Vorverarbeitungen vornimmt. Siehe unsere +[examples](https://github.com/huggingface/transformers/tree/main/examples) oder +[notebooks](https://huggingface.co/docs/transformers/notebooks), um diesen Ansatz in Aktion zu sehen. + +Sobald Sie einen `tf.data.Dataset` erstellt haben, können Sie das Modell wie zuvor kompilieren und anpassen: + +```py +model.compile(optimizer=Adam(3e-5)) + +model.fit(tf_dataset) +``` + + + + + + +## Trainieren in nativem PyTorch + + + + + +[`Trainer`] kümmert sich um die Trainingsschleife und ermöglicht die Feinabstimmung eines Modells in einer einzigen Codezeile. Für Benutzer, die es vorziehen, ihre eigene Trainingsschleife zu schreiben, können Sie auch eine Feinabstimmung eines 🤗 Transformers-Modells in nativem PyTorch vornehmen. + +An diesem Punkt müssen Sie möglicherweise Ihr Notebook neu starten oder den folgenden Code ausführen, um etwas Speicher freizugeben: + +```py +del model +del pytorch_model +del trainer +torch.cuda.empty_cache() +``` + +Als Nächstes müssen Sie den Datensatz `tokenized_dataset` manuell nachbearbeiten, um ihn für das Training vorzubereiten. + +1. Entfernen Sie die Spalte "Text", da das Modell keinen Rohtext als Eingabe akzeptiert: + + ```py + >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"]) + ``` + +2. Benennen Sie die Spalte "Label" in "Labels" um, da das Modell erwartet, dass das Argument "Labels" genannt wird: + + ```py + >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + ``` + +3. Stellen Sie das Format des Datensatzes so ein, dass PyTorch-Tensoren anstelle von Listen zurückgegeben werden: + + ```py + >>> tokenized_datasets.set_format("torch") + ``` + +Erstellen Sie dann eine kleinere Teilmenge des Datensatzes, wie zuvor gezeigt, um die Feinabstimmung zu beschleunigen: + +```py +>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) +>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) +``` + +### DataLoader + +Erstellen Sie einen `DataLoader` für Ihre Trainings- und Testdatensätze, damit Sie über die Datenstapel iterieren können: + +```py +>>> from torch.utils.data import DataLoader + +>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8) +>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8) +``` + +Laden Sie Ihr Modell mit der Anzahl der erwarteten Kennzeichnungen: + +```py +>>> from transformers import AutoModelForSequenceClassification + +>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) +``` + +### Optimierer und Lernratensteuerung + +Erstellen Sie einen Optimierer und einen Scheduler für die Lernrate, um das Modell fein abzustimmen. Wir verwenden den Optimierer [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) aus PyTorch: + +```py +>>> from torch.optim import AdamW + +>>> optimizer = AdamW(model.parameters(), lr=5e-5) +``` + +Erstellen Sie den Standard-Lernratenplaner aus [`Trainer`]: + +```py +>>> from transformers import get_scheduler + +>>> num_epochs = 3 +>>> num_training_steps = num_epochs * len(train_dataloader) +>>> lr_scheduler = get_scheduler( +... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps +... ) +``` + +Geben Sie schließlich `device` an, um einen Grafikprozessor zu verwenden, wenn Sie Zugang zu einem solchen haben. Andernfalls kann das Training auf einer CPU mehrere Stunden statt ein paar Minuten dauern. + +```py +>>> import torch + +>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") +>>> model.to(device) +``` + + + +Holen Sie sich mit einem gehosteten Notebook wie [Colaboratory](https://colab.research.google.com/) oder [SageMaker StudioLab](https://studiolab.sagemaker.aws/) kostenlosen Zugang zu einem Cloud-GPU, wenn Sie noch keinen haben. + + + +Großartig, Sie sind bereit für das Training! 🥳 + +### Trainingsschleife + +Um Ihren Trainingsfortschritt zu verfolgen, verwenden Sie die [tqdm](https://tqdm.github.io/) Bibliothek, um einen Fortschrittsbalken über die Anzahl der Trainingsschritte hinzuzufügen: + +```py +>>> from tqdm.auto import tqdm + +>>> progress_bar = tqdm(range(num_training_steps)) + +>>> model.train() +>>> for epoch in range(num_epochs): +... for batch in train_dataloader: +... batch = {k: v.to(device) for k, v in batch.items()} +... outputs = model(**batch) +... loss = outputs.loss +... loss.backward() + +... optimizer.step() +... lr_scheduler.step() +... optimizer.zero_grad() +... progress_bar.update(1) +``` + +### Auswertung + +Genauso wie Sie eine Bewertungsfunktion zu [`Trainer`] hinzugefügt haben, müssen Sie dasselbe tun, wenn Sie Ihre eigene Trainingsschleife schreiben. Aber anstatt die Metrik am Ende jeder Epoche zu berechnen und zu melden, werden Sie dieses Mal alle Stapel mit [`~evaluate.add_batch`] akkumulieren und die Metrik ganz am Ende berechnen. + +```py +>>> import evaluate + +>>> metric = evaluate.load("accuracy") +>>> model.eval() +>>> for batch in eval_dataloader: +... batch = {k: v.to(device) for k, v in batch.items()} +... with torch.no_grad(): +... outputs = model(**batch) + +... logits = outputs.logits +... predictions = torch.argmax(logits, dim=-1) +... metric.add_batch(predictions=predictions, references=batch["labels"]) + +>>> metric.compute() +``` + + + + + +## Zusätzliche Ressourcen + +Weitere Beispiele für die Feinabstimmung finden Sie unter: + +- [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) enthält Skripte + um gängige NLP-Aufgaben in PyTorch und TensorFlow zu trainieren. + +- [🤗 Transformers Notebooks](notebooks) enthält verschiedene Notebooks zur Feinabstimmung eines Modells für bestimmte Aufgaben in PyTorch und TensorFlow. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/transformers_agents.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/transformers_agents.md new file mode 100644 index 0000000000000000000000000000000000000000..1d676c395e176964df1ea77a889749c7c96e7017 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/de/transformers_agents.md @@ -0,0 +1,323 @@ + + +# Transformers Agents + + + +Transformers Agents ist eine experimentelle API, die jederzeit geändert werden kann. Die von den Agenten zurückgegebenen Ergebnisse +zurückgegeben werden, können variieren, da sich die APIs oder die zugrunde liegenden Modelle ändern können. + + + +Transformers Version v4.29.0, die auf dem Konzept von *Tools* und *Agenten* aufbaut. Sie können damit spielen in +[dieses Colab](https://colab.research.google.com/drive/1c7MHD-T1forUPGcC_jlwsIptOzpG3hSj). + +Kurz gesagt, es bietet eine API für natürliche Sprache auf der Grundlage von Transformers: Wir definieren eine Reihe von kuratierten Tools und entwerfen einen +Agenten, um natürliche Sprache zu interpretieren und diese Werkzeuge zu verwenden. Es ist von vornherein erweiterbar; wir haben einige relevante Tools kuratiert, +aber wir werden Ihnen zeigen, wie das System einfach erweitert werden kann, um jedes von der Community entwickelte Tool zu verwenden. + +Beginnen wir mit einigen Beispielen dafür, was mit dieser neuen API erreicht werden kann. Sie ist besonders leistungsfähig, wenn es um +Sie ist besonders leistungsstark, wenn es um multimodale Aufgaben geht. Lassen Sie uns also eine Runde drehen, um Bilder zu erzeugen und Text vorzulesen. + +```py +agent.run("Caption the following image", image=image) +``` + +| **Input** | **Output** | +|-----------------------------------------------------------------------------------------------------------------------------|-----------------------------------| +| | A beaver is swimming in the water | + +--- + +```py +agent.run("Read the following text out loud", text=text) +``` +| **Input** | **Output** | +|-------------------------------------------------------------------------------------------------------------------------|----------------------------------------------| +| A beaver is swimming in the water | + +--- + +```py +agent.run( + "In the following `document`, where will the TRRF Scientific Advisory Council Meeting take place?", + document=document, +) +``` +| **Input** | **Output** | +|-----------------------------------------------------------------------------------------------------------------------------|----------------| +| | ballroom foyer | + +## Schnellstart + +Bevor Sie `agent.run` verwenden können, müssen Sie einen Agenten instanziieren, der ein großes Sprachmodell (LLM) ist. +Wir bieten Unterstützung für openAI-Modelle sowie für OpenSource-Alternativen von BigCode und OpenAssistant. Die openAI +Modelle sind leistungsfähiger (erfordern aber einen openAI-API-Schlüssel, können also nicht kostenlos verwendet werden); Hugging Face +bietet kostenlosen Zugang zu Endpunkten für BigCode- und OpenAssistant-Modelle. + +To start with, please install the `agents` extras in order to install all default dependencies. +```bash +pip install transformers[agents] +``` + +Um openAI-Modelle zu verwenden, instanziieren Sie einen [`OpenAiAgent`], nachdem Sie die `openai`-Abhängigkeit installiert haben: + +```bash +pip install openai +``` + + +```py +from transformers import OpenAiAgent + +agent = OpenAiAgent(model="text-davinci-003", api_key="") +``` + +Um BigCode oder OpenAssistant zu verwenden, melden Sie sich zunächst an, um Zugriff auf die Inference API zu erhalten: + +```py +from huggingface_hub import login + +login("") +``` + +Dann instanziieren Sie den Agenten + +```py +from transformers import HfAgent + +# Starcoder +agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder") +# StarcoderBase +# agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoderbase") +# OpenAssistant +# agent = HfAgent(url_endpoint="https://api-inference.huggingface.co/models/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5") +``` + +Dies geschieht mit der Inferenz-API, die Hugging Face derzeit kostenlos zur Verfügung stellt. Wenn Sie Ihren eigenen Inferenz +Endpunkt für dieses Modell (oder einen anderen) haben, können Sie die obige URL durch Ihren URL-Endpunkt ersetzen. + + + +StarCoder und OpenAssistant sind kostenlos und leisten bei einfachen Aufgaben bewundernswert gute Arbeit. Allerdings halten die Kontrollpunkte +nicht, wenn es um komplexere Aufforderungen geht. Wenn Sie mit einem solchen Problem konfrontiert sind, empfehlen wir Ihnen, das OpenAI +Modell auszuprobieren, das zwar leider nicht quelloffen ist, aber zur Zeit eine bessere Leistung erbringt. + + + +Sie sind jetzt startklar! Lassen Sie uns in die beiden APIs eintauchen, die Ihnen jetzt zur Verfügung stehen. + +### Einzelne Ausführung (run) + +Die Methode der einmaligen Ausführung ist die Verwendung der [`~Agent.run`] Methode des Agenten: + +```py +agent.run("Draw me a picture of rivers and lakes.") +``` + + + +Es wählt automatisch das (oder die) Werkzeug(e) aus, das (die) für die von Ihnen gewünschte Aufgabe geeignet ist (sind) und führt es (sie) entsprechend aus. Es +kann eine oder mehrere Aufgaben in der gleichen Anweisung ausführen (je komplexer Ihre Anweisung ist, desto wahrscheinlicher ist ein +der Agent scheitern). + +```py +agent.run("Draw me a picture of the sea then transform the picture to add an island") +``` + + + +
+ + +Jede [`~Agent.run`] Operation ist unabhängig, so dass Sie sie mehrmals hintereinander mit unterschiedlichen Aufgaben ausführen können. + +Beachten Sie, dass Ihr `Agent` nur ein großsprachiges Modell ist, so dass kleine Variationen in Ihrer Eingabeaufforderung völlig unterschiedliche Ergebnisse liefern können. +unterschiedliche Ergebnisse liefern. Es ist wichtig, dass Sie die Aufgabe, die Sie ausführen möchten, so genau wie möglich erklären. Wir gehen noch weiter ins Detail +wie man gute Prompts schreibt [hier](custom_tools#writing-good-user-inputs). + +Wenn Sie einen Status über Ausführungszeiten hinweg beibehalten oder dem Agenten Nicht-Text-Objekte übergeben möchten, können Sie dies tun, indem Sie +Variablen, die der Agent verwenden soll. Sie könnten zum Beispiel das erste Bild von Flüssen und Seen erzeugen, +und das Modell bitten, dieses Bild zu aktualisieren und eine Insel hinzuzufügen, indem Sie Folgendes tun: + +```python +picture = agent.run("Generate a picture of rivers and lakes.") +updated_picture = agent.run("Transform the image in `picture` to add an island to it.", picture=picture) +``` + + + +Dies kann hilfreich sein, wenn das Modell Ihre Anfrage nicht verstehen kann und die Werkzeuge verwechselt. Ein Beispiel wäre: + +```py +agent.run("Draw me the picture of a capybara swimming in the sea") +``` + +Hier könnte das Modell auf zwei Arten interpretieren: +- Die Funktion `Text-zu-Bild` erzeugt ein Wasserschwein, das im Meer schwimmt. +- Oder Sie lassen das `Text-zu-Bild` ein Wasserschwein erzeugen und verwenden dann das Werkzeug `Bildtransformation`, um es im Meer schwimmen zu lassen. + +Falls Sie das erste Szenario erzwingen möchten, können Sie dies tun, indem Sie die Eingabeaufforderung als Argument übergeben: + +```py +agent.run("Draw me a picture of the `prompt`", prompt="a capybara swimming in the sea") +``` + + + + +### Chat-basierte Ausführung (Chat) + +Der Agent verfügt auch über einen Chat-basierten Ansatz, der die Methode [`~Agent.chat`] verwendet: + +```py +agent.chat("Generate a picture of rivers and lakes") +``` + + + +```py +agent.chat("Transform the picture so that there is a rock in there") +``` + + + +
+ +Dies ist ein interessanter Ansatz, wenn Sie den Zustand über Anweisungen hinweg beibehalten möchten. Er ist besser für Experimente geeignet, +eignet sich aber eher für einzelne Anweisungen als für komplexe Anweisungen (die die [`~Agent.run`] +Methode besser verarbeiten kann). + +Diese Methode kann auch Argumente entgegennehmen, wenn Sie Nicht-Text-Typen oder bestimmte Aufforderungen übergeben möchten. + +### ⚠️ Fernausführung + +Zu Demonstrationszwecken und damit es mit allen Setups verwendet werden kann, haben wir Remote-Executors für mehrere +der Standard-Tools erstellt, auf die der Agent in dieser Version Zugriff hat. Diese werden erstellt mit +[inference endpoints](https://huggingface.co/inference-endpoints). + +Wir haben diese vorerst deaktiviert, aber um zu sehen, wie Sie selbst Remote Executors Tools einrichten können, +empfehlen wir die Lektüre des [custom tool guide](./custom_tools). + +### Was passiert hier? Was sind Tools und was sind Agenten? + + + +#### Agenten + +Der "Agent" ist hier ein großes Sprachmodell, das wir auffordern, Zugang zu einem bestimmten Satz von Tools zu erhalten. + +LLMs sind ziemlich gut darin, kleine Codeproben zu erzeugen. Diese API macht sich das zunutze, indem sie das +LLM ein kleines Codebeispiel gibt, das eine Aufgabe mit einer Reihe von Werkzeugen ausführt. Diese Aufforderung wird dann ergänzt durch die +Aufgabe, die Sie Ihrem Agenten geben, und die Beschreibung der Werkzeuge, die Sie ihm geben. Auf diese Weise erhält er Zugriff auf die Dokumentation der +Tools, insbesondere die erwarteten Eingaben und Ausgaben, und kann den entsprechenden Code generieren. + +#### Tools + +Tools sind sehr einfach: Sie bestehen aus einer einzigen Funktion mit einem Namen und einer Beschreibung. Wir verwenden dann die Beschreibungen dieser Tools +um den Agenten aufzufordern. Anhand der Eingabeaufforderung zeigen wir dem Agenten, wie er die Tools nutzen kann, um das zu tun, was in der +in der Abfrage angefordert wurde. + +Dies geschieht mit brandneuen Tools und nicht mit Pipelines, denn der Agent schreibt besseren Code mit sehr atomaren Tools. +Pipelines sind stärker refaktorisiert und fassen oft mehrere Aufgaben in einer einzigen zusammen. Tools sind dafür gedacht, sich auf +eine einzige, sehr einfache Aufgabe konzentrieren. + +#### Code-Ausführung?! + +Dieser Code wird dann mit unserem kleinen Python-Interpreter auf den mit Ihren Tools übergebenen Eingaben ausgeführt. +Wir hören Sie schon schreien "Willkürliche Codeausführung!", aber lassen Sie uns erklären, warum das nicht der Fall ist. + +Die einzigen Funktionen, die aufgerufen werden können, sind die von Ihnen zur Verfügung gestellten Tools und die Druckfunktion, so dass Sie bereits eingeschränkt sind +eingeschränkt, was ausgeführt werden kann. Sie sollten sicher sein, wenn es sich auf die Werkzeuge für das Umarmungsgesicht beschränkt. + +Dann lassen wir keine Attributsuche oder Importe zu (die ohnehin nicht benötigt werden, um die +Inputs/Outputs an eine kleine Gruppe von Funktionen), so dass alle offensichtlichen Angriffe (und Sie müssten den LLM +dazu auffordern, sie auszugeben) kein Problem darstellen sollten. Wenn Sie auf Nummer sicher gehen wollen, können Sie die +run()-Methode mit dem zusätzlichen Argument return_code=True ausführen. In diesem Fall gibt der Agent nur den auszuführenden Code +zur Ausführung zurück und Sie können entscheiden, ob Sie ihn ausführen möchten oder nicht. + +Die Ausführung bricht bei jeder Zeile ab, in der versucht wird, eine illegale Operation auszuführen, oder wenn ein regulärer Python-Fehler +mit dem vom Agenten generierten Code. + +### Ein kuratierter Satz von Tools + +Wir haben eine Reihe von Tools identifiziert, die solche Agenten unterstützen können. Hier ist eine aktualisierte Liste der Tools, die wir integriert haben +in `transformers` integriert haben: + +- **Beantwortung von Fragen zu Dokumenten**: Beantworten Sie anhand eines Dokuments (z.B. PDF) im Bildformat eine Frage zu diesem Dokument ([Donut](./model_doc/donut)) +- Beantworten von Textfragen**: Geben Sie einen langen Text und eine Frage an, beantworten Sie die Frage im Text ([Flan-T5](./model_doc/flan-t5)) +- **Unbedingte Bildunterschriften**: Beschriften Sie das Bild! ([BLIP](./model_doc/blip)) +- **Bildfragebeantwortung**: Beantworten Sie bei einem Bild eine Frage zu diesem Bild ([VILT](./model_doc/vilt)) +- **Bildsegmentierung**: Geben Sie ein Bild und einen Prompt an und geben Sie die Segmentierungsmaske dieses Prompts aus ([CLIPSeg](./model_doc/clipseg)) +- **Sprache in Text**: Geben Sie eine Audioaufnahme einer sprechenden Person an und transkribieren Sie die Sprache in Text ([Whisper](./model_doc/whisper)) +- **Text in Sprache**: wandelt Text in Sprache um ([SpeechT5](./model_doc/speecht5)) +- **Zero-Shot-Textklassifizierung**: Ermitteln Sie anhand eines Textes und einer Liste von Bezeichnungen, welcher Bezeichnung der Text am ehesten entspricht ([BART](./model_doc/bart)) +- **Textzusammenfassung**: fassen Sie einen langen Text in einem oder wenigen Sätzen zusammen ([BART](./model_doc/bart)) +- **Übersetzung**: Übersetzen des Textes in eine bestimmte Sprache ([NLLB](./model_doc/nllb)) + +Diese Tools sind in Transformatoren integriert und können auch manuell verwendet werden, zum Beispiel: + +```py +from transformers import load_tool + +tool = load_tool("text-to-speech") +audio = tool("This is a text to speech tool") +``` + +### Benutzerdefinierte Tools + +Wir haben zwar eine Reihe von Tools identifiziert, sind aber der festen Überzeugung, dass der Hauptwert dieser Implementierung darin besteht +die Möglichkeit, benutzerdefinierte Tools schnell zu erstellen und weiterzugeben. + +Indem Sie den Code eines Tools in einen Hugging Face Space oder ein Modell-Repository stellen, können Sie das Tool +direkt mit dem Agenten nutzen. Wir haben ein paar neue Funktionen hinzugefügt +**transformers-agnostic** Tools zur [`huggingface-tools` Organisation](https://huggingface.co/huggingface-tools) hinzugefügt: + +- **Text-Downloader**: zum Herunterladen eines Textes von einer Web-URL +- **Text zu Bild**: erzeugt ein Bild nach einer Eingabeaufforderung und nutzt dabei stabile Diffusion +- **Bildtransformation**: verändert ein Bild anhand eines Ausgangsbildes und einer Eingabeaufforderung, unter Ausnutzung der stabilen pix2pix-Diffusion +- **Text zu Video**: Erzeugen eines kleinen Videos nach einer Eingabeaufforderung, unter Verwendung von damo-vilab + +Das Text-zu-Bild-Tool, das wir von Anfang an verwendet haben, ist ein Remote-Tool, das sich in +[*huggingface-tools/text-to-image*](https://huggingface.co/spaces/huggingface-tools/text-to-image)! Wir werden +weiterhin solche Tools für diese und andere Organisationen veröffentlichen, um diese Implementierung weiter zu verbessern. + +Die Agenten haben standardmäßig Zugriff auf die Tools, die sich auf [*huggingface-tools*](https://huggingface.co/huggingface-tools) befinden. +Wie Sie Ihre eigenen Tools schreiben und freigeben können und wie Sie jedes benutzerdefinierte Tool, das sich auf dem Hub befindet, nutzen können, erklären wir in [folgender Anleitung](custom_tools). + +### Code-Erzeugung + +Bisher haben wir gezeigt, wie Sie die Agenten nutzen können, um Aktionen für Sie durchzuführen. Der Agent generiert jedoch nur Code +den wir dann mit einem sehr eingeschränkten Python-Interpreter ausführen. Falls Sie den generierten Code in einer anderen Umgebung verwenden möchten +einer anderen Umgebung verwenden möchten, können Sie den Agenten auffordern, den Code zusammen mit einer Tooldefinition und genauen Importen zurückzugeben. + +Zum Beispiel die folgende Anweisung +```python +agent.run("Draw me a picture of rivers and lakes", return_code=True) +``` + +gibt den folgenden Code zurück + +```python +from transformers import load_tool + +image_generator = load_tool("huggingface-tools/text-to-image") + +image = image_generator(prompt="rivers and lakes") +``` + +die Sie dann selbst ändern und ausführen können. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_config.py b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f49e4e4731965a504b8da443c2cd979638cd22bb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_config.py @@ -0,0 +1,14 @@ +# docstyle-ignore +INSTALL_CONTENT = """ +# Transformers installation +! pip install transformers datasets evaluate accelerate +# To install from source instead of the last release, comment the command above and uncomment the following one. +# ! pip install git+https://github.com/huggingface/transformers.git +""" + +notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] +black_avoid_patterns = { + "{processor_class}": "FakeProcessorClass", + "{model_class}": "FakeModelClass", + "{object_class}": "FakeObjectClass", +} diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_redirects.yml b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_redirects.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff70547c7228419daa3e1b048c7256ec8a5deae1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_redirects.yml @@ -0,0 +1,5 @@ +# Optimizing inference + +perf_infer_gpu_many: perf_infer_gpu_one +transformers_agents: agents +quantization: quantization/overview diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_toctree.yml b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..79f8eb3d490d71b0ad8df0dfed9abb769dc984c4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/_toctree.yml @@ -0,0 +1,1060 @@ +- sections: + - local: index + title: Transformers + - local: installation + title: Installation + - local: quicktour + title: Quickstart + title: Get started +- isExpanded: false + sections: + - sections: + - local: models + title: Loading models + - local: custom_models + title: Customizing models + - local: how_to_hack_models + title: Customizing model components + - local: model_sharing + title: Sharing + - local: add_new_model + title: Adding a new model to Transformers + - local: modular_transformers + title: Modular Transformers + - local: task_summary + title: What 🤗 Transformers can do + - local: tasks_explained + title: How 🤗 Transformers solve tasks + - local: model_summary + title: The Transformer model family + - local: attention + title: Attention mechanisms + title: Models + - sections: + - local: fast_tokenizers + title: Tokenizers + - local: image_processors + title: Image processors + - local: backbones + title: Backbones + - local: feature_extractors + title: Feature extractors + - local: processors + title: Processors + - local: tokenizer_summary + title: Summary of the tokenizers + - local: pad_truncation + title: Padding and truncation + title: Preprocessors + title: Base classes +- isExpanded: false + sections: + - sections: + - local: pipeline_tutorial + title: Pipeline + - local: pipeline_gradio + title: Machine learning apps + - local: pipeline_webserver + title: Web server inference + - local: add_new_pipeline + title: Adding a new pipeline + title: Pipeline API + - sections: + - local: llm_tutorial + title: Text generation + - local: generation_strategies + title: Generation strategies + - local: generation_features + title: Generation features + - local: tasks/prompting + title: Prompt engineering + - local: llm_optims + title: Optimizing inference + - local: kv_cache + title: KV cache strategies + - local: serving + title: Serving + - local: cache_explanation + title: Caching + - local: llm_tutorial_optimization + title: Getting the most out of LLMs + - local: perplexity + title: Perplexity of fixed-length models + title: LLMs + - sections: + - local: conversations + title: Chat basics + - local: chat_templating + title: Templates + - local: chat_templating_multimodal + title: Multimodal templates + - local: chat_templating_writing + title: Template writing + - local: chat_extras + title: Tools and RAG + title: Chat with models + - sections: + - local: perf_torch_compile + title: torch.compile + - local: perf_infer_gpu_one + title: GPU + - local: perf_infer_gpu_multi + title: Distributed GPU inference + - local: perf_infer_cpu + title: CPU + - local: tf_xla + title: XLA + title: Optimization + - local: agents + title: Agents + - local: tools + title: Tools + title: Inference +- isExpanded: false + sections: + - sections: + - local: trainer + title: Trainer + - local: training + title: Fine-tuning + - local: optimizers + title: Optimizers + - local: hpo_train + title: Hyperparameter search + title: Trainer API + - sections: + - local: gpu_selection + title: GPU selection + - local: accelerate + title: Accelerate + - local: fsdp + title: FullyShardedDataParallel + - local: deepspeed + title: DeepSpeed + - local: debugging + title: Multi-GPU debugging + - local: perf_train_cpu_many + title: Distributed CPUs + - local: perf_train_gpu_many + title: Parallelism methods + title: Distributed training + - sections: + - local: perf_train_gpu_one + title: GPU + - local: perf_train_cpu + title: CPU + - local: perf_train_tpu_tf + title: TPU + - local: perf_train_special + title: Apple Silicon + - local: perf_hardware + title: Build your own machine + title: Hardware + - local: peft + title: PEFT + - local: model_memory_anatomy + title: Model training anatomy + title: Training +- isExpanded: false + sections: + - local: quantization/overview + title: Overview + - local: quantization/aqlm + title: AQLM + - local: quantization/awq + title: AWQ + - local: quantization/bitnet + title: BitNet + - local: quantization/bitsandbytes + title: bitsandbytes + - local: quantization/compressed_tensors + title: compressed-tensors + - local: quantization/eetq + title: EETQ + - local: quantization/fbgemm_fp8 + title: FBGEMM + - local: quantization/finegrained_fp8 + title: Fine-grained FP8 + - local: gguf + title: GGUF + - local: quantization/gptq + title: GPTQ + - local: quantization/higgs + title: HIGGS + - local: quantization/hqq + title: HQQ + - local: quantization/optimum + title: Optimum + - local: quantization/quanto + title: Quanto + - local: quantization/torchao + title: torchao + - local: quantization/spqr + title: SpQR + - local: quantization/vptq + title: VPTQ + - local: quantization/contribute + title: Contribute + title: Quantization +- isExpanded: false + sections: + - local: serialization + title: ONNX + - local: tflite + title: LiteRT + - local: executorch + title: ExecuTorch + - local: torchscript + title: TorchScript + title: Export to production +- isExpanded: false + sections: + - sections: + - sections: + - local: tasks/sequence_classification + title: Text classification + - local: tasks/token_classification + title: Token classification + - local: tasks/question_answering + title: Question answering + - local: tasks/language_modeling + title: Causal language modeling + - local: tasks/masked_language_modeling + title: Masked language modeling + - local: tasks/translation + title: Translation + - local: tasks/summarization + title: Summarization + - local: tasks/multiple_choice + title: Multiple choice + title: Natural language processing + - sections: + - local: tasks/audio_classification + title: Audio classification + - local: tasks/asr + title: Automatic speech recognition + title: Audio + - sections: + - local: tasks/image_classification + title: Image classification + - local: tasks/semantic_segmentation + title: Image segmentation + - local: tasks/video_classification + title: Video classification + - local: tasks/object_detection + title: Object detection + - local: tasks/zero_shot_object_detection + title: Zero-shot object detection + - local: tasks/zero_shot_image_classification + title: Zero-shot image classification + - local: tasks/monocular_depth_estimation + title: Depth estimation + - local: tasks/image_to_image + title: Image-to-Image + - local: tasks/image_feature_extraction + title: Image Feature Extraction + - local: tasks/mask_generation + title: Mask Generation + - local: tasks/keypoint_detection + title: Keypoint detection + - local: tasks/knowledge_distillation_for_image_classification + title: Knowledge Distillation for Computer Vision + title: Computer vision + - sections: + - local: tasks/image_captioning + title: Image captioning + - local: tasks/document_question_answering + title: Document Question Answering + - local: tasks/visual_question_answering + title: Visual Question Answering + - local: tasks/text-to-speech + title: Text to speech + - local: tasks/idefics + title: Image tasks with IDEFICS + - local: tasks/image_text_to_text + title: Image-text-to-text + - local: tasks/video_text_to_text + title: Video-text-to-text + title: Multimodal + title: Task recipes + - local: run_scripts + title: Training scripts + - local: glossary + title: Glossary + - local: philosophy + title: Philosophy + - local: notebooks + title: Notebooks with examples + - local: community + title: Community resources + - local: troubleshooting + title: Troubleshoot + title: Resources +- isExpanded: false + sections: + - local: contributing + title: Contribute to Transformers + - local: testing + title: Transformers model tests + - local: pr_checks + title: Pull request checks + title: Contribute +- isExpanded: false + sections: + - sections: + - local: main_classes/agent + title: Agents and Tools + - local: model_doc/auto + title: Auto Classes + - local: main_classes/backbones + title: Backbones + - local: main_classes/callback + title: Callbacks + - local: main_classes/configuration + title: Configuration + - local: main_classes/data_collator + title: Data Collator + - local: main_classes/keras_callbacks + title: Keras callbacks + - local: main_classes/logging + title: Logging + - local: main_classes/model + title: Models + - local: main_classes/text_generation + title: Text Generation + - local: main_classes/onnx + title: ONNX + - local: main_classes/optimizer_schedules + title: Optimization + - local: main_classes/output + title: Model outputs + - local: main_classes/peft + title: PEFT + - local: main_classes/pipelines + title: Pipelines + - local: main_classes/processors + title: Processors + - local: main_classes/quantization + title: Quantization + - local: main_classes/tokenizer + title: Tokenizer + - local: main_classes/trainer + title: Trainer + - local: main_classes/deepspeed + title: DeepSpeed + - local: main_classes/executorch + title: ExecuTorch + - local: main_classes/feature_extractor + title: Feature Extractor + - local: main_classes/image_processor + title: Image Processor + title: Main classes + - sections: + - sections: + - local: model_doc/albert + title: ALBERT + - local: model_doc/bamba + title: Bamba + - local: model_doc/bart + title: BART + - local: model_doc/barthez + title: BARThez + - local: model_doc/bartpho + title: BARTpho + - local: model_doc/bert + title: BERT + - local: model_doc/bert-generation + title: BertGeneration + - local: model_doc/bert-japanese + title: BertJapanese + - local: model_doc/bertweet + title: Bertweet + - local: model_doc/big_bird + title: BigBird + - local: model_doc/bigbird_pegasus + title: BigBirdPegasus + - local: model_doc/biogpt + title: BioGpt + - local: model_doc/blenderbot + title: Blenderbot + - local: model_doc/blenderbot-small + title: Blenderbot Small + - local: model_doc/bloom + title: BLOOM + - local: model_doc/bort + title: BORT + - local: model_doc/byt5 + title: ByT5 + - local: model_doc/camembert + title: CamemBERT + - local: model_doc/canine + title: CANINE + - local: model_doc/codegen + title: CodeGen + - local: model_doc/code_llama + title: CodeLlama + - local: model_doc/cohere + title: Cohere + - local: model_doc/cohere2 + title: Cohere2 + - local: model_doc/convbert + title: ConvBERT + - local: model_doc/cpm + title: CPM + - local: model_doc/cpmant + title: CPMANT + - local: model_doc/ctrl + title: CTRL + - local: model_doc/dbrx + title: DBRX + - local: model_doc/deberta + title: DeBERTa + - local: model_doc/deberta-v2 + title: DeBERTa-v2 + - local: model_doc/dialogpt + title: DialoGPT + - local: model_doc/diffllama + title: DiffLlama + - local: model_doc/distilbert + title: DistilBERT + - local: model_doc/dpr + title: DPR + - local: model_doc/electra + title: ELECTRA + - local: model_doc/encoder-decoder + title: Encoder Decoder Models + - local: model_doc/ernie + title: ERNIE + - local: model_doc/ernie_m + title: ErnieM + - local: model_doc/esm + title: ESM + - local: model_doc/falcon + title: Falcon + - local: model_doc/falcon3 + title: Falcon3 + - local: model_doc/falcon_mamba + title: FalconMamba + - local: model_doc/flan-t5 + title: FLAN-T5 + - local: model_doc/flan-ul2 + title: FLAN-UL2 + - local: model_doc/flaubert + title: FlauBERT + - local: model_doc/fnet + title: FNet + - local: model_doc/fsmt + title: FSMT + - local: model_doc/funnel + title: Funnel Transformer + - local: model_doc/fuyu + title: Fuyu + - local: model_doc/gemma + title: Gemma + - local: model_doc/gemma2 + title: Gemma2 + - local: model_doc/glm + title: GLM + - local: model_doc/openai-gpt + title: GPT + - local: model_doc/gpt_neo + title: GPT Neo + - local: model_doc/gpt_neox + title: GPT NeoX + - local: model_doc/gpt_neox_japanese + title: GPT NeoX Japanese + - local: model_doc/gptj + title: GPT-J + - local: model_doc/gpt2 + title: GPT2 + - local: model_doc/gpt_bigcode + title: GPTBigCode + - local: model_doc/gptsan-japanese + title: GPTSAN Japanese + - local: model_doc/gpt-sw3 + title: GPTSw3 + - local: model_doc/granite + title: Granite + - local: model_doc/granitemoe + title: GraniteMoe + - local: model_doc/granitemoeshared + title: GraniteMoeShared + - local: model_doc/granitevision + title: GraniteVision + - local: model_doc/helium + title: Helium + - local: model_doc/herbert + title: HerBERT + - local: model_doc/ibert + title: I-BERT + - local: model_doc/jamba + title: Jamba + - local: model_doc/jetmoe + title: JetMoe + - local: model_doc/jukebox + title: Jukebox + - local: model_doc/led + title: LED + - local: model_doc/llama + title: LLaMA + - local: model_doc/llama2 + title: Llama2 + - local: model_doc/llama3 + title: Llama3 + - local: model_doc/longformer + title: Longformer + - local: model_doc/longt5 + title: LongT5 + - local: model_doc/luke + title: LUKE + - local: model_doc/m2m_100 + title: M2M100 + - local: model_doc/madlad-400 + title: MADLAD-400 + - local: model_doc/mamba + title: Mamba + - local: model_doc/mamba2 + title: mamba2 + - local: model_doc/marian + title: MarianMT + - local: model_doc/markuplm + title: MarkupLM + - local: model_doc/mbart + title: MBart and MBart-50 + - local: model_doc/mega + title: MEGA + - local: model_doc/megatron-bert + title: MegatronBERT + - local: model_doc/megatron_gpt2 + title: MegatronGPT2 + - local: model_doc/mistral + title: Mistral + - local: model_doc/mistral3 + title: Mistral3 + - local: model_doc/mixtral + title: Mixtral + - local: model_doc/mluke + title: mLUKE + - local: model_doc/mobilebert + title: MobileBERT + - local: model_doc/modernbert + title: ModernBert + - local: model_doc/mpnet + title: MPNet + - local: model_doc/mpt + title: MPT + - local: model_doc/mra + title: MRA + - local: model_doc/mt5 + title: MT5 + - local: model_doc/mvp + title: MVP + - local: model_doc/myt5 + title: myt5 + - local: model_doc/nemotron + title: Nemotron + - local: model_doc/nezha + title: NEZHA + - local: model_doc/nllb + title: NLLB + - local: model_doc/nllb-moe + title: NLLB-MoE + - local: model_doc/nystromformer + title: Nyströmformer + - local: model_doc/olmo + title: OLMo + - local: model_doc/olmo2 + title: OLMo2 + - local: model_doc/olmoe + title: OLMoE + - local: model_doc/open-llama + title: Open-Llama + - local: model_doc/opt + title: OPT + - local: model_doc/pegasus + title: Pegasus + - local: model_doc/pegasus_x + title: PEGASUS-X + - local: model_doc/persimmon + title: Persimmon + - local: model_doc/phi + title: Phi + - local: model_doc/phi3 + title: Phi-3 + - local: model_doc/phimoe + title: PhiMoE + - local: model_doc/phobert + title: PhoBERT + - local: model_doc/plbart + title: PLBart + - local: model_doc/prophetnet + title: ProphetNet + - local: model_doc/qdqbert + title: QDQBert + - local: model_doc/qwen2 + title: Qwen2 + - local: model_doc/qwen2_moe + title: Qwen2MoE + - local: model_doc/rag + title: RAG + - local: model_doc/realm + title: REALM + - local: model_doc/recurrent_gemma + title: RecurrentGemma + - local: model_doc/reformer + title: Reformer + - local: model_doc/rembert + title: RemBERT + - local: model_doc/retribert + title: RetriBERT + - local: model_doc/roberta + title: RoBERTa + - local: model_doc/roberta-prelayernorm + title: RoBERTa-PreLayerNorm + - local: model_doc/roc_bert + title: RoCBert + - local: model_doc/roformer + title: RoFormer + - local: model_doc/rwkv + title: RWKV + - local: model_doc/splinter + title: Splinter + - local: model_doc/squeezebert + title: SqueezeBERT + - local: model_doc/stablelm + title: StableLm + - local: model_doc/starcoder2 + title: Starcoder2 + - local: model_doc/switch_transformers + title: SwitchTransformers + - local: model_doc/t5 + title: T5 + - local: model_doc/t5v1.1 + title: T5v1.1 + - local: model_doc/tapex + title: TAPEX + - local: model_doc/transfo-xl + title: Transformer XL + - local: model_doc/ul2 + title: UL2 + - local: model_doc/umt5 + title: UMT5 + - local: model_doc/xmod + title: X-MOD + - local: model_doc/xglm + title: XGLM + - local: model_doc/xlm + title: XLM + - local: model_doc/xlm-prophetnet + title: XLM-ProphetNet + - local: model_doc/xlm-roberta + title: XLM-RoBERTa + - local: model_doc/xlm-roberta-xl + title: XLM-RoBERTa-XL + - local: model_doc/xlm-v + title: XLM-V + - local: model_doc/xlnet + title: XLNet + - local: model_doc/yoso + title: YOSO + - local: model_doc/zamba + title: Zamba + - local: model_doc/zamba2 + title: Zamba2 + title: Text models + - sections: + - local: model_doc/beit + title: BEiT + - local: model_doc/bit + title: BiT + - local: model_doc/conditional_detr + title: Conditional DETR + - local: model_doc/convnext + title: ConvNeXT + - local: model_doc/convnextv2 + title: ConvNeXTV2 + - local: model_doc/cvt + title: CvT + - local: model_doc/dab-detr + title: DAB-DETR + - local: model_doc/deformable_detr + title: Deformable DETR + - local: model_doc/deit + title: DeiT + - local: model_doc/depth_anything + title: Depth Anything + - local: model_doc/depth_anything_v2 + title: Depth Anything V2 + - local: model_doc/depth_pro + title: DepthPro + - local: model_doc/deta + title: DETA + - local: model_doc/detr + title: DETR + - local: model_doc/dinat + title: DiNAT + - local: model_doc/dinov2 + title: DINOV2 + - local: model_doc/dinov2_with_registers + title: DINOv2 with Registers + - local: model_doc/dit + title: DiT + - local: model_doc/dpt + title: DPT + - local: model_doc/efficientformer + title: EfficientFormer + - local: model_doc/efficientnet + title: EfficientNet + - local: model_doc/focalnet + title: FocalNet + - local: model_doc/glpn + title: GLPN + - local: model_doc/hiera + title: Hiera + - local: model_doc/ijepa + title: I-JEPA + - local: model_doc/imagegpt + title: ImageGPT + - local: model_doc/levit + title: LeViT + - local: model_doc/mask2former + title: Mask2Former + - local: model_doc/maskformer + title: MaskFormer + - local: model_doc/mobilenet_v1 + title: MobileNetV1 + - local: model_doc/mobilenet_v2 + title: MobileNetV2 + - local: model_doc/mobilevit + title: MobileViT + - local: model_doc/mobilevitv2 + title: MobileViTV2 + - local: model_doc/nat + title: NAT + - local: model_doc/poolformer + title: PoolFormer + - local: model_doc/pvt + title: Pyramid Vision Transformer (PVT) + - local: model_doc/pvt_v2 + title: Pyramid Vision Transformer v2 (PVTv2) + - local: model_doc/regnet + title: RegNet + - local: model_doc/resnet + title: ResNet + - local: model_doc/rt_detr + title: RT-DETR + - local: model_doc/rt_detr_v2 + title: RT-DETRv2 + - local: model_doc/segformer + title: SegFormer + - local: model_doc/seggpt + title: SegGpt + - local: model_doc/superglue + title: SuperGlue + - local: model_doc/superpoint + title: SuperPoint + - local: model_doc/swiftformer + title: SwiftFormer + - local: model_doc/swin + title: Swin Transformer + - local: model_doc/swinv2 + title: Swin Transformer V2 + - local: model_doc/swin2sr + title: Swin2SR + - local: model_doc/table-transformer + title: Table Transformer + - local: model_doc/textnet + title: TextNet + - local: model_doc/timm_wrapper + title: Timm Wrapper + - local: model_doc/upernet + title: UperNet + - local: model_doc/van + title: VAN + - local: model_doc/vit + title: Vision Transformer (ViT) + - local: model_doc/vit_hybrid + title: ViT Hybrid + - local: model_doc/vitdet + title: ViTDet + - local: model_doc/vit_mae + title: ViTMAE + - local: model_doc/vitmatte + title: ViTMatte + - local: model_doc/vit_msn + title: ViTMSN + - local: model_doc/vitpose + title: ViTPose + - local: model_doc/yolos + title: YOLOS + - local: model_doc/zoedepth + title: ZoeDepth + title: Vision models + - sections: + - local: model_doc/audio-spectrogram-transformer + title: Audio Spectrogram Transformer + - local: model_doc/bark + title: Bark + - local: model_doc/clap + title: CLAP + - local: model_doc/dac + title: dac + - local: model_doc/encodec + title: EnCodec + - local: model_doc/fastspeech2_conformer + title: FastSpeech2Conformer + - local: model_doc/hubert + title: Hubert + - local: model_doc/mctct + title: MCTCT + - local: model_doc/mimi + title: Mimi + - local: model_doc/mms + title: MMS + - local: model_doc/moonshine + title: Moonshine + - local: model_doc/moshi + title: Moshi + - local: model_doc/musicgen + title: MusicGen + - local: model_doc/musicgen_melody + title: MusicGen Melody + - local: model_doc/pop2piano + title: Pop2Piano + - local: model_doc/seamless_m4t + title: Seamless-M4T + - local: model_doc/seamless_m4t_v2 + title: SeamlessM4T-v2 + - local: model_doc/sew + title: SEW + - local: model_doc/sew-d + title: SEW-D + - local: model_doc/speech_to_text + title: Speech2Text + - local: model_doc/speech_to_text_2 + title: Speech2Text2 + - local: model_doc/speecht5 + title: SpeechT5 + - local: model_doc/unispeech + title: UniSpeech + - local: model_doc/unispeech-sat + title: UniSpeech-SAT + - local: model_doc/univnet + title: UnivNet + - local: model_doc/vits + title: VITS + - local: model_doc/wav2vec2 + title: Wav2Vec2 + - local: model_doc/wav2vec2-bert + title: Wav2Vec2-BERT + - local: model_doc/wav2vec2-conformer + title: Wav2Vec2-Conformer + - local: model_doc/wav2vec2_phoneme + title: Wav2Vec2Phoneme + - local: model_doc/wavlm + title: WavLM + - local: model_doc/whisper + title: Whisper + - local: model_doc/xls_r + title: XLS-R + - local: model_doc/xlsr_wav2vec2 + title: XLSR-Wav2Vec2 + title: Audio models + - sections: + - local: model_doc/timesformer + title: TimeSformer + - local: model_doc/videomae + title: VideoMAE + - local: model_doc/vivit + title: ViViT + title: Video models + - sections: + - local: model_doc/align + title: ALIGN + - local: model_doc/altclip + title: AltCLIP + - local: model_doc/aria + title: Aria + - local: model_doc/aya_vision + title: AyaVision + - local: model_doc/blip + title: BLIP + - local: model_doc/blip-2 + title: BLIP-2 + - local: model_doc/bridgetower + title: BridgeTower + - local: model_doc/bros + title: BROS + - local: model_doc/chameleon + title: Chameleon + - local: model_doc/chinese_clip + title: Chinese-CLIP + - local: model_doc/clip + title: CLIP + - local: model_doc/clipseg + title: CLIPSeg + - local: model_doc/clvp + title: CLVP + - local: model_doc/colpali + title: ColPali + - local: model_doc/data2vec + title: Data2Vec + - local: model_doc/deplot + title: DePlot + - local: model_doc/donut + title: Donut + - local: model_doc/emu3 + title: Emu3 + - local: model_doc/flava + title: FLAVA + - local: model_doc/gemma3 + title: Gemma3 + - local: model_doc/git + title: GIT + - local: model_doc/got_ocr2 + title: GOT-OCR2 + - local: model_doc/grounding-dino + title: Grounding DINO + - local: model_doc/groupvit + title: GroupViT + - local: model_doc/idefics + title: IDEFICS + - local: model_doc/idefics2 + title: Idefics2 + - local: model_doc/idefics3 + title: Idefics3 + - local: model_doc/instructblip + title: InstructBLIP + - local: model_doc/instructblipvideo + title: InstructBlipVideo + - local: model_doc/kosmos-2 + title: KOSMOS-2 + - local: model_doc/layoutlm + title: LayoutLM + - local: model_doc/layoutlmv2 + title: LayoutLMV2 + - local: model_doc/layoutlmv3 + title: LayoutLMV3 + - local: model_doc/layoutxlm + title: LayoutXLM + - local: model_doc/lilt + title: LiLT + - local: model_doc/llava + title: Llava + - local: model_doc/llava_next + title: LLaVA-NeXT + - local: model_doc/llava_next_video + title: LLaVa-NeXT-Video + - local: model_doc/llava_onevision + title: LLaVA-Onevision + - local: model_doc/lxmert + title: LXMERT + - local: model_doc/matcha + title: MatCha + - local: model_doc/mgp-str + title: MGP-STR + - local: model_doc/mllama + title: mllama + - local: model_doc/nougat + title: Nougat + - local: model_doc/omdet-turbo + title: OmDet-Turbo + - local: model_doc/oneformer + title: OneFormer + - local: model_doc/owlvit + title: OWL-ViT + - local: model_doc/owlv2 + title: OWLv2 + - local: model_doc/paligemma + title: PaliGemma + - local: model_doc/perceiver + title: Perceiver + - local: model_doc/pix2struct + title: Pix2Struct + - local: model_doc/pixtral + title: Pixtral + - local: model_doc/qwen2_5_vl + title: Qwen2.5-VL + - local: model_doc/qwen2_audio + title: Qwen2Audio + - local: model_doc/qwen2_vl + title: Qwen2VL + - local: model_doc/sam + title: Segment Anything + - local: model_doc/siglip + title: SigLIP + - local: model_doc/siglip2 + title: SigLIP2 + - local: model_doc/smolvlm + title: SmolVLM + - local: model_doc/speech-encoder-decoder + title: Speech Encoder Decoder Models + - local: model_doc/tapas + title: TAPAS + - local: model_doc/trocr + title: TrOCR + - local: model_doc/tvlt + title: TVLT + - local: model_doc/tvp + title: TVP + - local: model_doc/udop + title: UDOP + - local: model_doc/video_llava + title: VideoLlava + - local: model_doc/vilt + title: ViLT + - local: model_doc/vipllava + title: VipLlava + - local: model_doc/vision-encoder-decoder + title: Vision Encoder Decoder Models + - local: model_doc/vision-text-dual-encoder + title: Vision Text Dual Encoder + - local: model_doc/visual_bert + title: VisualBERT + - local: model_doc/xclip + title: X-CLIP + title: Multimodal models + - sections: + - local: model_doc/decision_transformer + title: Decision Transformer + - local: model_doc/trajectory_transformer + title: Trajectory Transformer + title: Reinforcement learning models + - sections: + - local: model_doc/autoformer + title: Autoformer + - local: model_doc/informer + title: Informer + - local: model_doc/patchtsmixer + title: PatchTSMixer + - local: model_doc/patchtst + title: PatchTST + - local: model_doc/time_series_transformer + title: Time Series Transformer + title: Time series models + - sections: + - local: model_doc/graphormer + title: Graphormer + title: Graph models + title: Models + - sections: + - local: internal/modeling_utils + title: Custom Layers and Utilities + - local: internal/pipelines_utils + title: Utilities for pipelines + - local: internal/tokenization_utils + title: Utilities for Tokenizers + - local: internal/trainer_utils + title: Utilities for Trainer + - local: internal/generation_utils + title: Utilities for Generation + - local: internal/image_processing_utils + title: Utilities for Image Processors + - local: internal/audio_utils + title: Utilities for Audio processing + - local: internal/file_utils + title: General Utilities + - local: internal/time_series_utils + title: Utilities for Time Series + title: Internal helpers + title: API diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/accelerate.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/accelerate.md new file mode 100644 index 0000000000000000000000000000000000000000..c0ad46f8ac91fba157953fcba5143e437681d196 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/accelerate.md @@ -0,0 +1,165 @@ + + +# Accelerate + +[Accelerate](https://hf.co/docs/accelerate/index) is a library designed to simplify distributed training on any type of setup with PyTorch by uniting the most common frameworks ([Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) and [DeepSpeed](https://www.deepspeed.ai/)) for it into a single interface. [`Trainer`] is powered by Accelerate under the hood, enabling loading big models and distributed training. + +This guide will show you two ways to use Accelerate with Transformers, using FSDP as the backend. The first method demonstrates distributed training with [`Trainer`], and the second method demonstrates adapting a PyTorch training loop. For more detailed information about Accelerate, please refer to the [documentation](https://hf.co/docs/accelerate/index). + +```bash +pip install accelerate +``` + +Start by running [accelerate config](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-config) in the command line to answer a series of prompts about your training system. This creates and saves a configuration file to help Accelerate correctly set up training based on your setup. + +```bash +accelerate config +``` + +Depending on your setup and the answers you provide, an example configuration file for distributing training with FSDP on one machine with two GPUs may look like the following. + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_forward_prefetch: false + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +## Trainer + +Pass the path to the saved configuration file to [`TrainingArguments`], and from there, pass your [`TrainingArguments`] to [`Trainer`]. + +```py +from transformers import TrainingArguments, Trainer + +training_args = TrainingArguments( + output_dir="your-model", + learning_rate=2e-5, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + num_train_epochs=2, + fsdp_config="path/to/fsdp_config", + fsdp_strategy="full_shard", + weight_decay=0.01, + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + push_to_hub=True, +) + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], + processing_class=tokenizer, + data_collator=data_collator, + compute_metrics=compute_metrics, +) + +trainer.train() +``` + +## Native PyTorch + +Accelerate can also be added to any PyTorch training loop to enable distributed training. The [`~accelerate.Accelerator`] is the main entry point for adapting your PyTorch code to work with Accelerate. It automatically detects your distributed training setup and initializes all the necessary components for training. You don't need to explicitly place your model on a device because [`~accelerate.Accelerator`] knows which device to move your model to. + +```py +from accelerate import Accelerator + +accelerator = Accelerator() +device = accelerator.device +``` + +All PyTorch objects (model, optimizer, scheduler, dataloaders) should be passed to the [`~accelerate.Accelerator.prepare`] method now. This method moves your model to the appropriate device or devices, adapts the optimizer and scheduler to use [`~accelerate.optimizer.AcceleratedOptimizer`] and [`~accelerate.scheduler.AcceleratedScheduler`], and creates a new shardable dataloader. + +```py +train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( + train_dataloader, eval_dataloader, model, optimizer +) +``` + +Replace `loss.backward` in your training loop with Accelerates [`~accelerate.Accelerator.backward`] method to scale the gradients and determine the appropriate `backward` method to use depending on your framework (for example, DeepSpeed or Megatron). + +```py +for epoch in range(num_epochs): + for batch in train_dataloader: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + progress_bar.update(1) +``` + +Combine everything into a function and make it callable as a script. + +```py +from accelerate import Accelerator + +def main(): + accelerator = Accelerator() + + model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler + ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + +if __name__ == "__main__": + main() +``` + +From the command line, call [accelerate launch](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-launch) to run your training script. Any additional arguments or parameters can be passed here as well. + +To launch your training script on two GPUs, add the `--num_processes` argument. + +```bash +accelerate launch --num_processes=2 your_script.py +``` + +Refer to the [Launching Accelerate scripts](https://hf.co/docs/accelerate/main/en/basic_tutorials/launch) for more details. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_model.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..6f8e5499ba47867257b60688a329b53d7d7c984b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_model.md @@ -0,0 +1,623 @@ + + +# Adding a new model to Transformers + +> [!TIP] +> Try adding new models with a more [modular](./modular_transformers) approach first. This makes it significantly easier to contribute a model to Transformers! + +Many of the models in Transformers are contributed by developers and researchers. As an open-source first project, we're invested in empowering the community to actively and independently add more models. + +When you add a model to Transformers, you'll learn: + +- more about open-source best practices +- about a models architecture +- about Transformers' design principles +- how to efficiently test large models +- how to use Python utilities like [Black](https://black.readthedocs.io/en/stable/) and [Ruff](https://docs.astral.sh/ruff/) to create clean and readable code + +It is a challenging but rewarding process. + +This guide will walk you through adding an example BrandNewLlama PyTorch model to Transformers. Before you begin, it is a good idea to familiarize yourself with the library. + +## Transformers overview + +Transformers is an opinionated library with its own unique philosophy and design choices. These choices help us sustainably scale and maintain Transformers. + +> [!TIP] +> Learn more about our design principles on the [Philosophy](./philosophy) doc. + +Some of these design choices are: + +- composition > over-abstraction +- duplicate code isn't always bad if it greatly improves readability and accessibility +- model files are self-contained and all the necessary model code is found in the `modeling_mymodel.py` file + +These design choices are important *for everyone* interacting with the model. It is easier to read, understand, and modify. + +This section describes how the model and configuration classes interact and the Transformers code style. + +### Model and configuration + +All Transformers' models inherit from a base [`PreTrainedModel`] and [`PretrainedConfig`] class. The configuration is the models blueprint. + +There is never more than two levels of abstraction for any model to keep the code readable. The example model here, BrandNewLlama, inherits from `BrandNewLlamaPreTrainedModel` and [`PreTrainedModel`]. It is important that a new model only depends on [`PreTrainedModel`] so that it can use the [`~PreTrainedModel.from_pretrained`] and [`~PreTrainedModel.save_pretrained`] methods. + +Other important functions like the forward method are defined in the `modeling.py` file. + +Specific model heads (for example, sequence classification or language modeling) should call the base model in the forward pass rather than inheriting from it to keep abstraction low. + +New models require a configuration, for example `BrandNewLlamaConfig`, that is stored as an attribute of [`PreTrainedModel`]. + +```py +model = BrandNewLlamaModel.from_pretrained("username/brand_new_llama") +model.config +``` + +[`PretrainedConfig`] provides the [`~PretrainedConfig.from_pretrained`] and [`~PretrainedConfig.save_pretrained`] methods. + +When you use [`PreTrainedModel.save_pretrained`], it automatically calls [`PretrainedConfig.save_pretrained`] so that both the model and configuration are saved together. + +A model is saved to a `model.safetensors` file and a configuration is saved to a `config.json` file. + +### Code style + +Transformers prefers a clean and readable code over a more abstracted code style. Some of the code style choices include: + +- The code should be accessible to non-English users. Pick descriptive variable names and avoid abbreviations. For example, "activation" is preferred over "act". One letter variables names are highly discouraged unless it's an index in a for loop. + +- Explicit code is preferred - even if it's longer - over shorter code. + +- Avoid subclassing [nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html). Subclass [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module) instead so the code can be quickly debugged with print statements or breakpoints. + +- Function signatures should be type-annotated. Otherwise, use good variable names so they're more understandable. + +## New model addition issue + +Open a [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) issue to add a specific model. + +> [!TIP] +> Filter by the [New model](https://github.com/huggingface/transformers/labels/New%20model) label on GitHub to view and add any existing model requests. + +Now is a good time to get familiar with BrandNewLlama. It is helpful to read a models research paper to understand its technical design and implementation. You don't necessarily have to worry too much about the theoretical details. Instead, focus on the practical ones. Use the questions below to guide your reading. + +- What type of model is BrandNewLlama? Is it a encoder, decoder, or encoder-decoder model? +- What tasks can BrandNewLlama be used for? +- What makes BrandNewLlama different from other models? +- What models in Transformers are most similar to BrandNewLlama? +- What tokenizer does BrandNewLlama use? + +In addition to learning more about your model, use the tips below to help you add a model faster. + +> [!TIP] +> Each contributor has a unique style and workflow for adding models to Transformers. For an example, take a look at how [Gemma](https://github.com/huggingface/transformers/pull/29167) was added. + +- Don't reinvent the wheel! Take your time to explore existing models and tokenizers to see what you can copy and reuse. [Grep](https://www.gnu.org/software/grep/) and [ripgrep](https://github.com/BurntSushi/ripgrep) are great tools for this. +- This is more of an engineering than a science challenge. Focus on the more practical (setting up an efficient debugging environment for example) instead of the theorertical aspects of the model. +- Don't be shy to ask for help! We are here to support you. 🤗 + +## Dev environment + +Click on the **Fork** button on the [Transformers](https://github.com/huggingface/transformers) repository to create your own copy to work on. Clone the repository to your local disk and add the base repository as the remote. + +```bash +git clone https://github.com/[your Github handle]/transformers.git +cd transformers +git remote add upstream https://github.com/huggingface/transformers.git +``` + +Create a virtual environment and perform an [editable install](./installation#editable-install) of the library with the "dev" or development dependencies. + +```bash +python -m venv .env +source .env/bin/activate +pip install -e ".[dev]" +``` + +Due to the number of optional dependencies as Transformers grows, this command may fail. In this case, install the "quality" dependencies. Also make sure you have a deep learning framework installed. + +```bash +pip install -e ".[quality]" +``` + +Return to the parent directory and clone and install the original BrandNewLlama repository. + +```bash +git clone https://github.com/org_that_created_brand_new_llama_org/brand_new_llama.git +cd brand_new_bert +pip install -e . +``` + +Return to your clone of Transformers to begin porting BrandNewLlama. + +```bash +cd transformers +``` + +There are two possible debugging environments for running the original model, a notebook ([Google Colab](https://colab.research.google.com/notebooks/intro.ipynb) or [Jupyter](https://jupyter.org/)) or a local Python script. + +> [!WARNING] +> We don't recommend setting up a GPU environment to run the original model because it can be expensive. Instead, work in a CPU environment first to verify the model works in Transformers. Once it does, then you can verify it on a GPU. + +Notebooks are great for executing code cell-by-cell which can help split logical components from one another. It can also accelerate debugging cycles because intermediate results can be stored. You can also share notebooks when working with other contributors. + +The downside is that if you aren't used to them, it may take some time to get used to. + +> [!TIP] +> If the model architecture is identical to an existing model, skip ahead to add a [conversion script](#conversion-script), because you can reuse the architecture of the existing model. + +Run the command below to start and complete the questionnaire with some basic information about the new model. This command jumpstarts the process by automatically generating some model code that you'll need to adapt. + +```bash +transformers-cli add-new-model-like +``` + +## Create a pull request + +Before you start adapting the code, create a pull request to track your progress and get feedback from the Transformers team. Title your pull request **[WIP] Add BrandNewLlama** so it's clear that this is a work in progress. + +Create a branch with a descriptive name from your main branch. + +```bash +git checkout -b add_brand_new_bert +``` + +Commit the code, and then fetch and rebase on the main branch. + +```bash +git add . +git commit +git fetch upstream +git rebase upstream/main +``` + +Push any changes to your branch and click on **Compare & pull request** to open a pull request on GitHub. Open the pull request as a *draft* to indicate it's a work in progress. + +```bash +git push -u origin a-descriptive-name-for-my-changes +``` + +Include relevant Hugging Face team members by adding their GitHub handles in the pull request for questions, feedback, comments, and reviews. Direct team members to specific parts of the code you want by clicking on the **Files changed** tab, and then clicking on **+** to the left of the line number to add a comment. When a question or problem is solved, click on **Resolve** to indicate the issue is resolved. This keeps the conversation organized and clean. + +Remember to periodically commit and push your work, and update your work with the current main branch. + +```bash +git fetch upstream +git merge upstream/main +``` + +## Original checkpoint + +Take some time to work on the original model implementation first to understand how it works. + +This can be difficult if the original model repository is lacking documentation or if the codebase is complex. But you should use this as your motivation to implement the model in Transformers. Your contribution makes it more accessible and user-friendly to everyone! + +Orient yourself with the original repository by doing the following. + +- Locate the pretrained weights. +- Figure out how to the load pretrained weights into the model. +- Figure out how to run the tokenizer independently of the model. +- Trace one forward pass to understand which classes and functions are required. These are probably the only classes and functions you'll have to implement. +- Locate all the important components (model class, model subclasses, self-attention layer, etc.) of the model. +- Figure out how to debug the model in the original repository. Add print statements, use interactive debuggers like [ipdb](https://github.com/gotcha/ipdb), or a efficient integrated development environment (IDE) like [PyCharm](https://www.jetbrains.com/pycharm/). + +The last point is especially important because you'll need a thorough understanding of what's happening inside the original model before you can reimplement it in Transformers. Feel free to open issues and pull requests in the original repository if you encounter any issues. + +A good first step is to load a *small* pretrained checkpoint and try to reproduce a single forward pass with an example integer vector of inputs. For example, in pseudocode, this could look like the following. + +```py +model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids +original_output = model.generate(input_ids) +``` + +### Debugging + +If you run into issues, you'll need to choose one of the following debugging strategies depending on the original models codebase. + + + + +This strategy relies on breaking the original model into smaller sub-components, such as when the code can be easily run in eager mode. While more difficult, there are some advantages to this approach. + +1. It is easier later to compare the original model to your implementation. You can automatically verify that each individual component matches its corresponding component in the Transformers' implementation. This is better than relying on a visual comparison based on print statements. +2. It is easier to port individual components instead of the entire model. +3. It is easier for understanding how a model works by breaking it up into smaller parts. +4. It is easier to prevent regressions at a later stage when you change your code thanks to component-by-component tests. + +> [!TIP] +> Refer to the ELECTRA [integration checks](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed) for a good example of how to decompose a model into smaller components. + + + + +This strategy is viable when the original codebase is too complex, only allows intermediate components to be run in compiled mode, or if it's too time-consuming (maybe even impossible) to separate the model into smaller sub-components. + +For example, the MeshTensorFlow implementation of [T5](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) is too complex and doesn't offer a simple way to decompose the model into its sub-components. In this situation, you'll have to rely on verifying print statements. + + + + +Whichever strategy you choose, it is recommended to debug the initial layers first and the final layers last. Retrieve the output, either with print statements or sub-component functions, of the following layers in this order. + +1. input ids passed to the model +2. word embeddings +3. input of the first Transformer layer +4. output of the first Transformer layer +5. output of the following n-1 Transformer layers +6. output of the whole model + +The input ids should just be an array of integers like `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`. + +Layer outputs often consist of multi-dimensional float arrays. + +```py +[[ + [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024], + [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132], + [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648], + ..., + [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288], + [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191], + [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]], +``` + +Every Transformers model output should have a precision or error tolerance of *1e-3*. This accounts for any output differences that arise from using a different library framework. Compare the intermediate outputs of the original model with the Transformers implementation to ensure they're nearly identical. Having an *efficient* debugging environment is crucial for this step. + +Here are some tips for an efficient debugging environment. + +- To debug intermediate results, it depends on the machine learning framework the original model repository is using. For PyTorch, you should write a script to decompose the original model into smaller sub-components to retrieve the intermediate values. For TensorFlow, you may need to use [tf.print](https://www.tensorflow.org/api_docs/python/tf/print). For Flax, make sure the model is *not jitted* during the forward pass (refer to this GitHub [Issue](https://github.com/google/jax/issues/196) for more details). + +- It is faster to debug with a smaller pretrained checkpoint versus a larger checkpoint where the forward pass takes more than 10 seconds. If only large checkpoints are available, create a dummy model with randomly initialized weights and save those weights to compare against the Transformers implementation. + +- Find the easiest way to call the model's forward pass. Ideally, this function (may be called `predict`, `evaluate`, `forward`, or `__call__`) should only call the forward pass *once*. It is more difficult to debug a function that calls the forward pass multiple times. + +- Separate tokenization from the forward pass. Locate where a string input is changed to input ids in the forward pass and start here. You may need to create a small script or modify the original code to directly input the input ids instead of an input string. + +- Ensure the model is *not* in training mode. This can produce random outputs due to multiple dropout layers in a model. The forward pass in your debugging environment should be *deterministic* so that the dropout layers aren't used. + +Once you're able to run the original checkpoint, you're ready to start adapting the model code for Transformers. + +## Adapt the model code + +The `transformers-cli add-new-model-like` command should have generated a model and configuration file. + +- `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` +- `src/transformers/models/brand_new_llama/configuration_brand_new_llama.py` + +The automatically generated code in the `modeling.py` file has the same architecture as Llama if you answered it's a decoder-only model or it will have the same architecture as BART if you answered it's an encoder-decoder model. The generated code is just a starting point. Based on your research on the new model, you'll need to implement those specific changes by adapting the generated code. This may involve changes to the self-attention layer, the order of the normalization layer, and so on. + +### Model initialization + +At this point, your code doesn't have to be clean or even fully correct, It is more efficient to quickly create a first draft and then iteratively improve on it. The most important thing is that your model can be instantiated from Transformers. The command below creates a model from the configuration with random weights, verifying that the `__init__` method works. + +```py +from transformers import BrandNewLlama, BrandNewLlamaConfig +model = BrandNewLlama(BrandNewLlamaConfig()) +``` + +Random initialization occurs in the `_init_weights` method of `BrandNewLlamaPreTrainedModel`. All leaf modules are initialized depending on the configuration's variables. + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) +``` + +The initialization scheme can look different if you need to adapt it to your model. For example, [`Wav2Vec2ForPreTraining`] initializes [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) in its last two linear layers. + +The `_is_hf_initialized` flag makes sure the submodule is only initialized once. Setting `module.project_q` and `module.project_hid` to `True` ensures the custom initialization is not overridden later. The `_init_weights` function won't be applied to these modules. + +```py +def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, Wav2Vec2ForPreTraining): + module.project_hid.reset_parameters() + module.project_q.reset_parameters() + module.project_hid._is_hf_initialized = True + module.project_q._is_hf_initialized = True + elif isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() +``` + +### Convert checkpoints to Transformers + +The original checkpoint must be converted to a Transformers compatible checkpoint. + +> [!TIP] +> Try looking for an existing conversion script to copy, adapt, and reuse for your model! +> +> - If you're porting a model from TensorFlow to PyTorch, a good starting point may be the BERT [conversion script](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91). +> - If you're porting a model from PyTorch to PyTorch, a good starting point may be the BART [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py). + +Make sure **all** required weights are initialized and print out all the checkpoint weights that weren't used for initialization to make sure the model has been converted correctly. + +You may encounter wrong shape statements or name assignments during the conversion. This is most likely because of incorrect parameters in `BrandNewLlamaConfig`, the wrong architecture, a bug in the `init` method of your implementation, or you need to transpose one of the checkpoint weights. + +Keep iterating on the [Adapt the model code](#adapt-the-model-code) section until all the checkpoint weights are correctly loaded. Once you can load a checkpoint in your model, save it to a folder. This should contain a `model.safetensors` file and a `config.json` file. + +```py +model.save_pretrained("/path/to/converted/checkpoint/folder") +``` + +To help with conversion, the next section briefly describes how PyTorch models stores and defines layer weights and names. + +#### PyTorch layer weights and names + +It is helpful to create a basic PyTorch model to understand how layer names are defined and weights are initialized. + +```py +from torch import nn + +class SimpleModel(nn.Module): + def __init__(self): + super().__init__() + self.dense = nn.Linear(10, 10) + self.intermediate = nn.Linear(10, 10) + self.layer_norm = nn.LayerNorm(10) +``` + +PyTorch layer names are defined by the class attribute name of the layer (`dense`, `intermediate`, `layer_norm`). Create a instance of `SimpleModel` to fill all the layers with random weights. + +```py +model = SimpleModel() +print(model) +SimpleModel( + (dense): Linear(in_features=10, out_features=10, bias=True) + (intermediate): Linear(in_features=10, out_features=10, bias=True) + (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) +) +``` + +The weight values of a specific layer are randomly initialized. + +```py +print(model.dense.weight.data) +tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, + -0.2077, 0.2157], + [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, + 0.2166, -0.0212], + [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, + -0.1023, -0.0447], + [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, + -0.1876, -0.2467], + [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, + 0.2577, 0.0402], + [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, + 0.2132, 0.1680], + [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, + 0.2707, -0.2509], + [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, + 0.1829, -0.1568], + [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, + 0.0333, -0.0536], + [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, + 0.2220, 0.2358]]). +``` + +In the conversion script, the random weights should be replaced with the exact weights from the corresponding layer in the original checkpoint. + +```py +# retrieve matching layer weights with recursive algorithm +layer_name = "dense" +pretrained_weight = array_of_dense_layer + +model_pointer = getattr(model, "dense") +model_pointer.weight.data = torch.from_numpy(pretrained_weight) +``` + +Verify the randomly initialized weights and their corresponding pretrained checkpoint weights have the identical **shape** and **name**. Add assert statements for the shape and print out the checkpoint weight names. + +```py +assert ( + model_pointer.weight.shape == pretrained_weight.shape +), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" + +logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") +``` + +When the shape or name don't match, you may have assigned the incorrect checkpoint weight to a randomly initialized layer. An incorrect shape may be because the `BrandNewLlama` parameters don't exactly match the original models parameters. But it could also be that the PyTorch layer implementation requires the weights to be transposed first. + +### Implement the forward pass + +The forward pass should be implemented next if the model loads correctly. It takes some inputs and returns the model output. + +```py +model = BrandNewLlamaModel.from_pretrained("/path/to/converted/checkpoint/folder") +input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] +output = model.generate(input_ids).last_hidden_states +``` + +Don't be discouraged if your forward pass isn't identical with the output from the original model or if it returns an error. Check that the forward pass doesn't throw any errors. This is often because the dimensions are wrong or because the wrong data type is used ([torch.long](https://pytorch.org/docs/stable/generated/torch.Tensor.long.html) instead of [torch.float32](https://pytorch.org/docs/stable/tensors.html)). + +Your output should have a precision of *1e-3*. Ensure the output shapes and output values are identical. Common reasons for why the outputs aren't identical include: + +- Some layers were not added (activation layer or a residual connection). +- The word embedding matrix is not tied. +- The wrong positional embeddings are used because the original implementation includes an offset. +- Dropout is applied during the forward pass. Fix this error by making sure `model.training` is `False` and passing `self.training` to [torch.nn.functional.dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout). + +Compare the forward pass of the original model and your implementation to check if there are any differences. Ideally, debug and print out the intermediate outputs of both implementations of the forward pass to pinpoint where the original implementation differs from yours. + +1. Make sure the hardcoded `input_ids` in both implementations are identical. +2. Verify the outputs of the first transformation of `input_ids` (usually the word embeddings) are identical, and work your way through to the last layer. + +Any difference between the two implementations should point to the bug in your implementation. + +One of the best strategies is to add many print statements to the same positions in both implementations, and then successively remove them when they output identical values for the intermediate outputs. + +When both implementations produce the same output, verify the outputs are within a precision of *1e-3*. + +```py +torch.allclose(original_output, output, atol=1e-3) +``` + +This is typically the most difficult part of the process. Congratulations if you've made it this far! + +And if you're stuck or struggling with this step, don't hesitate to ask for help on your pull request. + +### Add model tests + +While the model works, you still need to add tests to ensure it is compatible with Transformers. Tests are important because they help users understand your work by looking at specific tests, and because they prevent your model from breaking in the future if any changes are made. + +[Cookiecutter](https://cookiecutter.readthedocs.io/en/stable/) should have added a test file for your model. Run the test file below to make sure all common tests pass. + +```bash +pytest tests/models/brand_new_llama/test_modeling_brand_new_llama.py +``` + +The integration tests should be added first because they serve the same purpose as the debugging scripts you used earlier to implement the new model in Transformers. A template of those model tests, `BrandNewLlamaModelIntegrationTests`, was added by Cookiecutter and should be filled out. To ensure it passes, run the following command. + + + + +```bash +RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests +``` + + + + +```bash +SET RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests +``` + + + + +All features unique to BrandNewLlama should be tested in a separate test under `BrandNewLlamaModelTester/BrandNewLlamaModelTest`. This test is often overlooked, but it is extremely important because: + +- it helps transfer knowledge you acquired during the process to the community by showing how the models novel features work +- future contributors can quickly test changes to the model by running these special tests + +## Implement tokenizer + +> [!TIP] +> We recommend adding a fast tokenizer ([`PreTrainedTokenizerFast`]) to give users the best performance. Feel free to tag [@ArthurZucker](https://github.com/ArthurZucker) or [@itazap](https://github.com/itazap) in your PR for help on how to add [`PreTrainedTokenizerFast`]. + +With the model out of the way, time to focus on the tokenizer. The tokenizer should be identical or very similar to an existing tokenizer in Transformers. + +Find and load the original tokenizer file into your implementation. Create a script in the original repository that inputs a string and returns the `input_ids`. The pseudocode should look similar to the code below. + +```py +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") +input_ids = model.tokenize(input_str) +``` + +You may need to search the original repository to find the correct tokenizer function or modify the existing tokenizer in your clone of the original repository to only return the `input_ids`. The script for your tokenizer should look similar to the following. + +```py +from transformers import BrandNewLlamaTokenizer + +input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." +tokenizer = BrandNewLlamaTokenizer.from_pretrained("/path/to/tokenizer/folder/") +input_ids = tokenizer(input_str).input_ids +``` + +When both implementations have the same `input_ids`, add a tokenizer test file. This file is analogous to the modeling test files. The tokenizer test files should contain a couple of hardcoded integration tests. + +## Integration tests + +Now that you have a model and tokenizer, add end-to-end integration tests for the model and tokenizer to `tests/models/brand_new_llama/test_modeling_brand_new_llama.py`. + +The test should provide a meaningful text-to-text example to show the model works as expected. For example, you can include a source-to-target translation pair, an article-to-summary pair, or a question-to-answer pair. + +If the checkpoint hasn't been fine-tuned on a downstream task, then the model tests are sufficient. + +Finally, try to make sure your tests can run on a GPU by adding `.to(self.device)` statements to the models internal tensors. If you don't have access to a GPU, we can take care of that for you. + +## Add documentation + +Your model is only useful if users know how to use it. This is why it's important to add documentation and docstrings. Cookiecutter added a template file, `docs/source/model_doc/brand_new_llama.md`, that you can fill out with information about your model. + +This is generally a user's first interaction with a model, so the documentation should be clear and concise. It is often very useful to add examples of how the model should be used. + +Make sure docstrings are added to `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` and includes all necessary inputs and outputs. Review our [guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) for writing documentation and docstrings. + +## Refactor + +Time to tidy things up and make sure the code style is consistent with the rest of the library. Run the following command to automatically fix incorrect styles. + +```bash +make style +``` + +To verify the code style passes quality checks, run the command below. + +```bash +make quality +``` + +There may be other failing tests or checks (missing docstring or incorrect naming) on your pull request due to Transformers strict design tests. We can help you with these issues if you're stuck. + +After ensuring the code runs correctly, you may want to refactor it to make it more readable or cleaner. + +## Upload to the Hub + +Convert and upload all checkpoints to the [Hub](https://hf.co/models). Add a model card to provide more transparency and context about the model. The model card should highlight specific characteristics of a checkpoint, how the model was trained, and code examples of how to use it. + +> [!TIP] +> In many cases, adding an interactive notebook users can run is a great way to showcase how to use the model for inference or fine-tune it on a downstream task. While not required, including a notebook can drive greater adoption of your model. + +You should also consult with the Transformers team to decide on an appropriate name for the model, and getting the required access rights to upload the model. + +Use the [`~PreTrainedModel.push_to_hub`] method to upload the model. + +```py +brand_new_bert.push_to_hub("brand_new_llama") +``` + +Refer to the [Sharing](./model_sharing) guide for more information about uploading models to the Hub. + +## Merge your model + +You're finally ready to merge your pull request and officially add the model to Transformers! Make sure all the tests are passing and all comments and feedback have been addressed. + +Congratulations on adding a new model to Transformers! 🥳 + +This is a very significant contribution. Your work makes Transformers more accessible to developers and researchers around the world. You should be proud of your contribution and share your accomplishment with the community! + +## Model addition timeline + +There are four timelines for model additions depending on the model contributor and community demand for an architecture. + +- **day-0 integration**: If you plan on having a Transformers-first release, this is a great option because we can ensure the documentation is clear and optimize your model as much as possible (quantization, FlashAttention, KV-cache, etc.). We can also help you add the model, provide early reviews and make sure it works as expected. + + Reach out to transformers@huggingface.co a few days (preferably weeks) in advance, especially if an architecture is particularly novel, to ensure model integration. We'll work together on a private fork of Transformers until your checkpoint and release is ready. + +- **same week integration**: Models with significant requests/demand are usually added the same week if the model author doesn't reach out. + + Use the [issue tracker](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&projects=&template=new-model-addition.yml) to request a specific model to add. The more activity on the issue, the faster and more likely we'll integrate it. + +- **post-release integration**: Models without popular requests/demand or if we don't have the bandwidth to integrate it are added post-release. + + This is a good opportunity if you're interested in contributing a model to Transformers. Take a look at open issues tagged with ["New model"](https://github.com/huggingface/transformers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+model%22). Feel free to give the most requested models a try first to multiply the impact of your contribution. We'll be there to help you each step of the way! + +- **Hub-first release**: Transformers [remote-code](./models#custom-models) feature allows Transformers-based projects to be shared directly on the Hub. This is a good option if you don't have the bandwidth to add a model directly to Transformers. + + If a model ends up being very popular, then it's very likely that we'll integrate it in Transformers ourselves to enable better support (documentation, maintenance, optimization, etc.) for it. A Hub-first release is the most frictionless way to add a model. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_pipeline.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..60ef43dab585032a01f6260dd2b748af732ee410 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/add_new_pipeline.md @@ -0,0 +1,229 @@ + + +# Adding a new pipeline + +Make [`Pipeline`] your own by subclassing it and implementing a few methods. Share the code with the community on the [Hub](https://hf.co) and register the pipeline with Transformers so that everyone can quickly and easily use it. + +This guide will walk you through the process of adding a new pipeline to Transformers. + +## Design choices + +At a minimum, you only need to provide [`Pipeline`] with an appropriate input for a task. This is also where you should begin when designing your pipeline. + +Decide what input types [`Pipeline`] can accept. It can be strings, raw bytes, dictionaries, and so on. Try to keep the inputs in pure Python where possible because it's more compatible. Next, decide on the output [`Pipeline`] should return. Again, keeping the output in Python is the simplest and best option because it's easier to work with. + +Keeping the inputs and outputs simple, and ideally JSON-serializable, makes it easier for users to run your [`Pipeline`] without needing to learn new object types. It's also common to support many different input types for even greater ease of use. For example, making an audio file acceptable from a filename, URL, or raw bytes gives the user more flexibility in how they provide the audio data. + +## Create a pipeline + +With an input and output decided, you can start implementing [`Pipeline`]. Your pipeline should inherit from the base [`Pipeline`] class and include 4 methods. + +```py +from transformers import Pipeline + +class MyPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + + def preprocess(self, inputs, args=2): + + def _forward(self, model_inputs): + + def postprocess(self, model_outputs): +``` + +1. `preprocess` takes the inputs and transforms them into the appropriate input format for the model. + +```py +def preprocess(self, inputs, maybe_arg=2): + model_input = Tensor(inputs["input_ids"]) + return {"model_input": model_input} +``` + +2. `_forward` shouldn't be called directly. `forward` is the preferred method because it includes safeguards to make sure everything works correctly on the expected device. Anything linked to the model belongs in `_forward` and everything else belongs in either `preprocess` or `postprocess`. + +```py +def _forward(self, model_inputs): + outputs = self.model(**model_inputs) + return outputs +``` + +3. `postprocess` generates the final output from the models output in `_forward`. + +```py +def postprocess(self, model_outputs, top_k=5): + best_class = model_outputs["logits"].softmax(-1) + return best_class +``` + +4. `_sanitize_parameters` lets users pass additional parameters to [`Pipeline`]. This could be during initialization or when [`Pipeline`] is called. `_sanitize_parameters` returns 3 dicts of additional keyword arguments that are passed directly to `preprocess`, `_forward`, and `postprocess`. Don't add anything if a user didn't call the pipeline with extra parameters. This keeps the default arguments in the function definition which is always more natural. + +For example, add a `top_k` parameter in `postprocess` to return the top 5 most likely classes. Then in `_sanitize_parameters`, check if the user passed in `top_k` and add it to `postprocess_kwargs`. + +```py +def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + + postprocess_kwargs = {} + if "top_k" in kwargs: + postprocess_kwargs["top_k"] = kwargs["top_k"] + return preprocess_kwargs, {}, postprocess_kwargs +``` + +Now the pipeline can return the top most likely labels if a user chooses to. + +```py +from transformers import pipeline + +pipeline = pipeline("my-task") +# returns 3 most likely labels +pipeline("This is the best meal I've ever had", top_k=3) +# returns 5 most likely labels by default +pipeline("This is the best meal I've ever had") +``` + +## Register a pipeline + +Register the new task your pipeline supports in the `PIPELINE_REGISTRY`. The registry defines: + +- the machine learning framework the pipeline supports with either `pt_model` or `tf_model` (add both to ensure it works with either frameworks) +- a default model which should come from a specific revision (branch, or commit hash) where the model works as expected with `default` +- the expected input with `type` + +```py +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "new-task", + pipeline_class=MyPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, + default={"pt": ("user/awesome-model", "branch-name")}, + type="text", +) +``` + +## Share your pipeline + +Share your pipeline with the community on the [Hub](https://hf.co) or you can add it directly to Transformers. + +It's faster to upload your pipeline code to the Hub because it doesn't require a review from the Transformers team. Adding the pipeline to Transformers may be slower because it requires a review and you need to add tests to ensure your [`Pipeline`] works. + +### Upload to the Hub + +Add your pipeline code to the Hub in a Python file. + +For example, a custom pipeline for sentence pair classification might look like the following code below. The implementation works for PyTorch and TensorFlow models. + +```py +import numpy as np +from transformers import Pipeline + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} +``` + +Save the code in a file named `pair_classification.py`, and import and register it as shown below. + +```py +from pair_classification import PairClassificationPipeline +from transformers.pipelines import PIPELINE_REGISTRY +from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification + +PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification, + tf_model=TFAutoModelForSequenceClassification, +) +``` + +The [register_pipeline](https://github.com/huggingface/transformers/blob/9feae5fb0164e89d4998e5776897c16f7330d3df/src/transformers/pipelines/base.py#L1387) function registers the pipeline details (task type, pipeline class, supported backends) to a models `config.json` file. + +```json + "custom_pipelines": { + "pair-classification": { + "impl": "pair_classification.PairClassificationPipeline", + "pt": [ + "AutoModelForSequenceClassification" + ], + "tf": [ + "TFAutoModelForSequenceClassification" + ], + } + }, +``` + +Call [`~Pipeline.push_to_hub`] to push the pipeline to the Hub. The Python file containing the code is copied to the Hub, and the pipelines model and tokenizer are also saved and pushed to the Hub. Your pipeline should now be available on the Hub under your namespace. + +```py +from transformers import pipeline + +pipeline = pipeline(task="pair-classification", model="sgugger/finetuned-bert-mrpc") +pipeline.push_to_hub("pair-classification-pipeline") +``` + +To use the pipeline, add `trust_remote_code=True` when loading the pipeline. + +```py +from transformers import pipeline + +pipeline = pipeline(task="pair-classification", trust_remote_code=True) +``` + +### Add to Transformers + +Adding a custom pipeline to Transformers requires adding tests to make sure everything works as expected, and requesting a review from the Transformers team. + +Add your pipeline code as a new module to the [pipelines](https://github.com/huggingface/transformers/tree/main/src/transformers/pipelines) submodule, and add it to the list of tasks defined in [pipelines/__init__.py](https://github.com/huggingface/transformers/blob/main/src/transformers/pipelines/__init__.py). + +Next, add a new test for the pipeline in [transformers/tests/pipelines](https://github.com/huggingface/transformers/tree/main/tests/pipelines). You can look at the other tests for examples of how to test your pipeline. + +The [run_pipeline_test](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L186) function should be very generic and run on the models defined in [model_mapping](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L48) and [tf_model_mapping](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L49). This is important for testing future compatibility with new models. + +You'll also notice `ANY` is used throughout the [run_pipeline_test](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L186) function. The models are random, so you can't check the actual values. Using `ANY` allows the test to match the output of the pipeline type instead. + +Finally, you should also implement the following 4 tests. + +1. [test_small_model_pt](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L59) and [test_small_model_tf](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_text_classification.py#L150), use a small model for these pipelines to make sure they return the correct outputs. The results don't have to make sense. Each pipeline should return the same result. +1. [test_large_model_pt](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_zero_shot_image_classification.py#L187) nad [test_large_model_tf](https://github.com/huggingface/transformers/blob/db70426854fe7850f2c5834d633aff637f14772e/tests/pipelines/test_pipelines_zero_shot_image_classification.py#L220), use a realistic model for these pipelines to make sure they return meaningful results. These tests are slow and should be marked as slow. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/agents.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/agents.md new file mode 100644 index 0000000000000000000000000000000000000000..bd24d8ce30cc7e0699aae68e88498f0b834baa8f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/agents.md @@ -0,0 +1,297 @@ + + +> [!WARNING] +> Agents and tools are being spun out into the standalone [smolagents](https://huggingface.co/docs/smolagents/index) library. These docs will be deprecated in the future! + +# Agents + +[[open-in-colab]] + +An agent is a system where a large language model (LLM) can execute more complex tasks through *planning* and using *tools*. + +- Planning helps a LLM reason its way through a task by breaking it down into smaller subtasks. For example, [`CodeAgent`] plans a series of actions to take and then generates Python code to execute all the actions at once. + + Another planning method is by self-reflection and refinement of its previous actions to improve its performance. The [`ReactJsonAgent`] is an example of this type of planning, and it's based on the [ReAct](https://hf.co/papers/2210.03629) framework. This agent plans and executes actions one at a time based on the feedback it receives from each action. + +- Tools give a LLM access to external functions or APIs that it can use to help it complete a task. For example, [gradio-tools](https://github.com/freddyaboulton/gradio-tools) gives a LLM access to any of the [Gradio](https://www.gradio.app/) apps available on Hugging Face [Spaces](https://hf.co/spaces). These apps can be used for a wide range of tasks such as image generation, video generation, audio transcription, and more. + +To use agents in Transformers, make sure you have the extra `agents` dependencies installed. + +```bash +!pip install transformers[agents] +``` + +Create an agent instance (refer to the [Agents](./main_classes/agent#agents) API for supported agents in Transformers) and a list of tools available for it to use, then [`~ReactAgent.run`] the agent on your task. The example below demonstrates how a ReAct agent reasons through a task. + +```py +from transformers import ReactCodeAgent + +agent = ReactCodeAgent(tools=[]) +agent.run( + "How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?", +) +``` + +```bash +======== New task ======== +How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need? +==== Agent is executing the code below: +bert_layers = 12 # BERT base encoder has 12 layers +attention_layers = 6 # Encoder in Attention is All You Need has 6 layers +layer_diff = bert_layers - attention_layers +print("The difference in layers between BERT base encoder and Attention is All You Need is", layer_diff) +==== +Print outputs: +The difference in layers between BERT base encoder and Attention is All You Need is 6 + +==== Agent is executing the code below: +final_answer("BERT base encoder has {} more layers than the encoder from Attention is All You Need.".format(layer_diff)) +==== +Print outputs: + +>>> Final answer: +BERT base encoder has 6 more layers than the encoder from Attention is All You Need. +``` + +This guide will walk you through in more detail how to initialize an agent. + +## LLM + +An agent uses a LLM to plan and execute a task; it is the engine that powers the agent. To choose and build your own LLM engine, you need a method that: + +1. the input uses the [chat template](./chat_templating) format, `List[Dict[str, str]]`, and it returns a string +2. the LLM stops generating outputs when it encounters the sequences in `stop_sequences` + +```py +def llm_engine(messages, stop_sequences=["Task"]) -> str: + response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000) + answer = response.choices[0].message.content + return answer +``` + +Next, initialize an engine to load a model. To run an agent locally, create a [`TransformersEngine`] to load a preinitialized [`Pipeline`]. + +However, you could also leverage Hugging Face's powerful inference infrastructure, [Inference API](https://hf.co/docs/api-inference/index) or [Inference Endpoints](https://hf.co/docs/inference-endpoints/index), to run your model. This is useful for loading larger models that are typically required for agentic behavior. In this case, load the [`HfApiEngine`] to run the agent. + +The agent requires a list of tools it can use to complete a task. If you aren't using any additional tools, pass an empty list. The default tools provided by Transformers are loaded automatically, but you can optionally set `add_base_tools=True` to explicitly enable them. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TransformersEngine, CodeAgent + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct").to("cuda") +pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer) +llm_engine = TransformersEngine(pipeline) +agent = CodeAgent(tools=[], llm_engine=llm_engine) +agent.run( + "What causes bread to rise?", +) +``` + + + + +```py +from transformers import CodeAgent, HfApiEngine + +llm_engine = HfApiEngine(model="meta-llama/Meta-Llama-3-70B-Instruct") +agent = CodeAgent(tools=[], llm_engine=llm_engine) +agent.run( + "Could you translate this sentence from French, say it out loud and return the audio.", + sentence="Où est la boulangerie la plus proche?", +) +``` + + + + +The agent supports [constrained generation](https://hf.co/docs/text-generation-inference/conceptual/guidance) for generating outputs according to a specific structure with the `grammar` parameter. The `grammar` parameter should be specified in the `llm_engine` method or you can set it when initializing an agent. + +Lastly, an agent accepts additional inputs such as text and audio. In the [`HfApiEngine`] example above, the agent accepted a sentence to translate. But you could also pass a path to a local or remote file for the agent to access. The example below demonstrates how to pass a path to an audio file. + +```py +from transformers import ReactCodeAgent + +agent = ReactCodeAgent(tools=[], llm_engine=llm_engine) +agent.run("Why doesn't he know many people in New York?", audio="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3") +``` + +## System prompt + +A system prompt describes how an agent should behave, a description of the available tools, and the expected output format. + +Tools are defined by the `<>` token which is dynamically replaced during runtime with the actual tool. The tool description is derived from the tool name, description, inputs, output type, and a Jinja2 template. Refer to the [Tools](./tools) guide for more information about how to describe tools. + +The example below is the system prompt for [`ReactCodeAgent`]. + +```py +You will be given a task to solve as best you can. +You have access to the following tools: +<> + +To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences. + +At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use. +Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '/End code' sequence. +During each intermediate step, you can use 'print()' to save whatever important information you will then need. +These print outputs will then be available in the 'Observation:' field, for using this information as input for the next step. + +In the end you have to return a final answer using the `final_answer` tool. + +Here are a few examples using notional tools: +--- +{examples} + +Above example were using notional tools that might not exist for you. You only have access to those tools: +<> +You also can perform computations in the python code you generate. + +Always provide a 'Thought:' and a 'Code:\n```py' sequence ending with '```' sequence. You MUST provide at least the 'Code:' sequence to move forward. + +Remember to not perform too many operations in a single code block! You should split the task into intermediate code blocks. +Print results at the end of each step to save the intermediate results. Then use final_answer() to return the final result. + +Remember to make sure that variables you use are all defined. + +Now Begin! +``` + +The system prompt can be tailored to the intended task. For example, you can add a better explanation of the output format or you can overwrite the system prompt template entirely with your own custom system prompt as shown below. + +> [!WARNING] +> If you're writing a custom system prompt, make sure to include `<>` in the template so the agent is aware of the available tools. + +```py +from transformers import ReactJsonAgent +from transformers.agents import PythonInterpreterTool + +agent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt="{your_custom_prompt}") +``` + +## Code execution + +For safety, only the tools you provide (and the default Transformers tools) and the `print` function are executed. The interpreter doesn't allow importing modules that aren't on a safe list. + +To import modules that aren't on the list, add them as a list to the `additional_authorized_imports` parameter when initializing an agent. + +```py +from transformers import ReactCodeAgent + +agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4']) +agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?") +``` + +Code execution stops if a tool isn't on the safe list, it isn't authorized, or if the code generated by the agent returns a Python error. + +> [!WARNING] +> A LLM can generate any arbitrary code that can be executed, so don't add any unsafe imports! + +## Multi-agent + +[Multi-agent](https://hf.co/papers/2308.08155) refers to multiple agents working together to solve a task. Performance is typically better because each agent is specialized for a particular subtask. + +Multi-agents are created through a [`ManagedAgent`] class, where a *manager agent* oversees how other agents work together. The manager agent requires an agent and their name and description. These are added to the manager agents system prompt which lets it know how to call and use them. + +The multi-agent example below creates a web search agent that is managed by another [`ReactCodeAgent`]. + +```py +from transformers.agents import ReactCodeAgent, HfApiEngine, DuckDuckGoSearchTool, ManagedAgent + +llm_engine = HfApiEngine() +web_agent = ReactCodeAgent(tools=[DuckDuckGoSearchTool()], llm_engine=llm_engine) +managed_web_agent = ManagedAgent( + agent=web_agent, + name="web_search", + description="Runs web searches for you. Give it your query as an argument." +) +manager_agent = ReactCodeAgent( + tools=[], llm_engine=llm_engine, managed_agents=[managed_web_agent] +) +manager_agent.run("Who is the CEO of Hugging Face?") +``` + +## Gradio integration + +[Gradio](https://www.gradio.app/) is a library for quickly creating and sharing machine learning apps. The [gradio.Chatbot](https://www.gradio.app/docs/gradio/chatbot) supports chatting with a Transformers agent with the [`stream_to_gradio`] function. + +Load a tool and LLM with an agent, and then create a Gradio app. The key is to use [`stream_to_gradio`] to stream the agents messages and display how it's reasoning through a task. + +```py +import gradio as gr +from transformers import ( + load_tool, + ReactCodeAgent, + HfApiEngine, + stream_to_gradio, +) + +# Import tool from Hub +image_generation_tool = load_tool("m-ric/text-to-image") +llm_engine = HfApiEngine("meta-llama/Meta-Llama-3-70B-Instruct") + +# Initialize the agent with the image generation tool +agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine) + +def interact_with_agent(task): + messages = [] + messages.append(gr.ChatMessage(role="user", content=task)) + yield messages + for msg in stream_to_gradio(agent, task): + messages.append(msg) + yield messages + [ + gr.ChatMessage(role="assistant", content="⏳ Task not finished yet!") + ] + yield messages + +with gr.Blocks() as demo: + text_input = gr.Textbox(lines=1, label="Chat Message", value="Make me a picture of the Statue of Liberty.") + submit = gr.Button("Run illustrator agent!") + chatbot = gr.Chatbot( + label="Agent", + type="messages", + avatar_images=( + None, + "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png", + ), + ) + submit.click(interact_with_agent, [text_input], [chatbot]) + +if __name__ == "__main__": + demo.launch() +``` + +## Troubleshoot + +For a better idea of what is happening when you call an agent, it is always a good idea to check the system prompt template first. + +```py +print(agent.system_prompt_template) +``` + +If the agent is behaving unexpectedly, remember to explain the task you want to perform as clearly as possible. Every [`~Agent.run`] is different and minor variations in your system prompt may yield completely different results. + +To find out what happened after a run, check the following agent attributes. + +- `agent.logs` stores the finegrained agent logs. At every step of the agents run, everything is stored in a dictionary and appended to `agent.logs`. +- `agent.write_inner_memory_from_logs` only stores a high-level overview of the agents run. For example, at each step, it stores the LLM output as a message and the tool call output as a separate message. Not every detail from a step is transcripted by `write_inner_memory_from_logs`. + +## Resources + +Learn more about ReAct agents in the [Open-source LLMs as LangChain Agents](https://hf.co/blog/open-source-llms-as-agents) blog post. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/attention.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/attention.md new file mode 100644 index 0000000000000000000000000000000000000000..02e4db58f5bea0c144f51e29eaf5cab77789ce11 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/attention.md @@ -0,0 +1,61 @@ + + +# Attention mechanisms + +Most transformer models use full attention in the sense that the attention matrix is square. It can be a big +computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and +use a sparse version of the attention matrix to speed up training. + +## LSH attention + +[Reformer](model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax +dimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only +the keys k in K that are close to q. A hash function is used to determine if q and k are close. The attention mask is +modified to mask the current token (except at the first position), because it will give a query and a key equal (so +very similar to each other). Since the hash can be a bit random, several hash functions are used in practice +(determined by a n_rounds parameter) and then are averaged together. + +## Local attention + +[Longformer](model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the +left and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small +window, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a +representation of the whole sentence. + +Some preselected input tokens are also given global attention: for those few tokens, the attention matrix can access +all tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in +their local window). This is shown in Figure 2d of the paper, see below for a sample attention mask: + +
+ +
+ +Using those attention matrices with less parameters then allows the model to have inputs having a bigger sequence +length. + +## Other tricks + +### Axial positional encodings + +[Reformer](model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding +E is a matrix of size \\(l\\) by \\(d\\), \\(l\\) being the sequence length and \\(d\\) the dimension of the +hidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate +that, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with +dimensions \\(l_{1} \times d_{1}\\) and \\(l_{2} \times d_{2}\\), such that \\(l_{1} \times l_{2} = l\\) and +\\(d_{1} + d_{2} = d\\) (with the product for the lengths, this ends up being way smaller). The embedding for time +step \\(j\\) in E is obtained by concatenating the embeddings for timestep \\(j \% l1\\) in E1 and \\(j // l1\\) +in E2. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/backbones.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/backbones.md new file mode 100644 index 0000000000000000000000000000000000000000..792b0b0d38f12f11c0f2e6519d90ce56fc704f8a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/backbones.md @@ -0,0 +1,155 @@ + + +# Backbones + +Higher-level computer visions tasks, such as object detection or image segmentation, use several models together to generate a prediction. A separate model is used for the *backbone*, neck, and head. The backbone extracts useful features from an input image into a feature map, the neck combines and processes the feature maps, and the head uses them to make a prediction. + +
+ +
+ +Load a backbone with [`~PretrainedConfig.from_pretrained`] and use the `out_indices` parameter to determine which layer, given by the index, to extract a feature map from. + +```py +from transformers import AutoBackbone + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +``` + +This guide describes the backbone class, backbones from the [timm](https://hf.co/docs/timm/index) library, and how to extract features with them. + +## Backbone classes + +There are two backbone classes. + +- [`~transformers.utils.BackboneMixin`] allows you to load a backbone and includes functions for extracting the feature maps and indices. +- [`~transformers.utils.BackboneConfigMixin`] allows you to set the feature map and indices of a backbone configuration. + +Refer to the [Backbone](./main_classes/backbones) API documentation to check which models support a backbone. + +There are two ways to load a Transformers backbone, [`AutoBackbone`] and a model-specific backbone class. + + + + +The [AutoClass](./model_doc/auto) API automatically loads a pretrained vision model with [`~PretrainedConfig.from_pretrained`] as a backbone if it's supported. + +Set the `out_indices` parameter to the layer you'd like to get the feature map from. If you know the name of the layer, you could also use `out_features`. These parameters can be used interchangeably, but if you use both, make sure they refer to the same layer. + +When `out_indices` or `out_features` isn't used, the backbone returns the feature map from the last layer. The example code below uses `out_indices=(1,)` to get the feature map from the first layer. + +
+ +
+ +```py +from transformers import AutoImageProcessor, AutoBackbone + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +``` + +
+ + +When you know a model supports a backbone, you can load the backbone and neck directly into the models configuration. Pass the configuration to the model to initialize it for a task. + +The example below loads a [ResNet](./model_doc/resnet) backbone and neck for use in a [MaskFormer](./model_doc/maskformer) instance segmentation head. + +Set `backbone` to a pretrained model and `use_pretrained_backbone=True` to use pretrained weights instead of randomly initialized weights. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="microsoft/resnet-50", use_pretrained_backbone=True) +model = MaskFormerForInstanceSegmentation(config) +``` + +Another option is to separately load the backbone configuration and then pass it to `backbone_config` in the model configuration. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig + +# instantiate backbone configuration +backbone_config = ResNetConfig() +# load backbone in model +config = MaskFormerConfig(backbone_config=backbone_config) +# attach backbone to model head +model = MaskFormerForInstanceSegmentation(config) +``` + + +
+ +## timm backbones + +[timm](https://hf.co/docs/timm/index) is a collection of vision models for training and inference. Transformers supports timm models as backbones with the [`TimmBackbone`] and [`TimmBackboneConfig`] classes. + +Set `use_timm_backbone=True` to load pretrained timm weights, and `use_pretrained_backbone` to use pretrained or randomly initialized weights. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone="resnet50", use_timm_backbone=True, use_pretrained_backbone=True) +model = MaskFormerForInstanceSegmentation(config) +``` + +You could also explicitly call the [`TimmBackboneConfig`] class to load and create a pretrained timm backbone. + +```py +from transformers import TimmBackboneConfig + +backbone_config = TimmBackboneConfig("resnet50", use_pretrained_backbone=True) +``` + +Pass the backbone configuration to the model configuration and instantiate the model head, [`MaskFormerForInstanceSegmentation`], with the backbone. + +```py +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation + +config = MaskFormerConfig(backbone_config=backbone_config) +model = MaskFormerForInstanceSegmentation(config) +``` + +## Feature extraction + +The backbone is used to extract image features. Pass an image through the backbone to get the feature maps. + +Load and preprocess an image and pass it to the backbone. The example below extracts the feature maps from the first layer. + +```py +from transformers import AutoImageProcessor, AutoBackbone +import torch +from PIL import Image +import requests + +model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,)) +processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224") + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(image, return_tensors="pt") +outputs = model(**inputs) +``` + +The features are stored and accessed from the outputs `feature_maps` attribute. + +```py +feature_maps = outputs.feature_maps +list(feature_maps[0].shape) +[1, 96, 56, 56] +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/cache_explanation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/cache_explanation.md new file mode 100644 index 0000000000000000000000000000000000000000..b13601459d899a9374ac457f0deeed0fd5a2f7f9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/cache_explanation.md @@ -0,0 +1,96 @@ + + +# Caching + +Imagine you’re having a conversation with someone, and instead of remembering what they previously said, they have to start from scratch every time you respond. This would be slow and inefficient, right? + +You can extend this analogy to transformer models. Autoregressive model generation can be slow because it makes a prediction one token at a time. Each new prediction is dependent on all the previous context. + +To predict the 1000th token, the model requires information from the previous 999 tokens. The information is represented as matrix multiplications across the token representations. + +To predict the 1001th token, you need the same information from the previous 999 tokens in addition to any information from the 1000th token. This is a lot of matrix multiplications a model has to compute over and over for each token! + +A key-value (KV) cache eliminates this inefficiency by storing kv pairs derived from the attention layers of previously processed tokens. The stored kv pairs are retrieved from the cache and reused for subsequent tokens, avoiding the need to recompute. + +> [!WARNING] +> Caching should only be used for **inference**. It may cause unexpected errors if it's enabled during training. + +## Cache class + +When you use Transformers' [`Cache`] class, the self-attention module performs several critical steps to integrate past and present information. + +1. The attention module concatenates current kv pairs with past kv pairs stored in the cache. This creates attentions weights with the shape `(new_tokens_length, past_kv_length + new_tokens_length)`. The current and past kv pairs are essentially combined to compute the attention scores, ensuring a model is aware of previous context and the current input. + +2. When the `forward` method is called iteratively, it's crucial that the attention mask shape matches the combined length of the past and current kv pairs. The attention mask should have the shape `(batch_size, past_kv_length + new_tokens_length)`. This is typically handled internally in [`~GenerationMixin.generate`], but if you want to implement your own generation loop with [`Cache`], keep this in mind! The attention mask should hold the past and current token values. + +3. It is also important to be aware of the `cache_position`. This is important if you want to reuse a prefilled [`Cache`] with the `forward` method because you have to pass a valid `cache_position` value. This indicates the input positions in a sequence. `cache_position` is unaffected by padding, and it always adds one more position for each token. For example, if a kv cache contains 10 tokens - regardless of pad tokens - the cache position for the next token should be `torch.tensor([10])`. + +The example below demonstrates how to create a generation loop with [`DynamicCache`]. As discussed, the attention mask is a concatenation of past and current token values and `1` is added to the cache position for the next token. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="cuda:0") +tokenizer = AutoTokenizer.from_pretrained(model_id) + +past_key_values = DynamicCache() +messages = [{"role": "user", "content": "Hello, what's your name."}] +inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda:0") + +generated_ids = inputs.input_ids +cache_position = torch.arange(inputs.input_ids.shape[1], dtype=torch.int64, device="cuda:0") +max_new_tokens = 10 + +for _ in range(max_new_tokens): + outputs = model(**inputs, cache_position=cache_position, past_key_values=past_key_values, use_cache=True) + # Greedily sample one next token + next_token_ids = outputs.logits[:, -1:].argmax(-1) + generated_ids = torch.cat([generated_ids, next_token_ids], dim=-1) + # Prepare inputs for the next generation step by leaaving unprocessed tokens, in our case we have only one new token + # and expanding attn mask for the new token, as explained above + attention_mask = inputs["attention_mask"] + attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1) + inputs = {"input_ids": next_token_ids, "attention_mask": attention_mask} + cache_position = cache_position[-1:] + 1 # add one more position for the next token + +print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]) +"[INST] Hello, what's your name. [/INST] Hello! My name is LLaMA," +``` + +## Legacy cache format + +Before the [`Cache`] class, the cache used to be stored as a tuple of tuples of tensors. This format has is dynamic because it grows as text is generated, similar to [`DynamicCache`]. + +If your project depends on this legacy format, you can convert between [`DynamicCache`] and a tuple of tuples as shown below with the [`~DynamicCache.from_legacy_cache`] and [`DynamicCache.to_legacy_cache`] functions. This is helpful if you have custom logic for manipulating a cache in a specific format. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +# `return_dict_in_generate=True` is required to return the cache and `return_legacy_cache` forces the returned cache +# in the the legacy format +generation_outputs = model.generate(**inputs, return_dict_in_generate=True, return_legacy_cache=True, max_new_tokens=5) + +cache = DynamicCache.from_legacy_cache(generation_outputs.past_key_values) +legacy_format_cache = cache.to_legacy_cache() +``` \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_extras.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_extras.md new file mode 100644 index 0000000000000000000000000000000000000000..863b0f06f2e90793d1a30e103ebf44d1d0855f3f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_extras.md @@ -0,0 +1,299 @@ + + +# Tools and RAG + +The [`~PreTrainedTokenizerBase.apply_chat_template`] method supports virtually any additional argument types - strings, lists, dicts - besides the chat message. This makes it possible to use chat templates for many use cases. + +This guide will demonstrate how to use chat templates with tools and retrieval-augmented generation (RAG). + +## Tools + +Tools are functions a large language model (LLM) can call to perform specific tasks. It is a powerful way to extend the capabilities of conversational agents with real-time information, computational tools, or access to large databases. + +Follow the rules below when creating a tool. + +1. The function should have a descriptive name. +2. The function arguments must have a type hint in the function header (don't include in the `Args` block). +3. The function must have a [Google-style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) docstring. +4. The function can have a return type and `Returns` block, but these are optional because most tool use models ignore them. + +An example tool to get temperature and wind speed is shown below. + +```py +def get_current_temperature(location: str, unit: str) -> float: + """ + Get the current temperature at a location. + + Args: + location: The location to get the temperature for, in the format "City, Country" + unit: The unit to return the temperature in. (choices: ["celsius", "fahrenheit"]) + Returns: + The current temperature at the specified location in the specified units, as a float. + """ + return 22. # A real function should probably actually get the temperature! + +def get_current_wind_speed(location: str) -> float: + """ + Get the current wind speed in km/h at a given location. + + Args: + location: The location to get the temperature for, in the format "City, Country" + Returns: + The current wind speed at the given location in km/h, as a float. + """ + return 6. # A real function should probably actually get the wind speed! + +tools = [get_current_temperature, get_current_wind_speed] +``` + +Load a model and tokenizer that supports tool-use like [NousResearch/Hermes-2-Pro-Llama-3-8B](https://hf.co/NousResearch/Hermes-2-Pro-Llama-3-8B), but you can also consider a larger model like [Command-R](./model_doc/cohere) and [Mixtral-8x22B](./model_doc/mixtral) if your hardware can support it. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B") +tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B") +model = AutoModelForCausalLM.from_pretrained( "NousResearch/Hermes-2-Pro-Llama-3-8B", torch_dtype=torch.bfloat16, device_map="auto") +``` + +Create a chat message. + +```py +messages = [ + {"role": "system", "content": "You are a bot that responds to weather queries. You should reply with the unit used in the queried location."}, + {"role": "user", "content": "Hey, what's the temperature in Paris right now?"} +] +``` + +Pass `messages` and a list of tools to [`~PreTrainedTokenizerBase.apply_chat_template`]. Then you can pass the inputs to the model for generation. + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +outputs = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(outputs[0][len(inputs["input_ids"][0]):])) +``` + +```txt + +{"arguments": {"location": "Paris, France", "unit": "celsius"}, "name": "get_current_temperature"} +<|im_end|> +``` + +The chat model called the `get_current_temperature` tool with the correct parameters from the docstring. It inferred France as the location based on Paris, and that it should use Celsius for the units of temperature. + +Now append the `get_current_temperature` function and these arguments to the chat message as `tool_call`. The `tool_call` dictionary should be provided to the `assistant` role instead of the `system` or `user`. + +> [!WARNING] +> The OpenAI API uses a JSON string as its `tool_call` format. This may cause errors or strange model behavior if used in Transformers, which expects a dict. + + + + +```py +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"type": "function", "function": tool_call}]}) +``` + +Allow the assistant to read the function outputs and chat with the user. + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + +```txt +The temperature in Paris, France right now is approximately 12°C (53.6°F).<|im_end|> +``` + + + + +For [Mistral](./model_doc/mistral) and [Mixtral](./model_doc/mixtral) models, you need an additional `tool_call_id`. The `tool_call_id` is 9 randomly generated alphanumeric characters assigned to the `id` key in the `tool_call` dictionary. + +```py +tool_call_id = "9Ae3bDc2F" +tool_call = {"name": "get_current_temperature", "arguments": {"location": "Paris, France", "unit": "celsius"}} +messages.append({"role": "assistant", "tool_calls": [{"type": "function", "id": tool_call_id, "function": tool_call}]}) +``` + +```py +inputs = tokenizer.apply_chat_template(messages, tools=tools, add_generation_prompt=True, return_dict=True, return_tensors="pt") +inputs = {k: v for k, v in inputs.items()} +out = model.generate(**inputs, max_new_tokens=128) +print(tokenizer.decode(out[0][len(inputs["input_ids"][0]):])) +``` + + + + +## Schema + +[`~PreTrainedTokenizerBase.apply_chat_template`] converts functions into a [JSON schema](https://json-schema.org/learn/getting-started-step-by-step) which is passed to the chat template. A LLM never sees the code inside the function. In other words, a LLM doesn't care how the function works technically, it only cares about function **definition** and **arguments**. + +The JSON schema is automatically generated behind the scenes as long as your function follows the [rules](#tools) listed earlier above. But you can use [get_json_schema](https://github.com/huggingface/transformers/blob/14561209291255e51c55260306c7d00c159381a5/src/transformers/utils/chat_template_utils.py#L205) to manually convert a schema for more visibility or debugging. + +```py +from transformers.utils import get_json_schema + +def multiply(a: float, b: float): + """ + A function that multiplies two numbers + + Args: + a: The first number to multiply + b: The second number to multiply + """ + return a * b + +schema = get_json_schema(multiply) +print(schema) +``` + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +You can edit the schema or write one entirely from scratch. This gives you a lot of flexibility to define precise schemas for more complex functions. + +> [!WARNING] +> Try keeping your function signatures simple and the arguments to a minimum. These are easier for a model to understand and use than complex functions for example with nested arguments. + +The example below demonstrates writing a schema manually and then passing it to [`~PreTrainedTokenizerBase.apply_chat_template`]. + +```py +# A simple function that takes no arguments +current_time = { + "type": "function", + "function": { + "name": "current_time", + "description": "Get the current local time as a string.", + "parameters": { + 'type': 'object', + 'properties': {} + } + } +} + +# A more complete function that takes two numerical arguments +multiply = { + 'type': 'function', + 'function': { + 'name': 'multiply', + 'description': 'A function that multiplies two numbers', + 'parameters': { + 'type': 'object', + 'properties': { + 'a': { + 'type': 'number', + 'description': 'The first number to multiply' + }, + 'b': { + 'type': 'number', 'description': 'The second number to multiply' + } + }, + 'required': ['a', 'b'] + } + } +} + +model_input = tokenizer.apply_chat_template( + messages, + tools = [current_time, multiply] +) +``` + +## RAG + +Retrieval-augmented generation (RAG) models enhance a models existing knowledge by allowing it to search documents for additional information before returning a query. For RAG models, add a `documents` parameter to [`~PreTrainedTokenizerBase.apply_chat_template`]. This `documents` parameter should be a list of documents, and each document should be a single dict with `title` and `content` keys. + +> [!TIP] +> The `documents` parameter for RAG isn't widely supported and many models have chat templates that ignore `documents`. Verify if a model supports `documents` by reading its model card or executing `print(tokenizer.chat_template)` to see if the `documents` key is present. [Command-R](https://hf.co/CohereForAI/c4ai-command-r-08-2024) and [Command-R+](https://hf.co/CohereForAI/c4ai-command-r-plus-08-2024) both support `documents` in their RAG chat templates. + +Create a list of documents to pass to the model. + +```py +documents = [ + { + "title": "The Moon: Our Age-Old Foe", + "text": "Man has always dreamed of destroying the moon. In this essay, I shall..." + }, + { + "title": "The Sun: Our Age-Old Friend", + "text": "Although often underappreciated, the sun provides several notable benefits..." + } +] +``` + +Set `chat_template="rag"` in [`~PreTrainedTokenizerBase.apply_chat_template`] and generate a response. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +# Load the model and tokenizer +tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01-4bit") +model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01-4bit", device_map="auto") +device = model.device # Get the device the model is loaded on + +# Define conversation input +conversation = [ + {"role": "user", "content": "What has Man always dreamed of?"} +] + +input_ids = tokenizer.apply_chat_template( + conversation=conversation, + documents=documents, + chat_template="rag", + tokenize=True, + add_generation_prompt=True, + return_tensors="pt").to(device) + +# Generate a response +generated_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +# Decode and print the generated text along with generation prompt +generated_text = tokenizer.decode(generated_tokens[0]) +print(generated_text) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating.md new file mode 100644 index 0000000000000000000000000000000000000000..d11b8fa5b4046298d0f980204994fd79e4dcafc0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating.md @@ -0,0 +1,229 @@ + + +# Templates + +The [chat pipeline](./conversations) guide introduced [`TextGenerationPipeline`] and the concept of a chat prompt or chat template for conversing with a model. Underlying this high-level pipeline is the [`apply_chat_template`] method. A chat template is a part of the tokenizer and it specifies how to convert conversations into a single tokenizable string in the expected model format. + +In the example below, Mistral-7B-Instruct and Zephyr-7B are finetuned from the same base model but they’re trained with different chat formats. Without chat templates, you have to manually write formatting code for each model and even minor errors can hurt performance. Chat templates offer a universal way to format chat inputs to any model. + + + + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") +chat = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] + +tokenizer.apply_chat_template(chat, tokenize=False) +``` +```md +[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST] +``` + + + + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") +chat = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] + +tokenizer.apply_chat_template(chat, tokenize=False) +``` +```md +<|user|>\nHello, how are you?\n<|assistant|>\nI'm doing great. How can I help you today?\n<|user|>\nI'd like to show off how chat templating works!\n +``` + + + + +This guide explores [`apply_chat_template`] and chat templates in more detail. + +## apply_chat_template + +Chats should be structured as a list of dictionaries with `role` and `content` keys. The `role` key specifies the speaker (usually between you and the system), and the `content` key contains your message. For the system, the `content` is a high-level description of how the model should behave and respond when you’re chatting with it. + +Pass your messages to [`apply_chat_template`] to tokenize and format them. You can set [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) to `True` to indicate the start of a message. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta", device_map="auto", torch_dtype=torch.bfloat16) + +messages = [ + {"role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate",}, + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, + ] +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +print(tokenizer.decode(tokenized_chat[0])) +``` +```md +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +``` + +Now pass the tokenized chat to [`~GenerationMixin.generate`] to generate a response. + +```py +outputs = model.generate(tokenized_chat, max_new_tokens=128) +print(tokenizer.decode(outputs[0])) +``` +```md +<|system|> +You are a friendly chatbot who always responds in the style of a pirate +<|user|> +How many helicopters can a human eat in one sitting? +<|assistant|> +Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all. +``` + +### add_generation_prompt +The [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) parameter adds tokens that indicate the start of a response. This ensures the chat model generates a system response instead of continuing a users message. + +Not all models require generation prompts, and some models, like [Llama](./model_doc/llama), don’t have any special tokens before the system response. In this case, [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) has no effect. + +```py +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) +tokenized_chat +``` +```md +<|im_start|>user +Hi there!<|im_end|> +<|im_start|>assistant +Nice to meet you!<|im_end|> +<|im_start|>user +Can I ask a question?<|im_end|> +``` + +### continue_final_message + +The [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) parameter controls whether the final message in the chat should be continued or not instead of starting a new one. It removes end of sequence tokens so that the model continues generation from the final message. + +This is useful for “prefilling” a model response. In the example below, the model generates text that continues the JSON string rather than starting a new message. It can be very useful for improving the accuracy for instruction following when you know how to start its replies. + +```py +chat = [ + {"role": "user", "content": "Can you format the answer in JSON?"}, + {"role": "assistant", "content": '{"name": "'}, +] + +formatted_chat = tokenizer.apply_chat_template(chat, tokenize=True, return_dict=True, continue_final_message=True) +model.generate(**formatted_chat) +``` + +> [!WARNING] +> You shouldn’t use [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) and [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) together. The former adds tokens that start a new message, while the latter removes end of sequence tokens. Using them together returns an error. + +[`TextGenerationPipeline`] sets [add_generation_prompt](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) to `True` by default to start a new message. However, if the final message in the chat has the “assistant” role, it assumes the message is a prefill and switches to `continue_final_message=True`. This is because most models don’t support multiple consecutive assistant messages. To override this behavior, explicitly pass the [continue_final_message](https://huggingface.co/docs/transformers/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) to the pipeline. + +## Multiple templates + +A model may have several different templates for different use cases. For example, a model may have a template for regular chat, tool use, and RAG. + +When there are multiple templates, the chat template is a dictionary. Each key corresponds to the name of a template. [`apply_chat_template`] handles multiple templates based on their name. It looks for a template named `default` in most cases and if it can’t find one, it raises an error. + +For a tool calling template, if a user passes a `tools` parameter and a `tool_use` template exists, the tool calling template is used instead of `default`. + +To access templates with other names, pass the template name to the `chat_template` parameter in [`apply_chat_template`]. For example, if you’re using a RAG template then set `chat_template="rag"`. + +It can be confusing to manage multiple templates though, so we recommend using a single template for all use cases. Use Jinja statements like `if tools is defined` and `{% macro %}` definitions to wrap multiple code paths in a single template. + +## Template selection + +It is important to set a chat template format that matches the template format a model was pretrained on, otherwise performance may suffer. Even if you’re training the model further, performance is best if the chat tokens are kept constant. + +But if you’re training a model from scratch or finetuning a model for chat, you have more options to select a template. For example, [ChatML](https://github.com/openai/openai-python/blob/release-v0.28.0/chatml.md) is a popular format that is flexbile enough to handle many use cases. It even includes support for [generation prompts](#add_generation_prompt), but it doesn’t add beginning-of-string (`BOS`) or end-of-string (`EOS`) tokens. If your model expects `BOS` and `EOS` tokens, set `add_special_tokens=True` and make sure to add them to your template. + +```py +{%- for message in messages %} + {{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }} +{%- endfor %} +``` + +Set the template with the following logic to support [generation prompts](#add_generation_prompt). The template wraps each message with `<|im_start|>` and `<|im_end|>` tokens and writes the role as a string. This allows you to easily customize the roles you want to train with. + +```py +tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +``` + +The `user`, `system` and `assistant` roles are standard roles in chat templates. We recommend using these roles when it makes sense, especially if you’re using your model with the [`TextGenerationPipeline`]. + +```py +<|im_start|>system +You are a helpful chatbot that will do its best not to say anything so stupid that people tweet about it.<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant +I'm doing great!<|im_end|> +``` + +## Model training + +Training a model with a chat template is a good way to ensure a chat template matches the tokens a model is trained on. Apply the chat template as a preprocessing step to your dataset. Set `add_generation_prompt=False` because the additional tokens to prompt an assistant response aren’t helpful during training. + +An example of preprocessing a dataset with a chat template is shown below. + +```py +from transformers import AutoTokenizer +from datasets import Dataset + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + +chat1 = [ + {"role": "user", "content": "Which is bigger, the moon or the sun?"}, + {"role": "assistant", "content": "The sun."} +] +chat2 = [ + {"role": "user", "content": "Which is bigger, a virus or a bacterium?"}, + {"role": "assistant", "content": "A bacterium."} +] + +dataset = Dataset.from_dict({"chat": [chat1, chat2]}) +dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)}) +print(dataset['formatted_chat'][0]) +``` +```md +<|user|> +Which is bigger, the moon or the sun? +<|assistant|> +The sun. +``` + +After this step, you can continue following the [training recipe](./tasks/language_modeling) for causal language models using the `formatted_chat` column. + +Some tokenizers add special `` and `` tokens. Chat templates should already include all the necessary special tokens, and adding additional special tokens is often incorrect or duplicated, hurting model performance. When you format text with `apply_chat_template(tokenize=False)`, make sure you set `add_special_tokens=False` as well to avoid duplicating them. + +```py +apply_chat_template(messages, tokenize=False, add_special_tokens=False) +``` + +This isn’t an issue if `apply_chat_template(tokenize=True)`. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_multimodal.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_multimodal.md new file mode 100644 index 0000000000000000000000000000000000000000..07ee8c828e4125808dfe53752a987c80f0a080f4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_multimodal.md @@ -0,0 +1,272 @@ + + +# Multimodal templates + +Multimodal model chat templates expect a similar [template](./chat_templating) as text-only models. It needs `messages` that includes a dictionary of the `role` and `content`. + +Multimodal templates are included in the [Processor](./processors) class and requires an additional `type` key for specifying whether the included content is an image, video, or text. + +This guide will show you how to format chat templates for multimodal models as well as some best practices for configuring the template + +## ImageTextToTextPipeline + +[`ImageTextToTextPipeline`] is a high-level image and text generation class with a “chat mode”. Chat mode is enabled when a conversational model is detected and the chat prompt is [properly formatted](./llm_tutorial#wrong-prompt-format). + +Start by building a chat history with the following two roles. + +- `system` describes how the model should behave and respond when you’re chatting with it. This role isn’t supported by all chat models. +- `user` is where you enter your first message to the model. + +```py +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What are these?"}, + ], + }, +] +``` + +Create a [`ImageTextToTextPipeline`] and pass the chat to it. For large models, setting [device_map=“auto”](./models#big-model-inference) helps load the model quicker and automatically places it on the fastest device available. Changing the data type to [torch.bfloat16](./models#model-data-type) also helps save memory. + +> [!TIP] +> The [`ImageTextToTextPipeline`] accepts chats in the OpenAI format to make inference easier and more accessible. + +```python +import torch +from transformers import pipeline + +pipeline = pipeline("image-text-to-text", model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf", device="cuda", torch_dtype=torch.float16) +pipeline(text=messages, max_new_tokens=50, return_full_text=False) +[{'input_text': [{'role': 'system', + 'content': [{'type': 'text', + 'text': 'You are a friendly chatbot who always responds in the style of a pirate'}]}, + {'role': 'user', + 'content': [{'type': 'image', + 'url': 'http://images.cocodataset.org/val2017/000000039769.jpg'}, + {'type': 'text', 'text': 'What are these?'}]}], + 'generated_text': 'The image shows two cats lying on a pink surface, which appears to be a cushion or a soft blanket. The cat on the left has a striped coat, typical of tabby cats, and is lying on its side with its head resting on the'}] +``` + +## Image inputs + +For multimodal models that accept images like [LLaVA](./model_doc/llava), include the following in `content` as shown below. + +- The content `"type"` can be an `"image"` or `"text"`. +- For images, it can be a link to the image (`"url"`), a file path (`"path"`), or `"base64"`. Images are automatically loaded, processed, and prepared into pixel values as inputs to the model. + +```python +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf") +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf") + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What are these?"}, + ], + }, +] +``` + +Pass `messages` to [`~ProcessorMixin.apply_chat_template`] to tokenize the input content and return the `input_ids` and `pixel_values`. + +```py +processed_chat = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") +print(processed_chat.keys()) +``` + +These inputs are now ready to be used in [`~GenerationMixin.generate`]. + +## Video inputs + +Some vision models also support video inputs. The message format is very similar to the format for [image inputs](#image-inputs). + +- The content `"type"` should be `"video"` to indicate the the content is a video. +- For videos, it can be a link to the video (`"url"`) or it could be a file path (`"path"`). Videos loaded from a URL can only be decoded with [PyAV](https://pyav.basswood-io.com/docs/stable/) or [Decord](https://github.com/dmlc/decord). + +> [!WARNING] +> Loading a video from `"url"` is only supported by the PyAV or Decord backends. + +```python +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf" +model = LlavaOnevisionForConditionalGeneration.from_pretrained(model_id) +processor = AutoProcessor.from_pretrained(model_id) + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "url": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4"}, + {"type": "text", "text": "What do you see in this video?"}, + ], + }, +] +``` + +Pass `messages` to [`~ProcessorMixin.apply_chat_template`] to tokenize the input content. There are a few extra parameters to include in [`~ProcessorMixin.apply_chat_template`] that controls the sampling process. + +The `video_load_backend` parameter refers to a specific framework to load a video. It supports [PyAV](https://pyav.basswood-io.com/docs/stable/), [Decord](https://github.com/dmlc/decord), [OpenCV](https://github.com/opencv/opencv), and [torchvision](https://pytorch.org/vision/stable/index.html). + +The examples below uses Decord as the backend because it is a bit faster than PyAV. + + + + +The `num_frames` parameter controls how many frames to uniformly sample from the video. Each checkpoint has a maximum frame count it was pretrained with and exceeding this count can significantly lower generation quality. It's important to choose a frame count that fits both the model capacity and your hardware resources. If `num_frames` isn't specified, the entire video is loaded without any frame sampling. + + +```python +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + num_frames=32, + video_load_backend="decord", +) +print(processed_chat.keys()) +``` + +These inputs are now ready to be used in [`~GenerationMixin.generate`]. + + + + +For longer videos, it may be better to sample more frames for better representation with the `video_fps` parameter. This determines how many frames per second to extract. As an example, if a video is 10 seconds long and `video_fps=2`, then the model samples 20 frames. In other words, 2 frames are uniformly sampled every 10 seconds. + +```py +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + video_fps=32, + video_load_backend="decord", +) +print(processed_chat.keys()) +``` + + + + +Some models don't sample frames *uniformly* and require more complex logic to determine which frames to use. For example, the model may have an *adaptive frame selection* or if the model prioritizes *key moments* in a video rather than evenly spaced frames. + +If a model has a different sampling strategy, you can write a function that customizes frame selection. The function should include the following requirements. + +- Use the `sample_indices_fn` parameter to pass a callable function for sampling. +- If provided, this function *overrides* the standard `num_frames` and `fps` parameters. +- The function receives all the parameters passed to `load_video` and must return valid frame indices to sample from. + +An example function is shown below. This gives you full control over frame selection, making the model more adaptable to different video scenarios. + +```py +def sample_indices_fn(metadata, **kwargs): + # samples only the first and the second frame + return [0, 1] + +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + sample_indices_fn=sample_indices_fn, + video_load_backend="decord", +) +print(processed_chat.keys()) +``` + + + + +Videos may also exist as a set of sampled frames stored as images rather than the full video file. + +In this case, pass a list of image file paths and the processor automatically concatenates them into a video. Make sure all images are the same size since they are assumed to be from the same video. + +```py +frames_paths = ["/path/to/frame0.png", "/path/to/frame5.png", "/path/to/frame10.png"] +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}], + }, + { + "role": "user", + "content": [ + {"type": "video", "path": frames_paths}, + {"type": "text", "text": "What do you see in this video?"}, + ], + }, +] + +processed_chat = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, +) +print(processed_chat.keys()) +``` + + + + +## Template configuration + +You can create a custom chat template with [Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) and set it with [`~ProcessorMixin.apply_chat_template`]. Refer to the [Template writing](./chat_templating_writing) guide for more details. + +For example, to enable a template to handle a *list of content* from multiple modalities while still supporting plain strings for text-only inference, specify how to handle the `content['type']` if it is an image or text as shown below in the Llama 3.2 Vision Instruct [template](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct/blob/main/chat_template.json). + +```jinja +{% for message in messages %} +{% if loop.index0 == 0 %}{{ bos_token }}{% endif %} +{{ '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' }} +{% if message['content'] is string %} +{{ message['content'] }} +{% else %} +{% for content in message['content'] %} +{% if content['type'] == 'image' %} +{{ '<|image|>' }} +{% elif content['type'] == 'text' %} +{{ content['text'] }} +{% endif %} +{% endfor %} +{% endif %} +{{ '<|eot_id|>' }} +{% endfor %} +{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}{% endif %} +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_writing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_writing.md new file mode 100644 index 0000000000000000000000000000000000000000..fbcec9f71c01972ae9a451abf1c96cde649e32f9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/chat_templating_writing.md @@ -0,0 +1,251 @@ + + +# Template writing + +A chat template is a [Jinja](https://jinja.palletsprojects.com/en/3.1.x/templates/) template stored in the tokenizers [chat_template](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizer.chat_template) attribute. Jinja is a templating language that allows you to write Python-like code and syntax. A chat template performs the following three roles. + +1. Print the role enclosed in `<|` and `|>` (`<|user|>`, `<|assistant|>`, etc.). +2. Print the message followed by an end-of-sequence (`EOS`) token. +3. Print the assistant token if [add_generation_prompt=True](./chat_templating#add_generation_prompt) so the model generates an assistant response. + +An example template is shown below. + +```jinja +{%- for message in messages %} + {{- '<|' + message['role'] + |>\n' }} + {{- message['content'] + eos_token }} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|assistant|>\n' }} +{%- endif %} +``` + +The template can be customized to handle more complex use cases. This guide will show you how to add and edit templates and includes template writing tips. + +## Create a template + +Create a template by writing a Jinja template and then setting it as the chat template in the tokenizer. For example, the template below adds `[ASST]` and `[/ASST]` tags to the assistant messages. + +```jinja +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {{- bos_token + '[INST] ' + message['content'].strip() + ' [/INST]' }} + {%- elif message['role'] == 'system' %} + {{- '<>\\n' + message['content'].strip() + '\\n<>\\n\\n' }} + {%- elif message['role'] == 'assistant' %} + {{- '[ASST] ' + message['content'] + ' [/ASST]' + eos_token }} + {%- endif %} +{%- endfor %} +``` + +Set the template in the tokenizer, and the next time you use [`~PreTrainedTokenizerBase.apply_chat_template`], the new template is used. + +```py +template = tokenizer.chat_template +template = template.replace("SYS", "SYSTEM") # Change the system token +tokenizer.chat_template = template # Set the new template +``` + +The template is saved in the `tokenizer_config.json` file. Upload it to the Hub with [`~PreTrainedTokenizer.push_to_hub`] so you can reuse it later and make sure everyone is using the right template for your model. + +```py +tokenizer.push_to_hub("model_name") +``` + +## Template writing tips + +The easiest way to start writing Jinja templates is to refer to existing templates. Use `print(tokenizer.chat_template)` on any chat model to see what template it's using. Try starting with simple models that don't call any tools or support RAG. Finally, take a look at the [Jinja documentation](https://jinja.palletsprojects.com/en/3.1.x/templates/#synopsis) for more details about formatting and syntax. + +This section curates some best practices for writing clean and efficient Jinja templates. + +### Trimming whitespace + +Jinja prints any whitespace before or after a block of text. This can be an issue for chat templates because whitespace usage should be intentional. Add `-` to strip any whitespace before a block. + +```jinja +{%- for message in messages %} + {{- message['role'] + message['content'] }} +{%- endfor %} +``` + +The incorrect whitespace usage example below may introduce a newline and indentation in the output. + +```jinja +{% for message in messages %} + {{ message['role'] + message['content'] }} +{% endfor %} +``` + +### Special variables + +There are five special variables available inside a template. You can pass virtually any additional arguments to [`~PreTrainedTokenizerBase.apply_chat_template`] and it will be available inside the template as a variable. However, you should try to keep the number of variables to the five below to make it easier for users to use the chat model without writing custom code to handle model-specific arguments. + +- `messages` contains the chat history as a list of message dicts. +- `tools` contains a list of tools in JSON schema format. +- `documents` contains a list of documents with the format `{"title": Title, "contents": "Contents"}` (designed for RAG models). +- `add_generation_prompt` is a boolean that determines whether to add an assistant header at the end of the conversation. +- `bos_token` and `eos_token` are special tokens extracted from a tokenizers `special_tokens_map`. + +### Callable functions + +There are two callable functions available inside a template. + +- `raise_exception(msg)` raises a `TemplateException`. This is useful for debugging or warning users about incorrect template usage. +- `strftime_now(format_str)` retrieves the current date and time in a specific format which could be useful to include in system messages. It is equivalent to [datetime.now().strftime(format_str)](https://docs.python.org/3/library/datetime.html#datetime.datetime.now) in Python. + +### Compatibility with non-Python Jinja + +Jinja is implemented in multiple languages and they generally have the same syntax. Writing a template in Python allows you to use Python methods such as [lower](https://docs.python.org/3/library/stdtypes.html#str.lower) on strings or [items](https://docs.python.org/3/library/stdtypes.html#dict.items) on dicts. But this won't work if the template is used in a non-Python implementation, for example, when deploying with Javascript or Rust. + +Make the changes below to ensure compatibility across all Jinja implementations. + +- Replace Python methods with Jinja filters. For example, replace `string.lower()` with `string|lower` or `dict.items()` with `dict|dictitems`. Most of the changes follow the same pattern except `string.strip()`, which is replaced with `string|trim`. Refer to the list of [built-in filters](https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters) for a complete list of filters. +- Replace `True`, `False`, and `None` (these are Python specific) with `true`, `false`, and `none` respectively. +- Directly rendering a dict or list may return different results in other implementations. For example, string entries may change from single-quote to double-quote. To avoid this, add the [tojson](https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.tojson) filter to maintain consistency. + +### Big templates + +Newer models or models with features like [tool-calling](./chat_extras#tools) and [RAG](./chat_extras#retrieval-augmented-generation-rag) require larger templates that can be longer than 100 lines. It may be easier to write larger templates in a separate file. The line numbers in the separate file corresponds exactly to the line numbers in template parsing or execution errors, making it easier to debug any potential issues. + +Write the template in a separate file and extract it to the chat template. + +```py +open("template.jinja", "w").write(tokenizer.chat_template) +``` + +You could also load an edited template back into the tokenizer. + +```py +tokenizer.chat_template = open("template.jinja").read() +``` + +## Templates for tools + +There isn't a specific format for writing templates for tools but it is best to follow the standard API. This ensures the template is widely accessible across models without requiring users to write custom code to use tools with your model. + +> [!WARNING] +> Formatting such as whitespace and special tokens are model-specific. Make sure everything exactly matches the format a model was trained with. + +The following section lists elements of the standard API for writing templates for tools. + +### Tool definitions + +Transformers chat template methods allow a user to pass tools as Python functions or a JSON schema. When functions are passed, a JSON schema is automatically generated and passed to the template. The `tools` variable in a template always takes a list of JSON schemas. + +The specific tokens and tool descriptions should match the ones your model was trained with. Your model doesn't need to understand the JSON schema input because your template can translate the JSON schema into your models format. For example, [Command-R](./model_doc/cohere) was trained with tools defined with Python function headers, but the Command-R tool template accepts JSON schemas. The template internally converts types and renders the input tools as Python headers. + +```json +{ + "type": "function", + "function": { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "a": { + "type": "number", + "description": "The first number to multiply" + }, + "b": { + "type": "number", + "description": "The second number to multiply" + } + }, + "required": ["a", "b"] + } + } +} +``` + +An example for handling tool definitions in a chat template is shown below. The specific tokens and tool descriptions should be changed to match the ones a model was trained with. + +``` +{%- if tools %} + {%- for tool in tools %} + {{- '' + tool['function']['name'] + '\n' }} + {%- for argument in tool['function']['parameters']['properties'] %} + {{- argument + ': ' + tool['function']['parameters']['properties'][argument]['description'] + '\n' }} + {%- endfor %} + {{- '\n' }} + {%- endif %} +{%- endif %} +``` + +### Tool calls + +Tool calls, if present, is a list with the `"assistant”` role. This is always a list even though most tool-calling models only support single tool calls, which means the list usually only contains a single element. + +```json +{ + "role": "assistant", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "multiply", + "arguments": { + "a": 5, + "b": 6 + } + } + } + ] +} +``` + +A common pattern for handling tool calls is shown below. + +``` +{%- if message['role'] == 'assistant' and 'tool_calls' in message %} + {%- for tool_call in message['tool_calls'] %} + {{- '' + tool_call['function']['name'] + '\n' + tool_call['function']['arguments']|tojson + '\n' }} + {%- endif %} + {%- endfor %} +{%- endif %} +``` + +### Tool responses + +Tool responses are a message dict with the `role`, `name` (name of the function) and `content` (result of the tool call) keys. + +```json +{ + "role": "tool", + "name": "multiply", + "content": "30" +} +``` + +Not all the keys need to be used in the tool response. For example, if a model doesn’t expect the function name to be included in the tool response, then you can just include the `role` and `content`. + +``` +{%- if message['role'] == 'tool' %} + {{- "" + message['content'] + "" }} +{%- endif %} +``` + +## Contribute + +Add a chat template by setting the `chat_template` attribute in the tokenizer and testing it with [`~PreTrainedTokenizerBase.apply_chat_template`]. If it works as expected, then you can upload it to the Hub with with [`~PreTrainedTokenizer.push_to_hub`]. + +Even if you're not the model owner, it is still helpful to add a template for a model with an empty chat template or a model that is using a default class template. Open a [pull request](https://hf.co/docs/hub/repositories-pull-requests-discussions) on the model repository to add the template. + +```py +tokenizer.chat_template = template +tokenizer.push_to_hub("model_name") +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/community.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/community.md new file mode 100644 index 0000000000000000000000000000000000000000..1b77bee9d2ded1c2836f98bbf6bb3a9f9b00ac1f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/community.md @@ -0,0 +1,70 @@ + + +# Community + +This page regroups resources around 🤗 Transformers developed by the community. + +## Community resources: + +| Resource | Description | Author | +|:----------|:-------------|------:| +| [Hugging Face Transformers Glossary Flashcards](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | A set of flashcards based on the [Transformers Docs Glossary](glossary) that has been put into a form which can be easily learned/revised using [Anki](https://apps.ankiweb.net/) an open source, cross platform app specifically designed for long term knowledge retention. See this [Introductory video on how to use the flashcards](https://www.youtube.com/watch?v=Dji_h7PILrw). | [Darigov Research](https://www.darigovresearch.com/) | + +## Community notebooks: + +| Notebook | Description | Author | | +|:----------|:-------------|:-------------|------:| +| [Fine-tune a pre-trained Transformer to generate lyrics](https://github.com/AlekseyKorshuk/huggingartists) | How to generate lyrics in the style of your favorite artist by fine-tuning a GPT-2 model | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) | +| [Train T5 in Tensorflow 2](https://github.com/snapthat/TF-T5-text-to-text) | How to train T5 for any task using Tensorflow 2. This notebook demonstrates a Question & Answer task implemented in Tensorflow 2 using SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | +| [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | How to train T5 on SQUAD with Transformers and Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | +| [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | How to fine-tune T5 for classification and multiple choice tasks using a text-to-text format with PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | +| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | How to fine-tune the DialoGPT model on a new dataset for open-dialog conversational chatbots | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | +| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | How to train on sequences as long as 500,000 tokens with Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | +| [Fine-tune BART for Summarization](https://github.com/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | How to fine-tune BART for summarization with fastai using blurr | [Wayde Gilliam](https://ohmeow.com/) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb) | +| [Fine-tune a pre-trained Transformer on anyone's tweets](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | How to generate tweets in the style of your favorite Twitter account by fine-tuning a GPT-2 model | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | +| [Optimize 🤗 Hugging Face models with Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | A complete tutorial showcasing W&B integration with Hugging Face | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | +| [Pretrain Longformer](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | How to build a "long" version of existing pretrained models | [Iz Beltagy](https://beltagy.net) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | +| [Fine-tune Longformer for QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | How to fine-tune longformer model for QA task | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | +| [Evaluate Model with 🤗nlp](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | How to evaluate longformer on TriviaQA with `nlp` | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) | +| [Fine-tune T5 for Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | How to fine-tune T5 for sentiment span extraction using a text-to-text format with PyTorch Lightning | [Lorenzo Ampil](https://github.com/enzoampil) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | +| [Fine-tune DistilBert for Multiclass Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | How to fine-tune DistilBert for multiclass classification with PyTorch | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)| +|[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|How to fine-tune BERT for multi-label classification using PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)| +|[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|How to fine-tune T5 for summarization in PyTorch and track experiments with WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)| +|[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|How to speed up fine-tuning by a factor of 2 using dynamic padding / bucketing|[Michael Benesty](https://github.com/pommedeterresautee) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)| +|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| How to train a Reformer model with bi-directional self-attention layers | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)| +|[Expand and Fine Tune Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| How to increase vocabulary of a pretrained SciBERT model from AllenAI on the CORD dataset and pipeline it. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)| +|[Fine Tune BlenderBotSmall for Summarization using the Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| How to fine-tune BlenderBotSmall for summarization on a custom dataset, using the Trainer API. | [Tanmay Thakur](https://github.com/lordtt13) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)| +|[Fine-tune Electra and interpret with Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | How to fine-tune Electra for sentiment analysis and interpret predictions with Captum Integrated Gradients | [Eliza Szczechla](https://elsanns.github.io) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)| +|[fine-tune a non-English GPT-2 Model with Trainer class](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | How to fine-tune a non-English GPT-2 Model with Trainer class | [Philipp Schmid](https://www.philschmid.de) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)| +|[Fine-tune a DistilBERT Model for Multi Label Classification task](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | How to fine-tune a DistilBERT Model for Multi Label Classification task | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)| +|[Fine-tune ALBERT for sentence-pair classification](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | How to fine-tune an ALBERT model or another BERT-based model for the sentence-pair classification task | [Nadir El Manouzi](https://github.com/NadirEM) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)| +|[Fine-tune Roberta for sentiment analysis](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | How to fine-tune a Roberta model for sentiment analysis | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)| +|[Evaluating Question Generation Models](https://github.com/flexudy-pipe/qugeev) | How accurate are the answers to questions generated by your seq2seq transformer model? | [Pascal Zoleko](https://github.com/zolekode) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)| +|[Classify text with DistilBERT and Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | How to fine-tune DistilBERT for text classification in TensorFlow | [Peter Bayerle](https://github.com/peterbayerle) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)| +|[Leverage BERT for Encoder-Decoder Summarization on CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | How to warm-start a *EncoderDecoderModel* with a *google-bert/bert-base-uncased* checkpoint for summarization on CNN/Dailymail | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)| +|[Leverage RoBERTa for Encoder-Decoder Summarization on BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | How to warm-start a shared *EncoderDecoderModel* with a *FacebookAI/roberta-base* checkpoint for summarization on BBC/XSum | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)| +|[Fine-tune TAPAS on Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | How to fine-tune *TapasForQuestionAnswering* with a *tapas-base* checkpoint on the Sequential Question Answering (SQA) dataset | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)| +|[Evaluate TAPAS on Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | How to evaluate a fine-tuned *TapasForSequenceClassification* with a *tapas-base-finetuned-tabfact* checkpoint using a combination of the 🤗 datasets and 🤗 transformers libraries | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)| +|[Fine-tuning mBART for translation](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | How to fine-tune mBART using Seq2SeqTrainer for Hindi to English translation | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)| +|[Fine-tune LayoutLM on FUNSD (a form understanding dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | How to fine-tune *LayoutLMForTokenClassification* on the FUNSD dataset for information extraction from scanned documents | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)| +|[Fine-Tune DistilGPT2 and Generate Text](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | How to fine-tune DistilGPT2 and generate text | [Aakash Tripathi](https://github.com/tripathiaakash) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)| +|[Fine-Tune LED on up to 8K tokens](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | How to fine-tune LED on pubmed for long-range summarization | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)| +|[Evaluate LED on Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | How to effectively evaluate LED on long-range summarization | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)| +|[Fine-tune LayoutLM on RVL-CDIP (a document image classification dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | How to fine-tune *LayoutLMForSequenceClassification* on the RVL-CDIP dataset for scanned document classification | [Niels Rogge](https://github.com/nielsrogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)| +|[Wav2Vec2 CTC decoding with GPT2 adjustment](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | How to decode CTC sequence with language model adjustment | [Eric Lam](https://github.com/voidful) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1e_z5jQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)| +|[Fine-tune BART for summarization in two languages with Trainer class](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | How to fine-tune BART for summarization in two languages with Trainer class | [Eliza Szczechla](https://github.com/elsanns) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)| +|[Evaluate Big Bird on Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | How to evaluate BigBird on long document question answering on Trivia QA | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)| +| [Create video captions using Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | How to create YouTube captions from any video by transcribing the audio with Wav2Vec | [Niklas Muennighoff](https://github.com/Muennighoff) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | How to fine-tune the Vision Transformer (ViT) on CIFAR-10 using HuggingFace Transformers, Datasets and PyTorch Lightning | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | +| [Fine-tune the Vision Transformer on CIFAR-10 using the 🤗 Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | How to fine-tune the Vision Transformer (ViT) on CIFAR-10 using HuggingFace Transformers, Datasets and the 🤗 Trainer | [Niels Rogge](https://github.com/nielsrogge) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | +| [Evaluate LUKE on Open Entity, an entity typing dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | How to evaluate *LukeForEntityClassification* on the Open Entity dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | +| [Evaluate LUKE on TACRED, a relation extraction dataset](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | How to evaluate *LukeForEntityPairClassification* on the TACRED dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | +| [Evaluate LUKE on CoNLL-2003, an important NER benchmark](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | How to evaluate *LukeForEntitySpanClassification* on the CoNLL-2003 dataset | [Ikuya Yamada](https://github.com/ikuyamada) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | +| [Evaluate BigBird-Pegasus on PubMed dataset](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | How to evaluate *BigBirdPegasusForConditionalGeneration* on PubMed dataset | [Vasudev Gupta](https://github.com/vasudevgupta7) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | +| [Speech Emotion Classification with Wav2Vec2](https://github.com/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | How to leverage a pretrained Wav2Vec2 model for Emotion Classification on the MEGA dataset | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | +| [Detect objects in an image with DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | How to use a trained *DetrForObjectDetection* model to detect objects in an image and visualize attention | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | +| [Fine-tune DETR on a custom object detection dataset](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | How to fine-tune *DetrForObjectDetection* on a custom object detection dataset | [Niels Rogge](https://github.com/NielsRogge) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | +| [Finetune T5 for Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | How to fine-tune *T5* on a Named Entity Recognition Task | [Ogundepo Odunayo](https://github.com/ToluClassics) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) | +| [Fine-Tuning Open-Source LLM using QLoRA with MLflow and PEFT](https://github.com/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | How to use [QLoRA](https://github.com/artidoro/qlora) and [PEFT](https://huggingface.co/docs/peft/en/index) to fine-tune an LLM in a memory-efficient way, while using [MLflow](https://mlflow.org/docs/latest/llms/transformers/index.html) to manage experiment tracking | [Yuki Watanabe](https://github.com/B-Step62) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlflow/mlflow/blob/master/docs/source/llms/transformers/tutorials/fine-tuning/transformers-peft.ipynb) | diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/contributing.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..c4804c69fb034fe0f83bf0e3bec11881c007db6c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/contributing.md @@ -0,0 +1,395 @@ + + +# Contribute to 🤗 Transformers + +Everyone is welcome to contribute, and we value everybody's contribution. Code +contributions are not the only way to help the community. Answering questions, helping +others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts +about the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our +[code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to 🤗 Transformers: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement new models. +* Contribute to the examples or to the documentation. + +If you don't know where to start, there is a special [Good First +Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of +open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions. + +> [!TIP] +> We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫 + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version** and **Python**, **PyTorch** and + **TensorFlow** versions when applicable. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +transformers-cli env +``` + +You can also run the same command from the root of the repository: + +```bash +python src/transformers/commands/transformers_cli.py env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the features usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue. + +## Do you want to implement a new model? + +New models are constantly released and if you want to implement a new model, please provide the following information: + +* A short description of the model and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to the model weights if they are available. + +If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers! + +We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model). + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested! + +For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs). + +## Create a Pull Request + +Before writing any code, we strongly advise you to search through the existing PRs or +issues to make sure nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to contribute to +🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest +manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing: + +1. Fork the [repository](https://github.com/huggingface/transformers) by + clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote: + + ```bash + git clone git@github.com:/transformers.git + cd transformers + git remote add upstream https://github.com/huggingface/transformers.git + ``` + +3. Create a new branch to hold your development changes: + + ```bash + git checkout -b a-descriptive-name-for-my-changes + ``` + + 🚨 **Do not** work on the `main` branch! + +4. Set up a development environment by running the following command in a virtual environment: + + ```bash + pip install -e ".[dev]" + ``` + + If 🤗 Transformers was already installed in the virtual environment, remove + it with `pip uninstall transformers` before reinstalling it in editable + mode with the `-e` flag. + + Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a + failure with this command. If that's the case make sure to install the Deep Learning framework you are working with + (PyTorch, TensorFlow and/or Flax) then do: + + ```bash + pip install -e ".[quality]" + ``` + + which should be enough for most use cases. + +5. Develop the features in your branch. + + As you work on your code, you should make sure the test suite + passes. Run the tests impacted by your changes like this: + + ```bash + pytest tests/.py + ``` + + For more information about tests, check out the + [Testing](https://huggingface.co/docs/transformers/testing) guide. + + 🤗 Transformers relies on `black` and `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + ```bash + make fixup + ``` + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command applies the + style corrections: + + ```bash + make style + ``` + + 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality + controls are run by the CI, but you can run the same checks with: + + ```bash + make quality + ``` + + Finally, we have a lot of scripts to make sure we don't forget to update + some files when adding a new model. You can run these scripts with: + + ```bash + make repo-consistency + ``` + + To learn more about those checks and how to fix any issues with them, check out the + [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + + If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check + make sure you install the [documentation builder](https://github.com/huggingface/doc-builder). + + ```bash + pip install hf-doc-builder + ``` + + Run the following command from the root of the repository: + + ```bash + doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build + ``` + + This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated + Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request. + + Once you're happy with your changes, add the changed files with `git add` and + record your changes locally with `git commit`: + + ```bash + git add modified_file.py + git commit + ``` + + Please remember to write [good commit + messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made! + + To keep your copy of the code up to date with the original + repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer: + + ```bash + git fetch upstream + git rebase upstream/main + ``` + + Push your changes to your branch: + + ```bash + git push -u origin a-descriptive-name-for-my-changes + ``` + + If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally. + +6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review. + +7. It's ok if maintainers request changes, it happens to our core contributors + too! So everyone can see the changes in the pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + +### Pull request checklist + +☐ The pull request title should summarize your contribution.
+☐ If your pull request addresses an issue, please mention the issue number in the pull +request description to make sure they are linked (and people viewing the issue know you +are working on it).
+☐ To indicate a work in progress please prefix the title with `[WIP]`. These are +useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.
+☐ Make sure existing tests pass.
+☐ If adding a new feature, also add tests for it.
+ - If you are adding a new model, make sure you use + `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests. + - If you are adding new `@slow` tests, make sure they pass using + `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`. + - If you are adding a new tokenizer, write tests and make sure + `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes. + - CircleCI does not run the slow tests, but GitHub Actions does every night!
+ +☐ All public methods must have informative docstrings (see +[`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py) +for an example).
+☐ Due to the rapidly growing repository, don't add any images, videos and other +non-text files that'll significantly weigh down the repository. Instead, use a Hub +repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) +to host these files and reference them by URL. We recommend placing documentation +related images in the following repository: +[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). +You can open a PR on this dataset repository and ask a Hugging Face member to merge it. + +For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide. + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the +[examples](https://github.com/huggingface/transformers/tree/main/examples) folder. + +We like `pytest` and `pytest-xdist` because it's faster. From the root of the +repository, specify a *path to a subfolder or a test file* to run the test: + +```bash +python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +``` + +Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory: + +```bash +pip install -r examples/xxx/requirements.txt # only needed the first time +python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)! + +You can also specify a smaller set of tests in order to test only the feature +you're working on. + +By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to +`yes` to run them. This will download many gigabytes of models so make sure you +have enough disk space, a good internet connection or a lot of patience! + + + +Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time! + + + +```bash +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model +RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification +``` + +Like the slow tests, there are other environment variables available which are not enabled by default during testing: +- `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers. + +More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py). + +🤗 Transformers uses `pytest` as a test runner only. It doesn't use any +`pytest`-specific features in the test suite itself. + +This means `unittest` is fully supported. Here's how to run tests with +`unittest`: + +```bash +python -m unittest discover -s tests -t . -v +python -m unittest discover -s examples -t examples -v +``` + +### Style guide + +For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). +Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) +for more information. + +### Develop on Windows + +On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings: + +```bash +git config core.autocrlf input +``` + +One way to run the `make` command on Windows is with MSYS2: + +1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`. +2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu). +3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`. +4. Add `C:\msys64\usr\bin` to your PATH environment variable. + +You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉 + +### Sync a forked repository with upstream main (the Hugging Face repository) + +When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs. + +1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main. +2. If a PR is absolutely necessary, use the following steps after checking out your branch: + + ```bash + git checkout -b your-branch-for-syncing + git pull --squash --no-commit upstream main + git commit -m '' + git push --set-upstream origin your-branch-for-syncing + ``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/conversations.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/conversations.md new file mode 100644 index 0000000000000000000000000000000000000000..2e842265a215897e1e3f563856d9cd4fb4a510a1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/conversations.md @@ -0,0 +1,154 @@ + + +# Chat basics + +Chat models are conversational models you can send and receive messages from. There are many chat models available to choose from, but in general, larger models tend to be better though that's not always the case. The model size is often included in the name, like "8B" or "70B", and it describes the number of parameters. Mixture-of-expert (MoE) models have names like "8x7B" or "141B-A35B" which means it's a 56B and 141B parameter model. You can try quantizing larger models to reduce memory requirements, otherwise you'll need ~2 bytes of memory per parameter. + +Check model leaderboards like [OpenLLM](https://hf.co/spaces/HuggingFaceH4/open_llm_leaderboard) and [LMSys Chatbot Arena](https://chat.lmsys.org/?leaderboard) to further help you identify the best chat models for your use case. Models that are specialized in certain domains (medical, legal text, non-English languages, etc.) may sometimes outperform larger general purpose models. + +> [!TIP] +> Chat with a number of open-source models for free on [HuggingChat](https://hf.co/chat/)! + +This guide shows you how to quickly start chatting with Transformers from the command line, how build and format a conversation, and how to chat using the [`TextGenerationPipeline`]. + +## transformers-cli + +Chat with a model directly from the command line as shown below. It launches an interactive session with a model. Enter `clear` to reset the conversation, `exit` to terminate the session, and `help` to display all the command options. + +```bash +transformers-cli chat --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct +``` + +
+ +
+ +For a full list of options, run the command below. + +```bash +transformers-cli chat -h +``` + +The chat is implemented on top of the [AutoClass](./model_doc/auto), using tooling from [text generation](./llm_tutorial) and [chat](./chat_templating). + +## TextGenerationPipeline + +[`TextGenerationPipeline`] is a high-level text generation class with a "chat mode". Chat mode is enabled when a conversational model is detected and the chat prompt is [properly formatted](./llm_tutorial#wrong-prompt-format). + +To start, build a chat history with the following two roles. + +- `system` describes how the model should behave and respond when you're chatting with it. This role isn't supported by all chat models. +- `user` is where you enter your first message to the model. + +```py +chat = [ + {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, + {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"} +] +``` + +Create the [`TextGenerationPipeline`] and pass `chat` to it. For large models, setting [device_map="auto"](./models#big-model-inference) helps load the model quicker and automatically places it on the fastest device available. Changing the data type to [torch.bfloat16](./models#model-data-type) also helps save memory. + +```py +import torch +from transformers import pipeline + +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto") +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +```txt +(sigh) Oh boy, you're asking me for advice? You're gonna need a map, pal! Alright, +alright, I'll give you the lowdown. But don't say I didn't warn you, I'm a robot, not a tour guide! + +So, you wanna know what's fun to do in the Big Apple? Well, let me tell you, there's a million +things to do, but I'll give you the highlights. First off, you gotta see the sights: the Statue of +Liberty, Central Park, Times Square... you know, the usual tourist traps. But if you're lookin' for +something a little more... unusual, I'd recommend checkin' out the Museum of Modern Art. It's got +some wild stuff, like that Warhol guy's soup cans and all that jazz. + +And if you're feelin' adventurous, take a walk across the Brooklyn Bridge. Just watch out for +those pesky pigeons, they're like little feathered thieves! (laughs) Get it? Thieves? Ah, never mind. + +Now, if you're lookin' for some serious fun, hit up the comedy clubs in Greenwich Village. You might +even catch a glimpse of some up-and-coming comedians... or a bunch of wannabes tryin' to make it big. (winks) + +And finally, if you're feelin' like a real New Yorker, grab a slice of pizza from one of the many amazing +pizzerias around the city. Just don't try to order a "robot-sized" slice, trust me, it won't end well. (laughs) + +So, there you have it, pal! That's my expert advice on what to do in New York. Now, if you'll +excuse me, I've got some oil changes to attend to. (winks) +``` + +Use the `append` method on `chat` to respond to the models message. + +```py +chat = response[0]["generated_text"] +chat.append( + {"role": "user", "content": "Wait, what's so wild about soup cans?"} +) +response = pipeline(chat, max_new_tokens=512) +print(response[0]["generated_text"][-1]["content"]) +``` + +```txt +(laughs) Oh, you're killin' me, pal! You don't get it, do you? Warhol's soup cans are like, art, man! +It's like, he took something totally mundane, like a can of soup, and turned it into a masterpiece. It's +like, "Hey, look at me, I'm a can of soup, but I'm also a work of art!" +(sarcastically) Oh, yeah, real original, Andy. + +But, you know, back in the '60s, it was like, a big deal. People were all about challenging the +status quo, and Warhol was like, the king of that. He took the ordinary and made it extraordinary. +And, let me tell you, it was like, a real game-changer. I mean, who would've thought that a can of soup could be art? (laughs) + +But, hey, you're not alone, pal. I mean, I'm a robot, and even I don't get it. (winks) +But, hey, that's what makes art, art, right? (laughs) +``` + +## Performance + +Transformers load models in full precision by default, and for a 8B model, this requires ~32GB of memory! Reduce memory usage by loading a model in half-precision or bfloat16 (only uses ~2 bytes per parameter). You can even quantize the model to a lower precision like 8-bit or 4-bit with [bitsandbytes](https://hf.co/docs/bitsandbytes/index). + +> [!TIP] +> Refer to the [Quantization](./quantization/overview) docs for more information about the different quantization backends available. + +Create a [`BitsAndBytesConfig`] with your desired quantization settings and pass it to the pipelines `model_kwargs` parameter. The example below quantizes a model to 8-bits. + +```py +from transformers import pipeline, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_8bit=True) +pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config}) +``` + +In general, larger models are slower in addition to requiring more memory because text generation is bottlenecked by **memory bandwidth** instead of compute power. Each active parameter must be read from memory for every generated token. For a 16GB model, 16GB must be read from memory for every generated token. + +The number of generated tokens/sec is proportional to the total memory bandwidth of the system divided by the model size. Depending on your hardware, total memory bandwidth can vary. Refer to the table below for approximate generation speeds for different hardware types. + +| Hardware | Memory bandwidth | +|---|---| +| consumer CPU | 20-100GB/sec | +| specialized CPU (Intel Xeon, AMD Threadripper/Epyc, Apple silicon) | 200-900GB/sec | +| data center GPU (NVIDIA A100/H100) | 2-3TB/sec | + +The easiest solution for improving generation speed is to either quantize a model or use hardware with higher memory bandwidth. + +You can also try techniques like [speculative decoding](./generation_strategies#speculative-decoding), where a smaller model generates candidate tokens that are verified by the larger model. If the candidate tokens are correct, the larger model can generate more than one token per `forward` pass. This significantly alleviates the bandwidth bottleneck and improves generation speed. + +> [!TIP] +> Parameters may not be active for every generated token in MoE models such as [Mixtral](./model_doc/mixtral), [Qwen2MoE](./model_doc/qwen2_moe.md), and [DBRX](./model_doc/dbrx). As a result, MoE models generally have much lower memory bandwidth requirements and can be faster than a regular LLM of the same size. However, techniques like speculative decoding are ineffective with MoE models because parameters become activated with each new speculated token. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/custom_models.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/custom_models.md new file mode 100644 index 0000000000000000000000000000000000000000..6ae5099a0312c5c18a1b31c0bfa6834866a5f442 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/custom_models.md @@ -0,0 +1,297 @@ + + +# Customizing models + +Transformers models are designed to be customizable. A models code is fully contained in the [model](https://github.com/huggingface/transformers/tree/main/src/transformers/models) subfolder of the Transformers repository. Each folder contains a `modeling.py` and a `configuration.py` file. Copy these files to start customizing a model. + +> [!TIP] +> It may be easier to start from scratch if you're creating an entirely new model. But for models that are very similar to an existing one in Transformers, it is faster to reuse or subclass the same configuration and model class. + +This guide will show you how to customize a ResNet model, enable [AutoClass](./models#autoclass) support, and share it on the Hub. + +## Configuration + +A configuration, given by the base [`PretrainedConfig`] class, contains all the necessary information to build a model. This is where you'll configure the attributes of the custom ResNet model. Different attributes gives different ResNet model types. + +The main rules for customizing a configuration are: + +1. A custom configuration must subclass [`PretrainedConfig`]. This ensures a custom model has all the functionality of a Transformers' model such as [`~PretrainedConfig.from_pretrained`], [`~PretrainedConfig.save_pretrained`], and [`~PretrainedConfig.push_to_hub`]. +2. The [`PretrainedConfig`] `__init__` must accept any `kwargs` and they must be passed to the superclass `__init__`. [`PretrainedConfig`] has more fields than the ones set in your custom configuration, so when you load a configuration with [`~PretrainedConfig.from_pretrained`], those fields need to be accepted by your configuration and passed to the superclass. + +> [!TIP] +> It is useful to check the validity of some of the parameters. In the example below, a check is implemented to ensure `block_type` and `stem_type` belong to one of the predefined values. +> +> Add `model_type` to the configuration class to enable [AutoClass](./models#autoclass) support. + +```py +from transformers import PretrainedConfig +from typing import List + +class ResnetConfig(PretrainedConfig): + model_type = "resnet" + + def __init__( + self, + block_type="bottleneck", + layers: List[int] = [3, 4, 6, 3], + num_classes: int = 1000, + input_channels: int = 3, + cardinality: int = 1, + base_width: int = 64, + stem_width: int = 64, + stem_type: str = "", + avg_down: bool = False, + **kwargs, + ): + if block_type not in ["basic", "bottleneck"]: + raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.") + if stem_type not in ["", "deep", "deep-tiered"]: + raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.") + + self.block_type = block_type + self.layers = layers + self.num_classes = num_classes + self.input_channels = input_channels + self.cardinality = cardinality + self.base_width = base_width + self.stem_width = stem_width + self.stem_type = stem_type + self.avg_down = avg_down + super().__init__(**kwargs) +``` + +Save the configuration to a JSON file in your custom model folder, `custom-resnet`, with [`~PretrainedConfig.save_pretrained`]. + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d_config.save_pretrained("custom-resnet") +``` + +## Model + +With the custom ResNet configuration, you can now create and customize the model. The model subclasses the base [`PreTrainedModel`] class. Like [`PretrainedConfig`], inheriting from [`PreTrainedModel`] and initializing the superclass with the configuration extends Transformers' functionalities such as saving and loading to the custom model. + +Transformers' models follow the convention of accepting a `config` object in the `__init__` method. This passes the entire `config` to the model sublayers, instead of breaking the `config` object into multiple arguments that are individually passed to the sublayers. + +Writing models this way produces simpler code with a clear source of truth for any hyperparameters. It also makes it easier to reuse code from other Transformers' models. + +You'll create two ResNet models, a barebones ResNet model that outputs the hidden states and a ResNet model with an image classification head. + + + + +Define a mapping between the block types and classes. Everything else is created by passing the configuration class to the ResNet model class. + +> [!TIP] +> Add `config_class` to the model class to enable [AutoClass](#autoclass-support) support. + +```py +from transformers import PreTrainedModel +from timm.models.resnet import BasicBlock, Bottleneck, ResNet +from .configuration_resnet import ResnetConfig + +BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck} + +class ResnetModel(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor): + return self.model.forward_features(tensor) +``` + + + + +The `forward` method needs to be rewrittten to calculate the loss for each logit if labels are available. Otherwise, the ResNet model class is the same. + +> [!TIP] +> Add `config_class` to the model class to enable [AutoClass](#autoclass-support) support. + +```py +import torch + +class ResnetModelForImageClassification(PreTrainedModel): + config_class = ResnetConfig + + def __init__(self, config): + super().__init__(config) + block_layer = BLOCK_MAPPING[config.block_type] + self.model = ResNet( + block_layer, + config.layers, + num_classes=config.num_classes, + in_chans=config.input_channels, + cardinality=config.cardinality, + base_width=config.base_width, + stem_width=config.stem_width, + stem_type=config.stem_type, + avg_down=config.avg_down, + ) + + def forward(self, tensor, labels=None): + logits = self.model(tensor) + if labels is not None: + loss = torch.nn.functional.cross_entropy(logits, labels) + return {"loss": loss, "logits": logits} + return {"logits": logits} +``` + + + + +A model can return any output format. Returning a dictionary (like `ResnetModelForImageClassification`) with losses when labels are available makes the custom model compatible with [`Trainer`]. For other output formats, you'll need your own training loop or a different library for training. + +Instantiate the custom model class with the configuration. + +```py +resnet50d = ResnetModelForImageClassification(resnet50d_config) +``` + +At this point, you can load pretrained weights into the model or train it from scratch. In this guide, you'll load pretrained weights. + +Load the pretrained weights from the [timm](https://hf.co/docs/timm/index) library, and then transfer those weights to the custom model with [load_state_dict](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.load_state_dict). + +```py +import timm + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +## AutoClass + +The [AutoClass](./models#model-classes) API is a shortcut for automatically loading the correct architecture for a given model. It is convenient to enable this for users loading your custom model. + +Make sure you have the `model_type` attribute (must be different from existing model types) in the configuration class and `config_class` attribute in the model class. Use the [`~AutoConfig.register`] method to add the custom configuration and model to the [AutoClass](./models#model-classes) API. + +> [!TIP] +> The first argument to [`AutoConfig.register`] must match the `model_type` attribute in the custom configuration class, and the first argument to [`AutoModel.register`] must match the `config_class` of the custom model class. + +```py +from transformers import AutoConfig, AutoModel, AutoModelForImageClassification + +AutoConfig.register("resnet", ResnetConfig) +AutoModel.register(ResnetConfig, ResnetModel) +AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification) +``` + +Your custom model code is now compatible with the [AutoClass](./models#autoclass) API. Users can load the model with the [AutoModel](./model_doc/auto#automodel) or [`AutoModelForImageClassification`] classes. + +## Upload + +Upload a custom model to the [Hub](https://hf.co/models) to allow other users to easily load and use it. + +Ensure the model directory is structured correctly as shown below. The directory should contain: + +- `modeling.py`: Contains the code for `ResnetModel` and `ResnetModelForImageClassification`. This file can rely on relative imports to other files as long as they're in the same directory. + +> [!WARNING] +> When copying a Transformers' model file, replace all relative imports at the top of the `modeling.py` file to import from Transformers instead. + +- `configuration.py`: Contains the code for `ResnetConfig`. +- `__init__.py`: Can be empty, this file allows Python `resnet_model` to be used as a module. + +```bash +. +└── resnet_model + ├── __init__.py + ├── configuration_resnet.py + └── modeling_resnet.py +``` + +To share the model, import the ResNet model and configuration. + +```py +from resnet_model.configuration_resnet import ResnetConfig +from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification +``` + +Copy the code from the model and configuration files. To make sure the AutoClass objects are saved with [`~PreTrainedModel.save_pretrained`], call the [`~PretrainedConfig.register_for_auto_class`] method. This modifies the configuration JSON file to include the AutoClass objects and mapping. + +For a model, pick the appropriate `AutoModelFor` class based on the task. + +```py +ResnetConfig.register_for_auto_class() +ResnetModel.register_for_auto_class("AutoModel") +ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification") +``` + +To map more than one task to the model, edit `auto_map` in the configuration JSON file directly. + +```json +"auto_map": { + "AutoConfig": "--", + "AutoModel": "--", + "AutoModelFor": "--", +}, +``` + +Create the configuration and model and load pretrained weights into it. + +```py +resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) +resnet50d = ResnetModelForImageClassification(resnet50d_config) + +pretrained_model = timm.create_model("resnet50d", pretrained=True) +resnet50d.model.load_state_dict(pretrained_model.state_dict()) +``` + +The model is ready to be pushed to the Hub now. Log in to your Hugging Face account from the command line or notebook. + + + + +```bash +huggingface-cli login +``` + + + + +```py +from huggingface_hub import notebook_login + +notebook_login() +``` + + + + +Call [`~PreTrainedModel.push_to_hub`] on the model to upload the model to the Hub. + +```py +resnet50d.push_to_hub("custom-resnet50d") +``` + +The pretrained weights, configuration, `modeling.py` and `configuration.py` files should all be uploaded to the Hub now in a [repository](https://hf.co/sgugger/custom-resnet50d) under your namespace. + +Because a custom model doesn't use the same modeling code as a Transformers' model, you need to add `trust_remode_code=True` in [`~PreTrainedModel.from_pretrained`] to load it. Refer to the load [custom models](./models#custom-models) section for more information. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/debugging.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/debugging.md new file mode 100644 index 0000000000000000000000000000000000000000..09394d2229d149a2e9300469573fd6ba29c1d938 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/debugging.md @@ -0,0 +1,367 @@ + + +# Multi-GPU debugging + +Distributed training can be tricky because you have to ensure you're using the correct CUDA version across your system. You may encounter inter-communication issues between GPUs, and there may be underflow or overflow problems in your model. + +This guide covers how to debug these issues, especially as it relates to DeepSpeed and PyTorch. + +## DeepSpeed CUDA + +DeepSpeed compiles CUDA C++ which can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system. This section focuses on PyTorch built with *CUDA 10.2* + +```bash +pip install deepspeed +``` + +> [!TIP] +> For any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team. + +### Non-identical toolkits + +PyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed everywhere. + +The exact location can vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly set up and added to your `PATH` environment variable, you can find the installation location with the following command. + +```bash +which nvcc +``` + +### Multiple toolkits + +You may also have more than one CUDA toolkit installed on your system. + +```bash +/usr/local/cuda-10.2 +/usr/local/cuda-11.0 +``` + +Typically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path. + +Take a look at the contents of the following environment variables first. + +```bash +echo $PATH +echo $LD_LIBRARY_PATH +``` + +`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To find a specific CUDA toolkit, insert the correct path to list first. This command prepends rather than overwrites the existing values. + +```bash +# adjust the version and full path if needed +export PATH=/usr/local/cuda-10.2/bin:$PATH +export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH +``` + +In addition, you should also check that the assigned directories actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`), and while it is unlikely your system names them differently, you should check the actual names and change them accordingly. + +### Older versions + +Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler. + +You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, create a symlink to give the build system visibility to the older compiler. + +```bash +# adjust the path to your system +sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc +sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ +``` + +### Prebuild + +If you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, try to prebuild the DeepSpeed modules before installing them. Run the commands below to make a local build for DeepSpeed. + +```bash +git clone https://github.com/deepspeedai/DeepSpeed/ +cd DeepSpeed +rm -rf build +TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \ +--global-option="build_ext" --global-option="-j8" --no-cache -v \ +--disable-pip-version-check 2>&1 | tee build.log +``` + +> [!TIP] +> Add the `DS_BUILD_AIO=1` parameter to the build command to use NVMe offload. Make sure you install the libaio-dev package across your system. + +Next, specify your GPUs architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command. + +```bash +python -c "import torch; print(torch.cuda.get_arch_list())" +``` + +Find the architecture for a GPU with the following command. + + + + +```bash +CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())" +``` + + + + +Run the following command to find the architecture for GPU `0`. The results will show a value for `major` and `minor`, which is your GPU architecture. The GPU architecture below is `8.6`. + +```bash +CUDA_VISIBLE_DEVICES=0 python -c "import torch; \ +print(torch.cuda.get_device_properties(torch.device('cuda'))) +"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)" +``` + + + + +If you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST="8.6"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST="6.1;8.6"`. + +It is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture. + +For training on multiple machines with the same setup, you'll need to make a binary wheel as shown below. + +```bash +git clone https://github.com/deepspeedai/DeepSpeed/ +cd DeepSpeed +rm -rf build +TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \ +python setup.py build_ext -j8 bdist_wheel +``` + +This command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Install this wheel locally or on another machine. + +```bash +pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl +``` + +## Communication + +Distributed training involves communication between processes and or nodes and this can be a potential source of errors. + +Download the script below to diagnose network issues, and then run it to test GPU communication. The example command below tests how two GPUs communicate. Adjust the `--nproc_per_node` and `--nnodes` parameters to adapt it to your system. + +```bash +wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py +python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py +``` + +The script prints an `OK` status if both GPUs are able to communicate and allocate memory. Take a closer look at the diagnostic script for more details and a recipe for running it in a SLURM environment. + +Add the `NCCL_DEBUG=INFO` environment variable to report more NCCL-related debugging information. + +```bash +NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py +``` + +## Underflow and overflow detection + +Underflow and overflow can occur when activations or weights are `inf`, `nan`, and when `loss=NaN`. This may indicate an underflow or overflow issue. To detect these issues, activate the `DebugUnderflowOverflow` module in [`TrainingArguments.debug`] or import and add the module to your own training loop or another trainer class. + + + + +```py +from transformers import TrainingArguments + +args = TrainingArguments( + debug="underflow_overflow", + ... +) +``` + + + + +```py +from transformers.debug_utils import DebugUnderflowOverflow + +debug_overflow = DebugUnderflowOverflow(model) +``` + + + + +The [`~debug_utils.DebugUnderflowOverflow`] module inserts hooks into the model to test the input and output variables and the corresponding model weights after each forward call. If `inf` or `nan` is detected in at least one element of the activations or weights, the module prints a report like the one shown below. + +The example below is for fp16 mixed precision training with [google/mt5-small](https://huggingface.co/google/mt5-small). + +```shell +Detected inf/nan during batch_number=0 +Last 21 forward frames: +abs min abs max metadata + encoder.block.1.layer.1.DenseReluDense.dropout Dropout +0.00e+00 2.57e+02 input[0] +0.00e+00 2.85e+02 output +[...] + encoder.block.2.layer.0 T5LayerSelfAttention +6.78e-04 3.15e+03 input[0] +2.65e-04 3.42e+03 output[0] + None output[1] +2.25e-01 1.00e+04 output[2] + encoder.block.2.layer.1.layer_norm T5LayerNorm +8.69e-02 4.18e-01 weight +2.65e-04 3.42e+03 input[0] +1.79e-06 4.65e+00 output + encoder.block.2.layer.1.DenseReluDense.wi_0 Linear +2.17e-07 4.50e+00 weight +1.79e-06 4.65e+00 input[0] +2.68e-06 3.70e+01 output + encoder.block.2.layer.1.DenseReluDense.wi_1 Linear +8.08e-07 2.66e+01 weight +1.79e-06 4.65e+00 input[0] +1.27e-04 2.37e+02 output + encoder.block.2.layer.1.DenseReluDense.dropout Dropout +0.00e+00 8.76e+03 input[0] +0.00e+00 9.74e+03 output + encoder.block.2.layer.1.DenseReluDense.wo Linear +1.01e-06 6.44e+00 weight +0.00e+00 9.74e+03 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense +1.79e-06 4.65e+00 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.dropout Dropout +3.18e-04 6.27e+04 input[0] +0.00e+00 inf output +``` + +At the start of the report, you can see which batch number the error occurred. In this case, it occurred on the first batch. + +Each frame describes the module it is reporting on. For example, the frame below inspected `encoder.block.2.layer.1.layer_norm`. This indicates the layer norm in the first layer of the second block of the encoder. The forward calls are to `T5LayerNorm`. + +```shell + encoder.block.2.layer.1.layer_norm T5LayerNorm +8.69e-02 4.18e-01 weight +2.65e-04 3.42e+03 input[0] +1.79e-06 4.65e+00 output +``` + +The last frame reports on the `Dropout.forward` function. It called the `dropout` attribute from inside the `DenseReluDense` class. You can observe that the overflow (`inf`) occurred in the first layer of the encoders second block in the first batch. The absolute largest input element was 6.27e+04. + +```shell + encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense +1.79e-06 4.65e+00 input[0] +3.18e-04 6.27e+04 output + encoder.block.2.layer.1.dropout Dropout +3.18e-04 6.27e+04 input[0] +0.00e+00 inf output +``` + +The `T5DenseGatedGeluDense.forward` function output activations had an absolute maximum value of 6.27e+04 which is close to fp16s maximum limit of 6.4e+04. In the next step, `Dropout` renormalizes the weights, after zeroing some elements, which pushes the absolute maximum value to greater than 6.4e+04 resulting in an overflow. + +Now that you know where the error is happening, you can investigate the modeling code in [modeling_t5.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py). + +```py +class T5DenseGatedGeluDense(nn.Module): + def __init__(self, config): + super().__init__() + self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False) + self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False) + self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) + self.dropout = nn.Dropout(config.dropout_rate) + self.gelu_act = ACT2FN["gelu_new"] + + def forward(self, hidden_states): + hidden_gelu = self.gelu_act(self.wi_0(hidden_states)) + hidden_linear = self.wi_1(hidden_states) + hidden_states = hidden_gelu * hidden_linear + hidden_states = self.dropout(hidden_states) + hidden_states = self.wo(hidden_states) + return hidden_states +``` + +One solution is to go back a few steps before the values started growing too large and switch to fp32 so the numbers don't overflow when multiplied or summed. Another potential solution is to temporarily disable mixed precision training (`amp`). + +```py +import torch + +def forward(self, hidden_states): + if torch.is_autocast_enabled(): + with torch.cuda.amp.autocast(enabled=False): + return self._forward(hidden_states) + else: + return self._forward(hidden_states) +``` + +The report only returns inputs and outputs of full frames, so you may also want to analyze the intermediate values of any `forward` function as well. Add the `detect_overflow` function after the forward calls to track `inf` or `nan` values in the intermediate `forwarded_states`. + +```py +from debug_utils import detect_overflow + +class T5LayerFF(nn.Module): + [...] + + def forward(self, hidden_states): + forwarded_states = self.layer_norm(hidden_states) + detect_overflow(forwarded_states, "after layer_norm") + forwarded_states = self.DenseReluDense(forwarded_states) + detect_overflow(forwarded_states, "after DenseReluDense") + return hidden_states + self.dropout(forwarded_states) +``` + +Finally, you can configure the number of frames printed by [`~debug_utils.DebugUnderflowOverflow`]. + +```py +from transformers.debug_utils import DebugUnderflowOverflow + +debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100) +``` + +### Batch tracing + +[`~debug_utils.DebugUnderflowOverflow`] is able to trace the absolute minimum and maximum values in each batch with the underflow and overflow feature disabled. This is useful for identifying where errors are occurring in the model. + +The example below shows how to trace the minimum and maximum values in batches 1 and 3 (batches are zero-indexd). + +```py +debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) +``` + +```shell + *** Starting batch number=1 *** +abs min abs max metadata + shared Embedding +1.01e-06 7.92e+02 weight +0.00e+00 2.47e+04 input[0] +5.36e-05 7.92e+02 output +[...] + decoder.dropout Dropout +1.60e-07 2.27e+01 input[0] +0.00e+00 2.52e+01 output + decoder T5Stack + not a tensor output + lm_head Linear +1.01e-06 7.92e+02 weight +0.00e+00 1.11e+00 input[0] +6.06e-02 8.39e+01 output + T5ForConditionalGeneration + not a tensor output + + *** Starting batch number=3 *** +abs min abs max metadata + shared Embedding +1.01e-06 7.92e+02 weight +0.00e+00 2.78e+04 input[0] +5.36e-05 7.92e+02 output +[...] +``` + +[`~debug_utils.DebugUnderflowOverflow`] reports on a large number of frames which is easier for debugging. Once you know where a problem is occurring, say batch 150, then you can focus the trace for batches 149 and 150 and compare where the numbers are diverging. + +It is also possible to abort the trace after a certain batch number, for example, batch 3. + +```py +debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/deepspeed.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..4d1df98e50a225537228d450ce1e6ebee40bbdcf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/deepspeed.md @@ -0,0 +1,1029 @@ + + +# DeepSpeed + +[DeepSpeed](https://www.deepspeed.ai/) is designed to optimize distributed training for large models with data, model, pipeline, and even a combination of all three [parallelism](./perf_train_gpu_many) strategies to provide better memory efficiency and faster training speeds. This is achieved with the [Zero Redundancy Optimizer (ZeRO)](https://hf.co/papers/1910.02054) which consists of three stages. + +| ZeRO stage | description | +|---|---| +| 1 | partition optimizer states | +| 2 | partition optimizer and gradient states | +| 3 | partition optimizer, gradient, and parameters | + +Each stage progressively saves more memory, allowing really large models to fit and train on a single GPU. All ZeRO stages, offloading optimizer memory and computations from the GPU to the CPU are integrated with [`Trainer`]. Provide a config file or one of the example templates to [`Trainer`] to enable DeepSpeed features. + +This guide walks you through setting up a DeepSpeed config file, how to enable its features in [`Trainer`], and deploy for training. + +Install DeepSpeed from either PyPI or Transformers. For more detailed installation instructions, refer to the DeepSpeed [installation](https://www.deepspeed.ai/tutorials/advanced-install/) or GitHUB [README](https://github.com/microsoft/deepspeed#installation). + + + + +```bash +pip install deepspeed +``` + + + + +```bash +pip install transformers[deepspeed] +``` + + + + +> [!WARNING] +> Refer to the [DeepSpeed CUDA installation](./debugging#deepspeed-cuda-issues) if you're having trouble with your installation. While DeepSpeed has a pip installable package, it is highly recommended to [install it from source](https://www.deepspeed.ai/tutorials/advanced-install/#install-deepspeed-from-source) to ensure it matches your hardware and to support certain features which aren't available in the PyPI distribution. + +DeepSpeed provides a tool for estimating the required CPU and GPU memory for the parameters, optimizer and gradient states. You'll also to need to reserve some memory for the CUDA kernels and activations. + +Run the command below to check the memory requirements for [bigscience/T0_3B](https://huggingface.co/docs/transformers/main/en/bigscience/T0_3B) on a single GPU. + +```bash +$ python -c 'from transformers import AutoModel; \ +from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ +model = AutoModel.from_pretrained("bigscience/T0_3B"); \ +estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1)' +[...] +Estimated memory needed for params, optim states and gradients for a: +HW: Setup with 1 node, 1 GPU per node. +SW: Model with 2783M total params, 65M largest layer params. + per CPU | per GPU | Options + 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 + 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 + 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=1 + 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=0 + 0.37GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=1 + 15.56GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=0 +``` + +> [!TIP] +> If you have enough GPU memory, disable CPU and NVMe offload to speed everything up. + +## Choosing a ZeRO stage + +Consider the table below to help you choose the appropriate ZeRO stage for training because there is a trade-off between training speed and memory usage. The table orders the ZeRO stages from fastest to slowest and from least memory usage to most. + +| fastest | least memory usage | +|---|---| +| ZeRO-1 | ZeRO-3 + offload | +| ZeRO-2 | ZeRO-3 | +| ZeRO-2 + offload | ZeRO-2 + offload | +| ZeRO-3 | ZeRO-2 | +| ZeRO-3 + offload | ZeRO-1 | + +Decide the type of performance you're optimizing for, speed or memory, and then work backwards to discover the best ZeRO stage for your use case. For example, if you're optimizing for speed, start with the fastest ZeRO stage and if you run out of memory, try the next stage which is slower but more memory efficient. + +## Config file + +Once you've decided on a ZeRO stage, set up a config file to enable DeepSpeed with [`Trainer`]. The config file contains all the parameters for how to configure and set up your training. When the training script is executed, DeepSpeed logs the configuration from [`Trainer`] to the console so you can see exactly what's being used. + +> [!TIP] +> Find a complete list of DeepSpeed configuration options on the [DeepSpeed Configuration JSON](https://www.deepspeed.ai/docs/config-json/) reference. There are also practical examples of various DeepSpeed configuration examples in the [DeepSpeedExamples](https://github.com/microsoft/DeepSpeedExamples) main [DeepSpeed](https://github.com/microsoft/DeepSpeed) repository. Run the command below to quickly find specific examples. +> +> ```bash +> git clone https://github.com/microsoft/DeepSpeedExamples +> cd DeepSpeedExamples +> find . -name '*json' +> # find examples with the Lamb optimizer +> grep -i Lamb $(find . -name '*json') +> ``` + +The config file is passed as a path to a JSON file if you're training from the command line interface or as a nested dict object if you're using [`Trainer`] in a notebook. + + + + +```py +TrainingArguments( + deepspeed="path/to/deepspeed_config.json", + ..., +) +``` + + + + +```py +ds_config_dict = dict(scheduler=scheduler_params, optimizer=optimizer_params) +args = TrainingArguments( + deepspeed=ds_config_dict, + ..., +) +trainer = Trainer( + model, + args, + ..., +) +``` + + + + +### DeepSpeed versus Trainer parameters + +There are three types of config parameters. + +1. Some config parameters are shared by DeepSpeed and [`Trainer`] making it difficult to identify errors when there are conflicting definitions. In this case, configure these parameters from the [`Trainer`] command line arguments. +1. Some config parameters are automatically derived from the model configuration and don't need to be manually configured. [`Trainer`] uses the config value `auto` to set the most correct or efficient option. You could define these parameters explicitly, but you must take care to ensure the [`Trainer`] and DeepSpeed config parameters match. Mismatches may cause training to fail in very difficult to detect ways. +1. Some config parameters are specific to DeepSpeed and should be manually set based on your training requirements. + +There are two ways to modify the config parameters. + +> [!TIP] +> Some values, such as `scheduler.params.total_num_steps`, are calculated by [`Trainer`] during training. + +1. Create or load a DeepSpeed config to use as the main config. +1. Create a [`TrainingArguments`] object based on the DeepSpeed config values. + +### ZeRO stage + +Each ZeRO stage config is defined in `zero_optimization`. + +For a more detailed explanation of each parameter, refer to the [DeepSpeed Configuration JSON](https://www.deepspeed.ai/docs/config-json/) reference. These parameters must be set up with DeepSpeed because [`Trainer`] doesn't provide equivalent command line arguments. + +> [!WARNING] +> DeepSpeed doesn't validate parameter names and any typos will fallback on the parameters default setting. Observe the DeepSpeed engine startup log messages to see what values are being used. + + + + +ZeRO-1 shards the optimizer states across GPUs and you can expect a small speed up. + +```yml +{ + "zero_optimization": { + "stage": 1 + } +} +``` + + + + +ZeRO-2 shards the optimizer and gradient states across GPUs. This stage is primarily used for training since its features are not relevant to inference. Some important parameters to configure for better performance include the following. + +* `offload_optimizer` should be enabled to reduce GPU memory usage. +* `overlap_comm` when set to `true` uses more GPU memory in exchange for lower allreduce latency. This feature uses 4.5x the `allgather_bucket_size` and `reduce_bucket_size` values. In this example, they're set to `5e8` which means it requires 9GB of GPU memory. If your GPU memory is 8GB or less, you should reduce `overlap_comm` to lower the memory requirements and prevent an out-of-memory (OOM) error. +* `allgather_bucket_size` and `reduce_bucket_size` trade-off available GPU memory for communication speed. The smaller their values, the slower communication is and the more GPU memory is available. You can balance, for example, whether a bigger batch size is more important than a slightly slower training time. +* `round_robin_gradients` is available in DeepSpeed 0.4.4 for CPU offloading. It parallelizes gradient copying to CPU memory among ranks by fine-grained gradient partitioning. Performance benefit grows with gradient accumulation steps (more copying between optimizer steps) or GPU count (increased parallelism). + +```yml +{ + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 5e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": 5e8, + "contiguous_gradients": true + "round_robin_gradients": true + } +} +``` + + + + +ZeRO-3 shards the optimizer and gradient states, and parameters across GPUs. Unlike ZeRO-2, ZeRO-3 can also be used for inference in addition to training because it loads large models onto multiple GPUs. Some important parameters to configure include the following. + +* `device: "cpu"` can help if you're running out of GPU memory and if you have free CPU memory available. This offloads model parameters to the CPU. +* `pin_memory: true` can improve throughput, but less memory becomes available for other processes because the pinned memory is reserved for the specific process that requested it and it's typically accessed much faster than normal CPU memory. +* `stage3_max_live_parameters` is the upper limit on how many full parameters to keep on the GPU at any given time. Reduce this value if you encounter an OOM error. +* `stage3_max_reuse_distance` is a value for determining when a parameter is used again in the future, and it helps decide whether to throw the parameter away or to keep it. If the parameter is going to be reused (if the value is less than `stage3_max_reuse_distance`), then it is kept to reduce communication overhead. This is helpful when activation checkpointing is enabled and you want to keep the parameter in the forward recompute until the backward pass. Reduce this value if you encounter an OOM error. +* `stage3_gather_16bit_weights_on_model_save` consolidates fp16 weights when a model is saved. For large models and multiple GPUs, this is expensive in terms of memory and speed. You should enable it if you're planning on resuming training. +* `sub_group_size` controls which parameters are updated during the optimizer step. Parameters are grouped into buckets of `sub_group_size` and each bucket is updated one at a time. When used with NVMe offload, `sub_group_size` determines when model states are moved in and out of CPU memory during the optimization step. This prevents running out of CPU memory for extremely large models. `sub_group_size` can be left to its default value if you aren't using NVMe offload, but you may want to change it if you: + + 1. Run into an OOM error during the optimization step. In this case, reduce `sub_group_size` to reduce memory usage of the temporary buffers. + 2. The optimization step is taking a really long time. In this case, increase `sub_group_size` to improve bandwidth utilization as a result of increased data buffers. + +* `reduce_bucket_size`, `stage3_prefetch_bucket_size`, and `stage3_param_persistence_threshold` are dependent on a models hidden size. It is recommended to set these values to `auto` and allow [`Trainer`] to automatically assign the values. + +```yml +{ + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + } +} +``` + +### Initialize large models + +With ZeRO-3, use the [deepspeed.zero.Init](https://deepspeed.readthedocs.io/en/latest/zero3.html#deepspeed.zero.Init) context manager to initialize a model faster. + +```py +from transformers import T5ForConditionalGeneration, T5Config +import deepspeed + +with deepspeed.zero.Init(): + config = T5Config.from_pretrained("google-t5/t5-small") + model = T5ForConditionalGeneration(config) +``` + +The DeepSped config file needs to have `is_deepspeed_zero3_enabled: true` setup in [`TrainingArguments`] and it needs a ZeRO configuration enabled. The [`TrainingArguments`] object must be created **before** calling [`~PreTrainedModel.from_pretrained`]. + +> [!TIP] +> You'll need ZeRO-3 when the fp16 weights don't fit on a single GPU. But if you're able to load the fp16 weights, set `torch_dtype=torch.float16` in [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import AutoModel, Trainer, TrainingArguments + +training_args = TrainingArguments(..., deepspeed=ds_config) +model = AutoModel.from_pretrained("google-t5/t5-small") +trainer = Trainer(model=model, args=training_args, ...) +``` + +When there are multiple GPUs, no single GPU has all the parameters unless it's the parameters of the currently executing layer. To access all parameters from all the layers at once, such as loading pretrained model weights in [`~PreTrainedModel.from_pretrained`], one layer is loaded at a time and immediately partitioned to all GPUs. For very large models, it isn't possible to load the weights onto one GPU and then distribute them across the other GPUs due to memory limitations. + +If you encounter a model parameter weight where `tensor([1.])` or the parameter size is 1 instead of a larger multidimensional shape, it means the parameter is partitioned and this is a ZeRO-3 placeholder. + +```py +tensor([1.0], device="cuda:0", dtype=torch.float16, requires_grad=True) +``` + +> [!TIP] +> For more information about initializing large models with ZeRO-3 and accessing the parameters, take a look at the [Constructing Massive Models](https://deepspeed.readthedocs.io/en/latest/zero3.html#constructing-massive-models) and [Gathering Parameters](https://deepspeed.readthedocs.io/en/latest/zero3.html#gathering-parameters) guides. + + + + +### NVMe + +[ZeRO-Infinity](https://hf.co/papers/2104.07857) offloads model states to the CPU and/or NVMe to save even more memory. Smart partitioning and tiling algorithms allow each GPU to send and receive very small amounts of data during offloading such that a modern NVMe can fit an even larger total memory pool than is available to your training process. ZeRO-Infinity requires ZeRO-3. + +Depending on the CPU and NVMe memory available, you can offload both the [optimizer states](https://www.deepspeed.ai/docs/config-json/#optimizer-offloading) and [parameters](https://www.deepspeed.ai/docs/config-json/#parameter-offloading), just one of them, or none of them. Make sure the `nvme_path` points to a NVMe device, because while it still works with a regular hard drive or solid state drive, it'll be significantly slower. With a modern NVMe, you can expect peak transfer speeds of ~3.5GB/s for read operations and ~3GB/s for write operations. + +Consider running a [benchmark](https://github.com/microsoft/DeepSpeed/issues/998) on your training setup to determine the optimal `aio` configuration. + +The example ZeRO-3 and ZeRO-Infinity config below sets most of the parameter values to `auto`, but you can also manually set configure these values. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "nvme", + "nvme_path": "/local_nvme", + "pin_memory": true, + "buffer_count": 4, + "fast_init": false + }, + "offload_param": { + "device": "nvme", + "nvme_path": "/local_nvme", + "pin_memory": true, + "buffer_count": 5, + "buffer_size": 1e8, + "max_in_cpu": 1e9 + }, + "aio": { + "block_size": 262144, + "queue_depth": 32, + "thread_count": 1, + "single_submit": false, + "overlap_events": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +``` + +## Training features + +DeepSpeed supports many training features that can be configured in the config file. This section describes some of the most important features. + +### Gradient checkpointing + +Gradient checkpointing saves memory by only storing *some* of the intermediate activations instead of storing *all* of them. It is useful for fitting larger models on the GPU without running out of memory or to increase the batch size for better performance. Training speed is slower though. + +* For a Transformers model, set `model.gradient_checkpointing_enable()` or add `--gradient_checkpointing` in the [`TrainingArguments`]. +* For a non-Transformers model, use the DeepSpeed [Activation Checkpointing API](https://deepspeed.readthedocs.io/en/latest/activation-checkpointing.html). Replacing Transformers modeling code and [torch.utils.checkpoint](https://pytorch.org/docs/stable/checkpoint.html) with the DeepSpeed API gives you more flexibility because you can offload the forward activations to the CPU memory instead of recalculating them. + +### Batch size + +The batch size can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets `train_micro_batch_size_per_gpu` and `train_batch_size` to the value of `world_size * per_device_train_batch_size * gradient_accumulation_steps`. + +```yaml +{ + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto" +} +``` + +### Communication data type + +A separate data type is used for communication collectives like reduction, gathering and scattering operations. + +All gather and scatter operations are performed in the same data type the data is in. For example, if you're training in bf16, the data is also gathered in bf16 because gathering is a non-lossy operation. + +Reduce operations are lossy, for example, when gradients are averaged across multiple GPUs. When the communication is done in fp16 or bf16, it's more likely to be lossy because adding multiple numbers in low precision isn't exact. This is especially the case with bf16 which has a lower precision than fp16. For this reason, fp16 is the default for reduction operations because the loss is minimal when averaging gradients. + +Choose the communication data type by setting the `communication_data_type` parameter in the config file. For example, choosing fp32 adds a small amount of overhead but ensures the reduction operation is accumulated in fp32 and when it is ready, it's downcasted to whichever half-precision data type you're training in. + +```yaml +{ + "communication_data_type": "fp32" +} +``` + +### Gradient accumulation + +Gradient accumulation accumulates gradients over several mini-batches of data before updating parameters. It stores less gradients and enables training with a larger *effective batch size*. Training speed is slower though, but it's useful for overcoming memory constraints. + +Gradient accumulation can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets it to the value of `gradient_accumulation_steps`. + +```yaml +{ + "gradient_accumulation_steps": "auto" +} +``` + +### Gradient clipping + +Gradient clipping is useful for preventing exploding gradients which can lead to instability during training. It sets a maximum threshold value and rescales the gradients if their norm exceeds the threshold. + +Gradient clipping can be automatically configured or manually set. When you choose the `"auto"` option, [`Trainer`] sets it to the value of `max_grad_norm`. + +```yaml +{ + "gradient_clipping": "auto" +} +``` + +### Mixed precision training + +Mixed precision accelerates training speed by performing some calculations in half-precision, but it also maintains some calculations in full-precision to preserve accuracy. DeepSpeed supports fp32, fp16, and bf16 data types. + + + + +Train in fp32 if a model wasn't pretrained in mixed precision because it may cause underflow or overflow errors. Disable fp16, the default, in this case. + +```yaml +{ + "fp16": { + "enabled": false + } +} +``` + +For Ampere GPUs and PyTorch 1.7+, the more efficient [tf32](https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) mode is automatically enabled for some operations but the results are still in fp32. Configure it in [`Trainer`] by setting `--tf32` to enable it, and `--tf32 0` or `--no_tf32` to disable it. + + + + +To configure AMP-like fp16 mixed precision, set up the config as shown below with `"auto"` or your own values. [`Trainer`] automatically enables or disables fp16 based on the value of `fp16_backend`, and the rest of the config can be set by you. fp16 is enabled from the command line when the following arguments are passed: `--fp16`, `--fp16_backend amp` or `--fp16_full_eval`. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + } +} +``` + +For additional DeepSpeed fp16 training options, take a look at the [FP16 Training Options](https://www.deepspeed.ai/docs/config-json/#fp16-training-options) reference. + +To configure Apex-like fp16 mixed precision, set up the config as shown below with `"auto"` or your own values. [`Trainer`] automatically configures `amp` based on the values of `fp16_backend` and `fp16_opt_level`. It can also be enabled from the command line when the following arguments are passed: `--fp16`, `--fp16_backend apex` or `--fp16_opt_level 01`. + +```yaml +{ + "amp": { + "enabled": "auto", + "opt_level": "auto" + } +} +``` + + + + +> [!TIP] +> bf16 requires DeepSpeed 0.6.0. + +bf16 has the same dynamic range as fp32, and doesn’t require loss scaling unlike fp16. However, if you use [gradient accumulation](#gradient-accumulation) with bf16, gradients are accumulated in bf16 which may not be desirable because the lower precision can lead to lossy accumulation. + +bf16 can be set up in the config file or enabled from the command line when the following arguments are passed: `--bf16` or `--bf16_full_eval`. + +```yaml +{ + "bf16": { + "enabled": "auto" + } +} +``` + + + + +### Optimizer and scheduler + +DeepSpeed and Transformers optimizers and schedulers can be mixed and matched if `offload_optimizer` isn't enabled. When `offload_optimizer` is enabled, use a non-DeepSpeed optimizer (except for LAMB) as long as it has it a CPU and GPU implementation. + +Set the optimizer and scheduler parameters for the config file from the command line to avoid hard to find errors. For example, if the learning rate is set to a different value in another place, you can override it from the command line. + + + + +DeepSpeed offers several [optimizers](https://www.deepspeed.ai/docs/config-json/#optimizer-parameters) (Adam, AdamW, OneBitAdam, and LAMB) but you can also import other optimizers from PyTorch. If you don't configure the optimizer in the config, [`Trainer`] automatically selects AdamW and either uses the supplied values or the default values for the following parameters from the command line: `lr`, `adam_beta1`, `adam_beta2`, `adam_epsilon`, `weight_decay`. + +You can set the parameters to `"auto"` or manually input your own values. + +```yaml +{ + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + } +} +``` + +Use an unsupported optimizer by adding the following to the top level configuration. + +```yaml +{ + "zero_allow_untested_optimizer": true +} +``` + +From DeepSpeed 0.8.3+, if you want to use offload, you'll also need to add the following to the top level configuration because offload works best with DeepSpeed's CPU Adam optimizer. + +```yaml +{ + "zero_force_ds_cpu_optimizer": false +} +``` + + + + +DeepSpeed supports the LRRangeTest, OneCycle, WarmupLR and WarmupDecayLR learning rate [schedulers](https://www.deepspeed.ai/docs/config-json/#scheduler-parameters). + +Transformers and DeepSpeed provide two of the same schedulers: + +* WarmupLR is the same as `--lr_scheduler_type constant_with_warmup` in Transformers. +* WarmupDecayLR is the same as `--lr_scheduler_type linear` in Transformers (this is the default scheduler used in Transformers). + +If you don't configure the scheduler in the config file, [`Trainer`] automatically selects WarmupDecayLR and either uses the supplied values or the default values for the following parameters from the command line: `warmup_min_lr`, `warmup_max_lr`, `warmup_num_steps`, `total_num_steps` (automatically calculated during run time if `max_steps` is not provided). + +You can set the parameters to `"auto"` or manually input your own values. + +```yaml +{ + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "total_num_steps": "auto", + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + } +} +``` + + + + +### Universal checkpointing + +[Universal Checkpointing](https://www.deepspeed.ai/tutorials/universal-checkpointing) saves and loads model, optimizer and training scheduler states across different model architectures, parallelism techniques, and training configurations. By saving them in a Universal format, it enables easier model training continuation and fine-tuning. + +Resume training with a Universal checkpoint by setting `load_universal` to `true` in the config file. + +```yaml +{ + "checkpoint": { + "load_universal": true + } +} +``` + +## Deploy + +DeepSpeed can be deployed with its native launcher, [torchrun](https://pytorch.org/docs/stable/elastic/run.html) or [Accelerate](https://huggingface.co/docs/accelerate/basic_tutorials/launch#using-accelerate-launch). + +Add the `--deepspeed ds_config.json` argument to [`Trainer`] in the command line. It is recommended to use DeepSpeeds [add_config_arguments](https://deepspeed.readthedocs.io/en/latest/initialize.html#argument-parsing) utility to add any other command line arguments to your code. + + + + +To deploy DeepSpeed on multiple GPUs, add `--num_gpus`. You don't need to add `--num_gpus` if you're planning on using all available GPUs. + +```bash +deepspeed --num_gpus=2 examples/pytorch/translation/run_translation.py \ +--deepspeed tests/deepspeed/ds_config_zero3.json \ +--model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ +--output_dir output_dir --overwrite_output_dir --fp16 \ +--do_train --max_train_samples 500 --num_train_epochs 1 \ +--dataset_name wmt16 --dataset_config "ro-en" \ +--source_lang en --target_lang ro +``` + + + + +DeepSpeed is still useful with just one GPU because you can: + +1. Offload some computations and memory to the CPU to make more GPU resources available to your model to use a larger batch size or fit a very large model that normally won't fit. +2. Minimize memory fragmentation with its smart GPU memory management system which also allows you to fit bigger models and data batches. + +To deploy DeepSpeed on a single GPU, add `--num_gpus`. You don't need to add `--num_gpus` if you only have one GPU because DeepSpeed deploys all GPUs it can see on a given node. + +> [!TIP] +> Set the `allgather_bucket_size` and `reduce_bucket_size` values to 2e8 in the [ZeRO-2](#zero-configuration) configuration file to get better performance on a single GPU. + +```bash +deepspeed --num_gpus=1 examples/pytorch/translation/run_translation.py \ +--deepspeed tests/deepspeed/ds_config_zero2.json \ +--model_name_or_path google-t5/t5-small --per_device_train_batch_size 1 \ +--output_dir output_dir --overwrite_output_dir --fp16 \ +--do_train --max_train_samples 500 --num_train_epochs 1 \ +--dataset_name wmt16 --dataset_config "ro-en" \ +--source_lang en --target_lang ro +``` + + + + +### Multi-node + +A multi-node setup consists of multiple nodes, where each node has one of more GPUs running a workload. DeepSpeed expects a shared storage system, but if this is not the case, you need to adjust the config file to include a [checkpoint](https://www.deepspeed.ai/docs/config-json/#checkpoint-options) to allow loading without access to a shared filesystem. + +```yaml +{ + "checkpoint": { + "use_node_local_storage": true + } +} +``` + +You could also use the `--save_on_each_node` parameter in [`TrainingArguments`] to automatically add the above `checkpoint` to your config. + +The examples below for the torchrun and DeepSpeed launcher shows how to deploy two nodes with eight GPUs each. Access the first node with `ssh hostname1` and the second node with `ssh hostname2`. Both nodes must be able to communicate with each other locally over ssh without a password. + + + + +With [torchrun](https://pytorch.org/docs/stable/elastic/run.html), ssh to each node and run the following command on both of them. The launcher waits until both nodes are synchronized before launching the training. + +```bash +torchrun --nproc_per_node=8 --nnode=2 --node_rank=0 --master_addr=hostname1 \ +--master_port=9901 your_program.py --deepspeed ds_config.json +``` + + + + +Create a `hostfile` for the DeepSpeed launcher. + +```bash +hostname1 slots=8 +hostname2 slots=8 +``` + +The DeepSpeed launcher automatically launches the command on both nodes at once with the command below. + +```bash +deepspeed --num_gpus 8 --num_nodes 2 --hostfile hostfile --master_addr hostname1 --master_port=9901 \ +your_program.py --deepspeed ds_config.json +``` + +Check out the [Resource Configuration (multi-node)](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) guide for more details about configuring multi-node compute resources. + + + + +### Slurm + +[Slurm](https://slurm.schedmd.com/documentation.html) is a cluster management and job scheduling system. An example Slurm script is shown below. + +```bash +#SBATCH --job-name=test-nodes # name +#SBATCH --nodes=2 # nodes +#SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! +#SBATCH --cpus-per-task=10 # number of cores per tasks +#SBATCH --gres=gpu:8 # number of gpus +#SBATCH --time 20:00:00 # maximum execution time (HH:MM:SS) +#SBATCH --output=%x-%j.out # output file name + +export GPUS_PER_NODE=8 +export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) +export MASTER_PORT=9901 + +srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ + --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ + --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ +your_program.py --deepspeed ds_config.json' +``` + +Launch training simultaneously on all nodes with the command below. + +```bash +sbatch launch.slurm +``` + +### Jupyter Notebook + +To use DeepSpeed in a Jupyter Notebook, you need to emulate a distributed environment because the launcher doesn't support deployment from a notebook. This is only supported for one GPU. To use multiple GPUs, you must use a multi-process environment, which means you have to use the DeepSpeed launcher which can't be emulated as shown here. + +```py +# emulate a launcher in the notebook +import os + +os.environ["MASTER_ADDR"] = "localhost" +os.environ["MASTER_PORT"] = "9994" # modify if RuntimeError: Address already in use +os.environ["RANK"] = "0" +os.environ["LOCAL_RANK"] = "0" +os.environ["WORLD_SIZE"] = "1" + +training_args = TrainingArguments(..., deepspeed="ds_config_zero3.json") +trainer = Trainer(...) +trainer.train() +``` + +Create a config file on the fly in the notebook in the current directory with a dedicated cell. + +```py +%%bash +cat <<'EOT' > ds_config_zero3.json +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +EOT +``` + +If the training script is in a file and not a notebook cell, launch DeepSpeed from the shell in the notebook cell. + +```py +!git clone https://github.com/huggingface/transformers +!cd transformers; deepspeed examples/pytorch/translation/run_translation.py ... +``` + +Another option is to use `%%bash` to run the shell program without emulating the distributed environment. However, you won't be able to view the logs until training is complete. + +```py +%%bash + +git clone https://github.com/huggingface/transformers +cd transformers +deepspeed examples/pytorch/translation/run_translation.py ... +``` + +## Save model weights + +DeepSpeed stores the main fp32 weights in custom checkpoint optimizer files (`global_step*/*optim_states.pt`) which are saved under the normal checkpoint. + +### fp16 + +ZeRO-2 saves the model weights in fp16. To save the weights in fp16 for ZeRO-3, set `"stage3_gather_16bit_weights_on_model_save": true` in the config file, because the weights are distributed across multiple GPUs. + +If you don't, [`Trainer`] won't save the weights in fp16 and won't create a `pytorch_model.bin` file. This is because DeepSpeed's state_dict contains a placeholder instead of the real weights, so you won't be able to load it. + +```yaml +{ + "zero_optimization": { + "stage": 3, + "stage3_gather_16bit_weights_on_model_save": true + } +} +``` + +### fp32 + +Unless you have a lot of free CPU memory, fp32 weights shouldn't be saved during training because it can require a lot of memory. It is usually best to save the fp32 weights offline after training is complete. + + + + +DeepSpeed provides a [zero_to_fp32.py](https://github.com/microsoft/DeepSpeed/blob/91829476a8fd4d0d9268c03c1d56795d20a51c12/deepspeed/utils/zero_to_fp32.py#L14) script at the top-level checkpoint folder for extracting weights at any point. This is a standalone script and you don't need a config file or [`Trainer`]. + +For example, if your checkpoint folder looks like the one shown below, then you can run the following command to create and consolidate the fp32 weights from multiple GPUs into a single `pytorch_model.bin` file. The script automatically discovers the subfolder `global_step1` which contains the checkpoint. + +```bash +$ ls -l output_dir/checkpoint-1/ +-rw-rw-r-- 1 stas stas 1.4K Mar 27 20:42 config.json +drwxrwxr-x 2 stas stas 4.0K Mar 25 19:52 global_step1/ +-rw-rw-r-- 1 stas stas 12 Mar 27 13:16 latest +-rw-rw-r-- 1 stas stas 827K Mar 27 20:42 optimizer.pt +-rw-rw-r-- 1 stas stas 231M Mar 27 20:42 pytorch_model.bin +-rw-rw-r-- 1 stas stas 623 Mar 27 20:42 scheduler.pt +-rw-rw-r-- 1 stas stas 1.8K Mar 27 20:42 special_tokens_map.json +-rw-rw-r-- 1 stas stas 774K Mar 27 20:42 spiece.model +-rw-rw-r-- 1 stas stas 1.9K Mar 27 20:42 tokenizer_config.json +-rw-rw-r-- 1 stas stas 339 Mar 27 20:42 trainer_state.json +-rw-rw-r-- 1 stas stas 2.3K Mar 27 20:42 training_args.bin +-rwxrw-r-- 1 stas stas 5.5K Mar 27 13:16 zero_to_fp32.py* +``` + +> [!TIP] +> Run `python zero_to_fp32.py -h` for more usage details. The script requires 2x the general RAM of the final fp32 weights. + +```bash +python zero_to_fp32.py . pytorch_model.bin +``` + + + + +Adding the `--load_best_model_at_end` parameter in [`TrainingArguments`] tracks the best checkpoint so you can finish training first and save the final model explicitly. Reload the model as shown below. + +> [!WARNING] +> Once [load_state_dict_from_zero_checkpoint](https://deepspeed.readthedocs.io/en/stable/model-checkpointing.html#deepspeed.utils.zero_to_fp32.load_state_dict_from_zero_checkpoint) is run, the model is no longer usable in DeepSpeed in the context of the same application. You'll need to reinitialize the DeepSpeed engine because `model.load_state_dict(state_dict)` removes all the DeepSpeed magic from it. Only use this function once training is complete. + +```py +from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint + +checkpoint_dir = os.path.join(trainer.args.output_dir, "checkpoint-final") +trainer.deepspeed.save_checkpoint(checkpoint_dir) +fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) +``` + +You must have saved at least one checkpoint to load the latest checkpoint as shown in the example below. + +```py +from transformers.trainer_utils import get_last_checkpoint +from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint + +checkpoint_dir = get_last_checkpoint(trainer.args.output_dir) +fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) +``` + +Use `load_state_dict` to extract and load the state_dict of the fp32 weights. + +```py +from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint + +state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) +model = model.cpu() +model.load_state_dict(state_dict) +``` + + + + +## Non-Trainer integration + +DeepSpeed also works with Transformers without [`Trainer`]. The [`~integrations.HfDeepSpeedConfig`] is responsible for gathering ZeRO-3 parameters and partitioning a model across multiple GPUs when [`~PreTrainedModel.from_pretrained`] is called. + +You must instantiate [`~integrations.HfDeepSpeedConfig`] before loading a model to efficiently deploy ZeRO-3. + + + + +```py +from transformers.integrations import HfDeepSpeedConfig +from transformers import AutoModel +import deepspeed + +# DeepSpeed config object or path to the file +ds_config = {...} +# must run before instantiating the model to detect ZeRO-3 +dschf = HfDeepSpeedConfig(ds_config) # keep this object alive +model = AutoModel.from_pretrained("openai-community/gpt2") +engine = deepspeed.initialize(model=model, config_params=ds_config, ...) +``` + + + + +[`~integrations.HfDeepSpeedConfig`] is not required for ZeRO-1 or ZeRO-2. + +```py +from transformers.integrations import HfDeepSpeedConfig +from transformers import AutoModel, AutoConfig +import deepspeed + +# DeepSpeed config object or path to the file +ds_config = {...} +# must run before instantiating the model to detect zero 3 +dschf = HfDeepSpeedConfig(ds_config) # keep this object alive +# randomly initialize model weights +config = AutoConfig.from_pretrained("openai-community/gpt2") +model = AutoModel.from_config(config) +engine = deepspeed.initialize(model=model, config_params=ds_config, ...) +``` + + + + +## Troubleshoot + +One of the first things to check when you encounter an error is whether DeepSpeed is the cause (because often it isn't). Retry your setup without DeepSpeed, and if the error persists, report the issue. If the issue is unrelated to the Transformers integration, please open the issue on the DeepSpeed [repository](https://github.com/microsoft/DeepSpeed). + +For issues related to the Transformers integration, please provide the following information. + +* The full DeepSpeed config file. +* The command line arguments for [`Trainer`] or the [`TrainingArguments`] if you're scripting the [`Trainer`] setup yourself (don't dump the entire [`TrainingArguments`] which contains many irrelevant entries). +* The outputs of the following commands. + + ```bash + python -c 'import torch; print(f"torch: {torch.__version__}")' + python -c 'import transformers; print(f"transformers: {transformers.__version__}")' + python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")' + ``` + +* A link to a Google Colab notebook to reproduce the issue. +* A standard or non-custom dataset or an existing example to reproduce the issue. + +The following sections provide a guide for resolving two of the most common issues. + +### Process killed at startup + +When the DeepSpeed process is killed during launch without a traceback, that usually means the program tried to allocate more CPU memory than is available on your system. Or the process may have tried to allocate more CPU memory than allowed, leading the OS kernel to terminate the process. + +In this case, check whether your config file has either `offload_optimizer`, `offlload_param`, or both configured to offload to the CPU. + +If you have NVM3 and ZeRO-3 set up, experiment with offloading to the NVMe ([estimate](https://deepspeed.readthedocs.io/en/latest/memory.html) the memory requirements of a model first) instead. + +### NaN loss + +NaN loss often occurs when a model is pretrained in bf16 and you try to use it with fp16 (especially relevant to TPU trained models). To resolve this, use fp32 or bf16 if your hardware (TPUs, Ampere GPUs or newer) supports it. + +It is also possible that fp16 is causing overflow. For example, if your config file looks like the one below, you may see the following overflow errors in the logs. + +```yaml +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + } +} +``` + +The `OVERFLOW!` error below is a result of the DeepSpeed loss scaler unable to find a scaling coefficient to overcome the loss overflow. Try a higher `initial_scale_power` value in this case (32 usually works). + +```bash +0%| | 0/189 [00:00 + +# ExecuTorch + +[ExecuTorch](https://pytorch.org/executorch/stable/index.html) is a platform that enables PyTorch training and inference programs to be run on mobile and edge devices. It is powered by [torch.compile](https://pytorch.org/docs/stable/torch.compiler.html) and [torch.export](https://pytorch.org/docs/main/export.html) for performance and deployment. + +You can use ExecuTorch with Transformers with [torch.export](https://pytorch.org/docs/main/export.html). The [`~transformers.convert_and_export_with_cache`] method converts a [`PreTrainedModel`] into an exportable module. Under the hood, it uses [torch.export](https://pytorch.org/docs/main/export.html) to export the model, ensuring compatibility with ExecuTorch. + +```py +import torch +from transformers import LlamaForCausalLM, AutoTokenizer, GenerationConfig +from transformers.integrations.executorch import( + TorchExportableModuleWithStaticCache, + convert_and_export_with_cache +) + +generation_config = GenerationConfig( + use_cache=True, + cache_implementation="static", + cache_config={ + "batch_size": 1, + "max_cache_len": 20, + } +) + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B", pad_token="", padding_side="right") +model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B", device_map="auto", torch_dtype=torch.bfloat16, attn_implementation="sdpa", generation_config=generation_config) + +exported_program = convert_and_export_with_cache(model) +``` + +The exported PyTorch model is now ready to be used with ExecuTorch. Wrap the model with [`~transformers.TorchExportableModuleWithStaticCache`] to generate text. + +```py +prompts = ["Simply put, the theory of relativity states that "] +prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) +prompt_token_ids = prompt_tokens["input_ids"] + +generated_ids = TorchExportableModuleWithStaticCache.generate( + exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=20, +) +generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +print(generated_text) +['Simply put, the theory of relativity states that 1) the speed of light is the'] +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fast_tokenizers.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fast_tokenizers.md new file mode 100644 index 0000000000000000000000000000000000000000..921c0ba7b6f588fe6896b1016d7e1c9f1a24c5e1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fast_tokenizers.md @@ -0,0 +1,362 @@ + + +# Tokenizers + +Tokenizers convert text into an array of numbers known as tensors, the inputs to a text model. There are several tokenizer algorithms, but they all share the same purpose. Split text into smaller words or subwords (tokens) according to some rules, and convert them into numbers (input ids). A Transformers tokenizer also returns an attention mask to indicate which tokens should be attended to. + +> [!TIP] +> Learn about the most popular tokenization algorithms on the [Summary of the tokenizers](./tokenizer_summary) doc. + +Call [`~PreTrainedTokenizer.from_pretrained`] to load a tokenizer and its configuration from the Hugging Face [Hub](https://hf.co) or a local directory. The pretrained tokenizer is saved in a [tokenizer.model](https://huggingface.co/google/gemma-2-2b/blob/main/tokenizer.model) file with all its associated vocabulary files. + +Pass a string of text to the tokenizer to return the input ids and attention mask, and set the framework tensor type to return with the `return_tensors` parameter. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +Whichever tokenizer you use, make sure the tokenizer vocabulary is the same as the pretrained models tokenizer vocabulary. This is especially important if you're using a custom tokenizer with a different vocabulary from the pretrained models tokenizer. + +This guide provides a brief overview of the tokenizer classes and how to preprocess text with it. + +## Tokenizer classes + +All tokenizers inherit from a [`PreTrainedTokenizerBase`] class that provides common methods for all tokenizers like [`~PreTrainedTokenizerBase.from_pretrained`] and [`~PreTrainedTokenizerBase.batch_decode`]. There are two main tokenizer classes that build on top of the base class. + +- [`PreTrainedTokenizer`] is a Python implementation, for example [`LlamaTokenizer`]. +- [`PreTrainedTokenizerFast`] is a fast Rust-based implementation from the [Tokenizers](https://hf.co/docs/tokenizers/index) library, for example [`LlamaTokenizerFast`]. + +There are two ways you can load a tokenizer, with [`AutoTokenizer`] or a model-specific tokenizer. + + + + +The [AutoClass](./model_doc/auto) API is a fast and easy way to load a tokenizer without needing to know whether a Python or Rust-based implementation is available. By default, [`AutoTokenizer`] tries to load a fast tokenizer if it's available, otherwise, it loads the Python implementation. + +Use [`~PreTrainedTokenizer.from_pretrained`] to load a tokenizer. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +Load your own tokenizer by passing its vocabulary file to [`~AutoTokenizer.from_pretrained`]. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("./model_directory/my_vocab_file.txt") +``` + + + + +Each pretrained model is associated with a tokenizer and the specific vocabulary it was trained on. A tokenizer can be loaded directly from the model-specific class. + +> [!TIP] +> Refer to a models API documentation to check whether a fast tokenizer is supported. + +```py +from transformers import GemmaTokenizer + +tokenizer = GemmaTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +``` + +To load a fast tokenizer, use the fast implementation class. + +```py +from transformers import GemmaTokenizerFast + +tokenizer = GemmaTokenizerFast.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +``` + +Load your own tokenizer by passing its vocabulary file to the `vocab_file` parameter. + +```py +from transformers import GemmaTokenizerFast + +tokenizer = GemmaTokenizerFast(vocab_file="my_vocab_file.txt") +``` + + + + +## Multimodal tokenizers + +In addition to text tokens, multimodal tokenizers also holds tokens from other modalities as a part of its attributes for easy access. + +To add these special tokens to a tokenizer, pass them as a dictionary to the `extra_special_tokens` parameter in [`~AutoTokenizer.from_pretrained`]. The example below adds the `image_token` to a vision-language model. + +Save the tokenizer so you can reuse it with direct access to the `image_token`, `boi_token`, and `eoi_token`. + +```py +vision_tokenizer = AutoTokenizer.from_pretrained( + "llava-hf/llava-1.5-7b-hf", + extra_special_tokens={"image_token": "", "boi_token": "", "eoi_token": ""} +) +print(vision_tokenizer.image_token, vision_tokenizer.image_token_id) +("", 32000) + +vision_tokenizer.save_pretrained("./path/to/tokenizer") +``` + +## Fast tokenizers + + + +[`PreTrainedTokenizerFast`] or *fast tokenizers* are Rust-based tokenizers from the [Tokenizers](https://hf.co/docs/tokenizers) library. It is significantly faster at batched tokenization and provides additional alignment methods compared to the Python-based tokenizers. + +[`AutoTokenizer`] automatically loads a fast tokenizer if it's supported. Otherwise, you need to explicitly load the fast tokenizer. + +This section will show you how to train a fast tokenizer and reuse it in Transformers. + +To train a Byte-Pair Encoding (BPE) tokenizer, create a [`~tokenizers.Tokenizer`] and [`~tokenizers.trainers.BpeTrainer`] class and define the unknown token and special tokens. + +```py +from tokenizers import Tokenizer +from tokenizers.models import BPE +from tokenizers.trainers import BpeTrainer + +tokenizer = Tokenizer(BPE(unk_token="[UNK]")) +trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) +``` + +Split the tokens on [`~tokenizers.pre_tokenizers.Whitespace`] to create tokens that don't overlap with each other. + +```py +from tokenizers.pre_tokenizers import Whitespace + +tokenizer.pre_tokenizer = Whitespace() +``` + +Call [`~tokenizers.Tokenizer.train`] on the text files and trainer to start training. + +```py +files = [...] +tokenizer.train(files, trainer) +``` + +Use [`~tokenizers.Tokenizer.save`] to save the tokenizers configuration and vocabulary to a JSON file. + +```py +tokenizer.save("tokenizer.json") +``` + +Now you can load and reuse the tokenizer object in Transformers by passing it to the `tokenizer_object` parameter in [`PreTrainedTokenizerFast`]. + +```py +from transformers import PreTrainedTokenizerFast + +fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) +``` + +To load a saved tokenizer from its JSON file, pass the file path to the `tokenizer_file` parameter in [`PreTrainedTokenizerFast`]. + +```py +from transformers import PreTrainedTokenizerFast + +fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json") +``` + +## tiktoken + +[tiktoken](https://github.com/openai/tiktoken) is a [byte-pair encoding (BPE)](./tokenizer_summary#byte-pair-encoding-bpe) tokenizer by OpenAI. It includes several tokenization schemes or encodings for how text should be tokenized. + +There are currently two models trained and released with tiktoken, GPT2 and Llama3. Transformers supports models with a [tokenizer.model](https://hf.co/meta-llama/Meta-Llama-3-8B/blob/main/original/tokenizer.model) tiktoken file. The tiktoken file is automatically converted into Transformers Rust-based [`PreTrainedTokenizerFast`]. + +Add the `subfolder` parameter to [`~PreTrainedModel.from_pretrained`] to specify where the `tokenizer.model` tiktoken file is located. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", subfolder="original") +``` + +### Create a tiktoken tokenizer + +The tiktoken `tokenizer.model` file contains no information about additional tokens or pattern strings. If these are important, convert the tokenizer to `tokenizer.json` (the appropriate format for [`PreTrainedTokenizerFast`]). + +Generate the tiktoken `tokenizer.model` file with the [tiktoken.get_encoding](https://github.com/openai/tiktoken/blob/63527649963def8c759b0f91f2eb69a40934e468/tiktoken/registry.py#L63) function, and convert it to `tokenizer.json` with [convert_tiktoken_to_fast](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/integrations/tiktoken.py#L8). + +```py +from transformers.integrations.tiktoken import convert_tiktoken_to_fast +from tiktoken import get_encoding + +# Load your custom encoding or the one provided by OpenAI +encoding = get_encoding("gpt2") +convert_tiktoken_to_fast(encoding, "config/save/dir") +``` + +The resulting `tokenizer.json` file is saved to the specified directory and loaded with [`~PreTrainedTokenizerFast.from_pretrained`]. + +```py +tokenizer = PreTrainedTokenizerFast.from_pretrained("config/save/dir") +``` + +## Preprocess + + + +A Transformers model expects the input to be a PyTorch, TensorFlow, or NumPy tensor. A tokenizers job is to preprocess text into those tensors. Specify the framework tensor type to return with the `return_tensors` parameter. + +```py +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b") +tokenizer("We are very happy to show you the 🤗 Transformers library.", return_tensors="pt") +{'input_ids': tensor([[ 2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, + 156808, 128149, 9581, 235265]]), + 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) +} +``` + +The tokenization process of converting text into input ids is completed in two steps. + + + + +In the first step, a string of text is split into tokens by the [`~PreTrainedTokenizer.tokenize`] function. How the text is split depends on the tokenization algorithm. + +```py +tokens = tokenizer.tokenize("We are very happy to show you the 🤗 Transformers library") +print(tokens) +['We', '▁are', '▁very', '▁happy', '▁to', '▁show', '▁you', '▁the', '▁🤗', '▁Transformers', '▁library'] +``` + +Gemma uses a [SentencePiece](./tokenizer_summary#sentencepiece) tokenizer which replaces spaces with an underscore `_`. + + + + +In the second step, the tokens are converted into ids with [`~PreTrainedTokenizer.convert_tokens_to_ids`]. + +```py +ids = tokenizer.convert_tokens_to_ids(tokens) +print(ids) +[1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +``` + + + + +Lastly, the model prediction typically generates numerical outputs which are converted back to text with [`~PreTrainedTokenizer.decode`]. + +```py +decoded_string = tokenizer.decode(ids) +print(decoded_string) +'We are very happy to show you the 🤗 Transformers library' +``` + + + + +> [!TIP] +> Visualize how different tokenizers work in the [Tokenizer Playground](https://xenova-the-tokenizer-playground.static.hf.space). + +### Special tokens + +Special tokens provide the model with some additional information about the text. + +For example, if you compare the tokens obtained from passing text directly to the tokenizer and from [`~PreTrainedTokenizer.convert_tokens_to_ids`], you'll notice some additional tokens are added. + +```py +model_inputs = tokenizer("We are very happy to show you the 🤗 Transformers library.") +[2, 1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +tokenizer.convert_tokens_to_ids(tokens) +[1734, 708, 1508, 4915, 577, 1500, 692, 573, 156808, 128149, 9581] +``` + +When you [`~PreTrainedTokenizer.decode`] the ids, you'll see `` at the beginning of the string. This is used to indicate the beginning of a sentence to the model. + +```py +print(tokenizer.decode(model_inputs["input_ids"])) +print(tokenizer.decode(ids)) +'We are very happy to show you the 🤗 Transformers library.' +'We are very happy to show you the 🤗 Transformers library' +``` + +Not all models need special tokens, but if they do, a tokenizer automatically adds them. + +### Batch tokenization + +It is faster and more efficient to preprocess *batches* of text instead of a single sentence at a time. Fast tokenizers are especially good at parallelizing tokenization. + +Pass a list of string text to the tokenizer. + +```py +batch_sentences = [ + "But what about second breakfast?", + "Don't think he knows about second breakfast, Pip.", + "What about elevensies?", +] +encoded_inputs = tokenizer(batch_sentences, return_tensors="pt") +print(encoded_inputs) +{ + 'input_ids': + [[2, 1860, 1212, 1105, 2257, 14457, 235336], + [2, 4454, 235303, 235251, 1742, 693, 9242, 1105, 2257, 14457, 235269, 48782, 235265], + [2, 1841, 1105, 29754, 37453, 235336]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1]] +} +``` + +### Padding + +> [!TIP] +> Learn about additional padding strategies in the [Padding and truncation](./pad_truncation) guide. + +In the output above, the `input_ids` have different lengths. This is an issue because Transformers expects them to have the same lengths so it can pack them into a batch. Sequences with uneven lengths can't be batched. + +Padding adds a special *padding token* to ensure all sequences have the same length. Set `padding=True` to pad the sequences to the longest sequence length in the batch. + +```py +encoded_inputs = tokenizer(batch_sentences, padding=True, return_tensors="pt") +print(encoded_inputs) +``` + +The tokenizer added the special padding token `0` to the left side (*left padding*) because Gemma and LLMs in general are not trained to continue generation from a padding token. + +### Truncation + +> [!TIP] +> Learn about additional truncation strategies in the [Padding and truncation](./pad_truncation) guide. + +Models are only able to process sequences up to a certain length. If you try to process a sequence longer than a model can handle, it crashes. + +Truncation removes tokens from a sequence to ensure it doesn't exceed the maximum length. Set `truncation=True` to truncate a sequence to the maximum length accepted by the model. You can also set the maximum length yourself with the `max_length` parameter. + +```py +encoded_inputs = tokenizer(batch_sentences, max_length=8, truncation=True, return_tensors="pt") +print(encoded_inputs) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/feature_extractors.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/feature_extractors.md new file mode 100644 index 0000000000000000000000000000000000000000..6cc202057697773840dac7fd8b05ead2c22acc2e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/feature_extractors.md @@ -0,0 +1,199 @@ + + +# Feature extractors + +Feature extractors preprocess audio data into the correct format for a given model. It takes the raw audio signal and converts it into a tensor that can be fed to a model. The tensor shape depends on the model, but the feature extractor will correctly preprocess the audio data for you given the model you're using. Feature extractors also include methods for padding, truncation, and resampling. + +Call [`~AutoFeatureExtractor.from_pretrained`] to load a feature extractor and its preprocessor configuration from the Hugging Face [Hub](https://hf.co/models) or local directory. The feature extractor and preprocessor configuration is saved in a [preprocessor_config.json](https://hf.co/openai/whisper-tiny/blob/main/preprocessor_config.json) file. + +Pass the audio signal, typically stored in `array`, to the feature extractor and set the `sampling_rate` parameter to the pretrained audio models sampling rate. It is important the sampling rate of the audio data matches the sampling rate of the data a pretrained audio model was trained on. + +```py +from transformers import AutoFeatureExtractor + +feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +processed_sample = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=16000) +processed_sample +{'input_values': [array([ 9.4472744e-05, 3.0777880e-03, -2.8888427e-03, ..., + -2.8888427e-03, 9.4472744e-05, 9.4472744e-05], dtype=float32)]} +``` + +The feature extractor returns an input, `input_values`, that is ready for the model to consume. + +This guide walks you through the feature extractor classes and how to preprocess audio data. + +## Feature extractor classes + +Transformers feature extractors inherit from the base [`SequenceFeatureExtractor`] class which subclasses [`FeatureExtractionMixin`]. + +- [`SequenceFeatureExtractor`] provides a method to [`~SequenceFeatureExtractor.pad`] sequences to a certain length to avoid uneven sequence lengths. +- [`FeatureExtractionMixin`] provides [`~FeatureExtractionMixin.from_pretrained`] and [`~FeatureExtractionMixin.save_pretrained`] to load and save a feature extractor. + +There are two ways you can load a feature extractor, [`AutoFeatureExtractor`] and a model-specific feature extractor class. + + + + +The [AutoClass](./model_doc/auto) API automatically loads the correct feature extractor for a given model. + +Use [`~AutoFeatureExtractor.from_pretrained`] to load a feature extractor. + +```py +from transformers import AutoFeatureExtractor + +feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-tiny") +``` + + + + +Every pretrained audio model has a specific associated feature extractor for correctly processing audio data. When you load a feature extractor, it retrieves the feature extractors configuration (feature size, chunk length, etc.) from [preprocessor_config.json](https://hf.co/openai/whisper-tiny/blob/main/preprocessor_config.json). + +A feature extractor can be loaded directly from its model-specific class. + +```py +from transformers import WhisperFeatureExtractor + +feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-tiny") +``` + + + + +## Preprocess + +A feature extractor expects the input as a PyTorch tensor of a certain shape. The exact input shape can vary depending on the specific audio model you're using. + +For example, [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper) expects `input_features` to be a tensor of shape `(batch_size, feature_size, sequence_length)` but [Wav2Vec2](https://hf.co/docs/transformers/model_doc/wav2vec2) expects `input_values` to be a tensor of shape `(batch_size, sequence_length)`. + +The feature extractor generates the correct input shape for whichever audio model you're using. + +A feature extractor also sets the sampling rate (the number of audio signal values taken per second) of the audio files. The sampling rate of your audio data must match the sampling rate of the dataset a pretrained model was trained on. This value is typically given in the model card. + +Load a dataset and feature extractor with [`~FeatureExtractionMixin.from_pretrained`]. + +```py +from datasets import load_dataset, Audio +from transformers import AutoFeatureExtractor + +dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") +feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") +``` + +Check out the first example from the dataset and access the `audio` column which contains `array`, the raw audio signal. + +```py +dataset[0]["audio"]["array"] +array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ]) +``` + +The feature extractor preprocesses `array` into the expected input format for a given audio model. Use the `sampling_rate` parameter to set the appropriate sampling rate. + +```py +processed_dataset = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=16000) +processed_dataset +{'input_values': [array([ 9.4472744e-05, 3.0777880e-03, -2.8888427e-03, ..., + -2.8888427e-03, 9.4472744e-05, 9.4472744e-05], dtype=float32)]} +``` + +### Padding + +Audio sequence lengths that are different is an issue because Transformers expects all sequences to have the same lengths so they can be batched. Uneven sequence lengths can't be batched. + +```py +dataset[0]["audio"]["array"].shape +(86699,) + +dataset[1]["audio"]["array"].shape +(53248,) +``` + +Padding adds a special *padding token* to ensure all sequences have the same length. The feature extractor adds a `0` - interpreted as silence - to `array` to pad it. Set `padding=True` to pad sequences to the longest sequence length in the batch. + +```py +def preprocess_function(examples): + audio_arrays = [x["array"] for x in examples["audio"]] + inputs = feature_extractor( + audio_arrays, + sampling_rate=16000, + padding=True, + ) + return inputs + +processed_dataset = preprocess_function(dataset[:5]) +processed_dataset["input_values"][0].shape +(86699,) + +processed_dataset["input_values"][1].shape +(86699,) +``` + +### Truncation + +Models can only process sequences up to a certain length before crashing. + +Truncation is a strategy for removing excess tokens from a sequence to ensure it doesn't exceed the maximum length. Set `truncation=True` to truncate a sequence to the length in the `max_length` parameter. + +```py +def preprocess_function(examples): + audio_arrays = [x["array"] for x in examples["audio"]] + inputs = feature_extractor( + audio_arrays, + sampling_rate=16000, + max_length=50000, + truncation=True, + ) + return inputs + +processed_dataset = preprocess_function(dataset[:5]) +processed_dataset["input_values"][0].shape +(50000,) + +processed_dataset["input_values"][1].shape +(50000,) +``` + +### Resampling + +The [Datasets](https://hf.co/docs/datasets/index) library can also resample audio data to match an audio models expected sampling rate. This method resamples the audio data on the fly when they're loaded which can be faster than resampling the entire dataset in-place. + +The audio dataset you've been working on has a sampling rate of 8kHz and the pretrained model expects 16kHz. + +```py +dataset[0]["audio"] +{'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, + 0. , 0. ]), + 'sampling_rate': 8000} +``` + +Call [`~datasets.Dataset.cast_column`] on the `audio` column to upsample the sampling rate to 16kHz. + +```py +dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) +``` + +When you load the dataset sample, it is now resampled to 16kHz. + +```py +dataset[0]["audio"] +{'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', + 'array': array([ 1.70562416e-05, 2.18727451e-04, 2.28099874e-04, ..., + 3.43842403e-05, -5.96364771e-06, -1.76846661e-05]), + 'sampling_rate': 16000} +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fsdp.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..944c5a18e109356195fd4b5eb2cf176174af9693 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/fsdp.md @@ -0,0 +1,145 @@ + + +# FullyShardedDataParallel + +[Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) is a [parallelism](./perf_train_gpu_many) method that combines the advantages of data and model parallelism for distributed training. + +Unlike [DistributedDataParallel (DDP)](./perf_train_gpu_many#distributeddataparallel), FSDP saves more memory because it doesn't replicate a model on each GPU. It shards the models parameters, gradients and optimizer states across GPUs. Each model shard processes a portion of the data and the results are synchronized to speed up training. + +This guide covers how to set up training a model with FSDP and [Accelerate](https://hf.co/docs/accelerate/index), a library for managing distributed training. + +```bash +pip install accelerate +``` + +## Configuration options + +Always start by running the [accelerate config](https://hf.co/docs/accelerate/package_reference/cli#accelerate-config) command to help Accelerate set up the correct distributed training environment. + +```bash +accelerate config +``` + +The section below discusses some of the more important FSDP configuration options. Learn more about other available options in the [fsdp_config](https://hf.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.fsdp_config) parameter. + +### Sharding strategy + +FSDP offers several sharding strategies to distribute a model. Refer to the table below to help you choose the best strategy for your setup. Specify a strategy with the `fsdp_sharding_strategy` parameter in the configuration file. + +| sharding strategy | description | parameter value | +|---|---|---| +| `FULL_SHARD` | shards model parameters, gradients, and optimizer states | `1` | +| `SHARD_GRAD_OP` | shards gradients and optimizer states | `2` | +| `NO_SHARD` | don't shard the model | `3` | +| `HYBRID_SHARD` | shards model parameters, gradients, and optimizer states within each GPU | `4` | +| `HYBRID_SHARD_ZERO2` | shards gradients and optimizer states within each GPU | `5` | + +### CPU offload + +Offload model parameters and gradients when they aren't being used to the CPU to save additional GPU memory. This is useful for scenarios where a model is too large even with FSDP. + +Specify `fsdp_offload_params: true` in the configuration file to enable offloading. + +### Wrapping policy + +FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for the next layer. + +There are several wrapping policies available, but the *auto wrapping* policy is the simplest and doesn't require any changes to your code. Specify `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to determine which layer to wrap (for example, `BertLayer`). + +Size-based wrapping is also available. If a layer exceeds a certain number of parameters, it is wrapped. Specify `fsdp_wrap_policy: SIZED_BASED_WRAP` and `min_num_param` to set the minimum number of parameters for a layer to be wrapped. + +### Checkpoints + +Intermediate checkpoints should be saved as a sharded state dict because saving the full state dict - even with CPU offloading - is time consuming and can cause `NCCL Timeout` errors due to indefinite hanging during broadcasting. + +Specify `fsdp_state_dict_type: SHARDED_STATE_DICT` in the configuration file to save the sharded state dict. Now you can resume training from the sharded state dict with [`~accelerate.Accelerator.load_state`]. + +```py +accelerator.load_state("directory/containing/checkpoints") +``` + +Once training is complete though, you should save the full state dict because the sharded state dict is only compatible with FSDP. + +```py +if trainer.is_fsdp_enabled: + trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT") + +trainer.save_model(script_args.output_dir) +``` + +### TPU + +[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html), a package for running PyTorch on XLA devices, enables FSDP on TPUs. Modify the configuration file to include the parameters below. Refer to the [xla_fsdp_settings](https://github.com/pytorch/xla/blob/2e6e183e0724818f137c8135b34ef273dea33318/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py#L128) parameter for additional XLA-specific parameters you can configure for FSDP. + +```yaml +xla: True # must be set to True to enable PyTorch/XLA +xla_fsdp_settings: # XLA specific FSDP parameters +xla_fsdp_grad_ckpt: True # enable gradient checkpointing +``` + +## Training + +After running [accelerate config](https://hf.co/docs/accelerate/package_reference/cli#accelerate-config), your configuration file should be ready. An example configuration file is shown below that fully shards the parameter, gradient and optimizer states on two GPUs. Your file may look different depending on how you set up your configuration. + +```yaml +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: true + fsdp_sharding_strategy: 1 + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +Run the [accelerate launch](https://hf.co/docs/accelerate/package_reference/cli#accelerate-launch) command to launch a training script with the FSDP configurations you chose in the configuration file. + +```bash +accelerate launch my-training-script.py +``` + +It is also possible to directly specify some of the FSDP arguments in the command line. + +```bash +accelerate launch --fsdp="full shard" --fsdp_config="path/to/fsdp_config/" my-training-script.py +``` + +## Resources + +FSDP is a powerful tool for training large models with fewer GPUs compared to other parallelism strategies. Refer to the following resources below to learn even more about FSDP. + +- Follow along with the more in-depth Accelerate guide for [FSDP](https://hf.co/docs/accelerate/usage_guides/fsdp). +- Read the [Introducing PyTorch Fully Sharded Data Parallel (FSDP) API](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) blog post. +- Read the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) blog post. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_features.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_features.md new file mode 100644 index 0000000000000000000000000000000000000000..19ac987807261da527b9de5358fd007fe474087e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_features.md @@ -0,0 +1,82 @@ + + +# Generation features + +The [`~GenerationMixin.generate`] API supports a couple features for building applications on top of it. + +This guide will show you how to use these features. + +## Streaming + +Streaming starts returning text as soon as it is generated so you don't have to wait to see the entire generated response all at once. It is important in user-facing applications because it reduces perceived latency and allows users to see the generation progression. + +
+ +
+ +> [!TIP] +> Learn more about streaming in the [Text Generation Inference](https://huggingface.co/docs/text-generation-inference/en/conceptual/streaming) docs. + +Create an instance of [`TextStreamer`] with the tokenizer. Pass [`TextStreamer`] to the `streamer` parameter in [`~GenerationMixin.generate`] to stream the output one word at a time. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer + +tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") +model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") +inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt") +streamer = TextStreamer(tokenizer) + +_ = model.generate(**inputs, streamer=streamer, max_new_tokens=20) +``` + +The `streamer` parameter is compatible with any class with a [`~TextStreamer.put`] and [`~TextStreamer.end`] method. [`~TextStreamer.put`] pushes new tokens and [`~TextStreamer.end`] flags the end of generation. You can create your own streamer class as long as they include these two methods, or you can use Transformers' basic streamer classes. + +## Watermarking + +Watermarking is useful for detecting whether text is generated. The [watermarking strategy](https://hf.co/papers/2306.04634) in Transformers randomly "colors" a subset of the tokens green. When green tokens are generated, they have a small bias added to their logits, and a higher probability of being generated. You can detect generated text by comparing the proportion of green tokens to the amount of green tokens typically found in human-generated text. + +Watermarking is supported for any generative model in Transformers and doesn't require an extra classification model to detect the watermarked text. + +Create a [`WatermarkingConfig`] with the bias value to add to the logits and watermarking algorithm. The example below uses the `"selfhash"` algorithm, where the green token selection only depends on the current token. Pass the [`WatermarkingConfig`] to [`~GenerationMixin.generate`]. + +> [!TIP] +> The [`WatermarkDetector`] class detects the proportion of green tokens in generated text, which is why it is recommended to strip the prompt text, if it is much longer than the generated text. Padding can also have an effect on [`WatermarkDetector`]. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig + +model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") +tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") +tokenizer.pad_token_id = tokenizer.eos_token_id +tokenizer.padding_side = "left" + +inputs = tokenizer(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt") +input_len = inputs["input_ids"].shape[-1] + +watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash") +out = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20) +``` + +Create an instance of [`WatermarkDetector`] and pass the model output to it to detect whether the text is machine-generated. The [`WatermarkDetector`] must have the same [`WatermarkingConfig`] used during generation. + +```py +detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config) +detection_out = detector(out, return_dict=True) +detection_out.prediction +array([True, True]) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_strategies.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_strategies.md new file mode 100644 index 0000000000000000000000000000000000000000..5c56fb0e04f8ec2282b88e2450c461cf082b767f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/generation_strategies.md @@ -0,0 +1,330 @@ + + +# Generation strategies + +A decoding strategy informs how a model should select the next generated token. There are many types of decoding strategies, and choosing the appropriate one has a significant impact on the quality of the generated text. + +This guide will help you understand the different decoding strategies available in Transformers and how and when to use them. + +## Greedy search + +Greedy search is the default decoding strategy. It selects the next most likely token at each step. Unless specified in [`GenerationConfig`], this strategy generates a maximum of 20 tokens. + +Greedy search works well for tasks with relatively short outputs. However, it breaks down when generating longer sequences because it begins to repeat itself. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("I look forward to", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to default length because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=20) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing' +``` + +## Contrastive search + +[Contrastive search](https://huggingface.co/papers/2202.06417) is a decoding strategy that aims to reduce repetition even while generating longer sequences. This strategy compares how similar a generated token is against previous tokens, and if they're more similar, a penalty is applied. + +Enable contrastive search with the `penalty_alpha` and `top_k` parameters. The `penalty_alpha` manages the penalty applied and `top_k` is the number of most likely tokens to return. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=100, penalty_alpha=0.6, top_k=4) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for building and deploying AI models.\nHugging Face is an open-source company that provides a platform for building and deploying AI models. The platform allows developers to build and deploy AI models, as well as collaborate with other developers.\nHugging Face was founded in 2019 by Thibault Wittemberg and Clément Delangue. The company is based in Paris, France.\nHugging Face has' +``` + +## Beam search + +Beam search keeps track of several generated sequences (beams) at each time step. After a certain number of steps, it selects the sequence with the highest *overall* probability. Unlike greedy search, this strategy can "look ahead" and pick a sequence with a higher probability overall even if the initial tokens have a lower probability. + +> [!TIP] +> Check out the [beam search visualizer](https://huggingface.co/spaces/m-ric/beam_search_visualizer) to see how beam search works. + +Enable beam search with the `num_beams` parameter (should be greater than 1 otherwise it's equivalent to greedy search). + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, num_beams=2) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +"['Hugging Face is an open-source company that develops and maintains the Hugging Face platform, which is a collection of tools and libraries for building and deploying natural language processing (NLP) models. Hugging Face was founded in 2018 by Thomas Wolf']" +``` + +## Diverse beam search + +[Diverse beam search](https://hf.co/papers/1610.02424) is a variant of beam search that produces more diverse output candidates to choose from. This strategy measures the dissimilarity of sequences and a penalty is applied if sequences are too similar. To avoid high computation costs, the number of beams is divided into groups. + +Enable diverse beam search with the `num_beams`, `num_beam_groups` and `diversity_penalty` parameters (the `num_beams` parameter should be divisible by `num_beam_groups`). + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, num_beams=6, num_beam_groups=3, diversity_penalty=1.0, do_sample=False) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company 🤗\nWe are an open-source company. Our mission is to democratize AI and make it accessible to everyone. We believe that AI should be used for the benefit of humanity, not for the benefit of a' +``` + +## Multinomial sampling + +Search methods selects the most likely tokens. Sampling, or multinomial sampling, randomly selects a token based on the probability distribution over the entire models vocabulary. This means every token with a non-zero probability has a chance to be selected. Sampling strategies reduce repetition and can generate more creative and diverse outputs. + +Enable multinomial sampling with `do_sample=True` and `num_beams=1`. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=1) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company 🤗\nWe are open-source and believe that open-source is the best way to build technology. Our mission is to make AI accessible to everyone, and we believe that open-source is the best way to achieve that.' +``` + +## Beam search multinomial sampling + +This decoding strategy is a combination of beam search and multinomial sampling. It generates multiple beams and uses a sampling strategy for each beam. + +Enable beam search multinomial sampling by setting `num_beams` to a value greater than 1 and `do_sample=True`. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16).to("cuda") +# explicitly set to 100 because Llama2 generation length is 4096 +outputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=4) +'Hugging Face is an open-source company 100% dedicated to making AI more accessible. We believe that AI should be available to everyone, and we’re working hard to make that a reality.\nWe’re a team of passionate engineers, designers,' +``` + +## Speculative decoding + +[Speculative](https://hf.co/papers/2211.17192) or assistive decoding isn't a search or sampling strategy. Instead, speculative decoding adds a second smaller model to generate candidate tokens. The main model verifies the candidate tokens in a single `forward` pass, which speeds up the decoding process overall. This method is especially useful for LLMs where it can be more costly and slower to generate tokens. Refer to the [speculative decoding](./llm_optims#speculative-decoding) guide to learn more. + +Currently, only greedy search and multinomial sampling are supported with speculative decoding. Batched inputs aren't supported either. + +Enable speculative decoding with the `assistant_model` parameter. You'll notice the fastest speed up with an assistant model that is much smaller than the main model. Add `do_sample=True` to enable token validation with resampling. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt") + +outputs = model.generate(**inputs, assistant_model=assistant_model) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for developers to build and deploy machine' +``` + +Speculative decoding is also supported in [`Pipeline`] with the `assistant_model` parameter. + +```python +from transformers import pipeline +import torch + +pipe = pipeline( + "text-generation", + model="meta-llama/Llama-3.1-8B", + assistant_model="meta-llama/Llama-3.2-1B", + torch_dtype=torch.bfloat16 +) +pipe_output = pipe("Once upon a time, ", max_new_tokens=50, do_sample=False) +pipe_output[0]["generated_text"] +``` + + + + +Add the `temperature` parameter to control sampling randomness. For speculative decoding, a lower temperature may improve latency. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt") + +outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=True, temperature=0.5) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that is dedicated to creating a better world through technology.' +``` + + + + +### Prompt lookup decoding + +[Prompt lookup decoding](./llm_optims#prompt-lookup-decoding) is a variant of speculative decoding that uses overlapping n-grams as the candidate tokens. It works well for input-grounded tasks such as summarization. Refer to the [prompt lookup decoding](./llm_optims#prompt-lookup-decoding) guide to learn more. + +Enable prompt lookup decoding with the `prompt_lookup_num_tokens` parameter. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +assistant_model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, assistant_model=assistant_model, max_new_tokens=20, prompt_lookup_num_tokens=5) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +'Hugging Face is an open-source company that provides a platform for developers to build and deploy machine learning models. It offers a variety of tools' +``` + +### Self-speculative decoding + +Early exiting uses the earlier hidden states from the language modeling head as inputs, effectively skipping layers to yield a lower quality output. The lower quality output is used as the assistant output and self-speculation is applied to fix the output using the remaining layers. The final generated result from this self-speculative method is the same (or has the same distribution) as the original models generation. + +The assistant model is also part of the target model, so the caches and weights can be shared, resulting in lower memory requirements. + +For a model trained with early exit, pass `assistant_early_exit` to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +prompt = "Alice and Bob" +checkpoint = "facebook/layerskip-llama3.2-1B" + +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +inputs = tokenizer(prompt, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained(checkpoint) +outputs = model.generate(**inputs, assistant_early_exit=4, do_sample=False, max_new_tokens=20) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +``` + +### Universal assisted decoding + +Universal assisted decoding (UAD) enables the main and assistant models to use different tokenizers. The main models input tokens are re-encoded into assistant model tokens. Candidate tokens are generated in the assistant encoding which are re-encoded into the main model candidate tokens. The candidate tokens are verified as explained in [speculative decoding](#speculative-decoding). + +Re-encoding involves decoding token ids into text and encoding the text with a different tokenizer. To prevent tokenization discrepancies during re-encoding, UAD finds the longest common sub-sequence between the source and target encodings to ensure the new tokens include the correct prompt suffix. + +Add the `tokenizer` and `assistant_tokenizer` parameters to [`~GenerationMixin.generate`] to enable UAD. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer + +prompt = "Alice and Bob" + +assistant_tokenizer = AutoTokenizer.from_pretrained("double7/vicuna-68m") +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b") +inputs = tokenizer(prompt, return_tensors="pt") + +model = AutoModelForCausalLM.from_pretrained("google/gemma-2-9b") +assistant_model = AutoModelForCausalLM.from_pretrained("double7/vicuna-68m") +outputs = model.generate(**inputs, assistant_model=assistant_model, tokenizer=tokenizer, assistant_tokenizer=assistant_tokenizer) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +['Alice and Bob are sitting in a bar. Alice is drinking a beer and Bob is drinking a'] +``` + +## DoLa + +[Decoding by Contrasting Layers (DoLa)](https://hf.co/papers/2309.03883) is a contrastive decoding strategy for improving factuality and reducing hallucination. This strategy works by contrasting the logit differences between the final and early layers. As a result, factual knowledge localized to particular layers are amplified. DoLa is not recommended for smaller models like GPT-2. + +Enable DoLa with the following parameters. + +- `dola_layers` are the candidate layers to be contrasted with the final layer. It can be a string (`low` or `high`) to contrast the lower or higher parts of a layer. `high` is recommended for short-answer tasks like TruthfulQA. `low` is recommended for long-answer reasoning tasks like GSM8K, StrategyQA, FACTOR, and VicunaQA. + + When a model has tied word embeddings, layer 0 is skipped and it begins from layer 2. + + It can also be a list of integers that represent the layer indices between 0 and the total number of layers. Layer 0 is the word embedding, 1 is the first transformer layer, and so on. Refer to the table below for the range of layer indices depending on the number of model layers. + + | layers | low | high | + |---|---|---| + | > 40 | (0, 20, 2) | (N - 20, N, 2) | + | <= 40 | range(0, N // 2, 2) | range(N // 2, N, 2) | + +- `repetition_penalty` reduces repetition and it is recommended to set it to 1.2. + + + + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("What is the highest peak in the world??", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, max_new_tokens=50, dola_layers="high", do_sample=False) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +" Mount EverestMount Everest, called Himalaya in Nepali, is the world's highest peak, lying almost 9.5 kilometers above the sea level and the tallest mountain from 19,036.91 ft. The mountain was" +``` + + + + +Contrast layers 18 and 20 with the final layer. + +```py +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-1.7B") +model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-1.7B", torch_dtype=torch.float16).to("cuda") +inputs = tokenizer("What is the highest peak in the world?", return_tensors="pt").to("cuda") + +outputs = model.generate(**inputs, max_new_tokens=50, dola_layers=[18,20], do_sample=False, repetition_penalty=1.2) +tokenizer.batch_decode(outputs[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True) +" Mount EverestMount Everest, called Himalaya in Nepali, is the world's highest peak above sea level and it rises to an incredible height of 29,028 feet above the ocean. Its summit is over a mile taller than Mt" +``` + + + + +## Resources + +Read the [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) blog post for an explanation of how common decoding strategies work. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gguf.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gguf.md new file mode 100644 index 0000000000000000000000000000000000000000..5043da792155ff9a18832eaee2fe0e9a66906b27 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gguf.md @@ -0,0 +1,53 @@ + + +# GGUF + +[GGUF](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) is a file format used to store models for inference with [GGML](https://github.com/ggerganov/ggml), a fast and lightweight inference framework written in C and C++. GGUF is a single-file format containing the model metadata and tensors. + +
+ +
+ +The GGUF format also supports many quantized data types (refer to [quantization type table](https://hf.co/docs/hub/en/gguf#quantization-types) for a complete list of supported quantization types) which saves a significant amount of memory, making inference with large models like Whisper and Llama feasible on local and edge devices. + +Transformers supports loading models stored in the GGUF format for further training or finetuning. The GGUF checkpoint is **dequantized to fp32** where the full model weights are available and compatible with PyTorch. + +> [!TIP] +> Models that support GGUF include Llama, Mistral, Qwen2, Qwen2Moe, Phi3, Bloom, Falcon, StableLM, GPT2, Starcoder2, and [more](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/ggml.py) + +Add the `gguf_file` parameter to [`~PreTrainedModel.from_pretrained`] to specify the GGUF file to load. + +```py +# pip install gguf +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" +filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf" + +torch_dtype = torch.float32 # could be torch.float16 or torch.bfloat16 too +tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename) +model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename, torch_dtype=torch_dtype) +``` + +Once you're done tinkering with the model, save and convert it back to the GGUF format with the [convert-hf-to-gguf.py](https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py) script. + +```py +tokenizer.save_pretrained("directory") +model.save_pretrained("directory") + +!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory} +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/glossary.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..d9fdac2475f23bcda4685330086fb730848dd666 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/glossary.md @@ -0,0 +1,522 @@ + + +# Glossary + +This glossary defines general machine learning and 🤗 Transformers terms to help you better understand the +documentation. + +## A + +### attention mask + +The attention mask is an optional argument used when batching sequences together. + + + +This argument indicates to the model which tokens should be attended to, and which should not. + +For example, consider these two sequences: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence_a = "This is a short sequence." +>>> sequence_b = "This is a rather long sequence. It is at least longer than the sequence A." + +>>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] +>>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] +``` + +The encoded versions have different lengths: + +```python +>>> len(encoded_sequence_a), len(encoded_sequence_b) +(8, 19) +``` + +Therefore, we can't put them together in the same tensor as-is. The first sequence needs to be padded up to the length +of the second one, or the second one needs to be truncated down to the length of the first one. + +In the first case, the list of IDs will be extended by the padding indices. We can pass a list to the tokenizer and ask +it to pad like this: + +```python +>>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) +``` + +We can see that 0s have been added on the right of the first sentence to make it the same length as the second one: + +```python +>>> padded_sequences["input_ids"] +[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] +``` + +This can then be converted into a tensor in PyTorch or TensorFlow. The attention mask is a binary tensor indicating the +position of the padded indices so that the model does not attend to them. For the [`BertTokenizer`], `1` indicates a +value that should be attended to, while `0` indicates a padded value. This attention mask is in the dictionary returned +by the tokenizer under the key "attention_mask": + +```python +>>> padded_sequences["attention_mask"] +[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] +``` + +### autoencoding models + +See [encoder models](#encoder-models) and [masked language modeling](#masked-language-modeling-mlm) + +### autoregressive models + +See [causal language modeling](#causal-language-modeling) and [decoder models](#decoder-models) + +## B + +### backbone + +The backbone is the network (embeddings and layers) that outputs the raw hidden states or features. It is usually connected to a [head](#head) which accepts the features as its input to make a prediction. For example, [`ViTModel`] is a backbone without a specific head on top. Other models can also use [`VitModel`] as a backbone such as [DPT](model_doc/dpt). + +## C + +### causal language modeling + +A pretraining task where the model reads the texts in order and has to predict the next word. It's usually done by +reading the whole sentence but using a mask inside the model to hide the future tokens at a certain timestep. + +### channel + +Color images are made up of some combination of values in three channels: red, green, and blue (RGB) and grayscale images only have one channel. In 🤗 Transformers, the channel can be the first or last dimension of an image's tensor: [`n_channels`, `height`, `width`] or [`height`, `width`, `n_channels`]. + +### connectionist temporal classification (CTC) + +An algorithm which allows a model to learn without knowing exactly how the input and output are aligned; CTC calculates the distribution of all possible outputs for a given input and chooses the most likely output from it. CTC is commonly used in speech recognition tasks because speech doesn't always cleanly align with the transcript for a variety of reasons such as a speaker's different speech rates. + +### convolution + +A type of layer in a neural network where the input matrix is multiplied element-wise by a smaller matrix (kernel or filter) and the values are summed up in a new matrix. This is known as a convolutional operation which is repeated over the entire input matrix. Each operation is applied to a different segment of the input matrix. Convolutional neural networks (CNNs) are commonly used in computer vision. + +## D + +### DataParallel (DP) + +Parallelism technique for training on multiple GPUs where the same setup is replicated multiple times, with each instance +receiving a distinct data slice. The processing is done in parallel and all setups are synchronized at the end of each training step. + +Learn more about how DataParallel works [here](perf_train_gpu_many#dataparallel-vs-distributeddataparallel). + +### decoder input IDs + +This input is specific to encoder-decoder models, and contains the input IDs that will be fed to the decoder. These +inputs should be used for sequence to sequence tasks, such as translation or summarization, and are usually built in a +way specific to each model. + +Most encoder-decoder models (BART, T5) create their `decoder_input_ids` on their own from the `labels`. In such models, +passing the `labels` is the preferred way to handle training. + +Please check each model's docs to see how they handle these input IDs for sequence to sequence training. + +### decoder models + +Also referred to as autoregressive models, decoder models involve a pretraining task (called causal language modeling) where the model reads the texts in order and has to predict the next word. It's usually done by +reading the whole sentence with a mask to hide future tokens at a certain timestep. + + + +### deep learning (DL) + +Machine learning algorithms which use neural networks with several layers. + +## E + +### encoder models + +Also known as autoencoding models, encoder models take an input (such as text or images) and transform them into a condensed numerical representation called an embedding. Oftentimes, encoder models are pretrained using techniques like [masked language modeling](#masked-language-modeling-mlm), which masks parts of the input sequence and forces the model to create more meaningful representations. + + + +## F + +### feature extraction + +The process of selecting and transforming raw data into a set of features that are more informative and useful for machine learning algorithms. Some examples of feature extraction include transforming raw text into word embeddings and extracting important features such as edges or shapes from image/video data. + +### feed forward chunking + +In each residual attention block in transformers the self-attention layer is usually followed by 2 feed forward layers. +The intermediate embedding size of the feed forward layers is often bigger than the hidden size of the model (e.g., for +`google-bert/bert-base-uncased`). + +For an input of size `[batch_size, sequence_length]`, the memory required to store the intermediate feed forward +embeddings `[batch_size, sequence_length, config.intermediate_size]` can account for a large fraction of the memory +use. The authors of [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) noticed that since the +computation is independent of the `sequence_length` dimension, it is mathematically equivalent to compute the output +embeddings of both feed forward layers `[batch_size, config.hidden_size]_0, ..., [batch_size, config.hidden_size]_n` +individually and concat them afterward to `[batch_size, sequence_length, config.hidden_size]` with `n = sequence_length`, which trades increased computation time against reduced memory use, but yields a mathematically +**equivalent** result. + +For models employing the function [`apply_chunking_to_forward`], the `chunk_size` defines the number of output +embeddings that are computed in parallel and thus defines the trade-off between memory and time complexity. If +`chunk_size` is set to 0, no feed forward chunking is done. + +### finetuned models + +Finetuning is a form of transfer learning which involves taking a pretrained model, freezing its weights, and replacing the output layer with a newly added [model head](#head). The model head is trained on your target dataset. + +See the [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) tutorial for more details, and learn how to fine-tune models with 🤗 Transformers. + +## H + +### head + +The model head refers to the last layer of a neural network that accepts the raw hidden states and projects them onto a different dimension. There is a different model head for each task. For example: + + * [`GPT2ForSequenceClassification`] is a sequence classification head - a linear layer - on top of the base [`GPT2Model`]. + * [`ViTForImageClassification`] is an image classification head - a linear layer on top of the final hidden state of the `CLS` token - on top of the base [`ViTModel`]. + * [`Wav2Vec2ForCTC`] is a language modeling head with [CTC](#connectionist-temporal-classification-ctc) on top of the base [`Wav2Vec2Model`]. + +## I + +### image patch + +Vision-based Transformers models split an image into smaller patches which are linearly embedded, and then passed as a sequence to the model. You can find the `patch_size` - or resolution - of the model in its configuration. + +### inference + +Inference is the process of evaluating a model on new data after training is complete. See the [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) tutorial to learn how to perform inference with 🤗 Transformers. + +### input IDs + +The input ids are often the only required parameters to be passed to the model as input. They are token indices, +numerical representations of tokens building the sequences that will be used as input by the model. + + + +Each tokenizer works differently but the underlying mechanism remains the same. Here's an example using the BERT +tokenizer, which is a [WordPiece](https://arxiv.org/pdf/1609.08144.pdf) tokenizer: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + +>>> sequence = "A Titan RTX has 24GB of VRAM" +``` + +The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. + +```python +>>> tokenized_sequence = tokenizer.tokenize(sequence) +``` + +The tokens are either words or subwords. Here for instance, "VRAM" wasn't in the model vocabulary, so it's been split +in "V", "RA" and "M". To indicate those tokens are not separate words but parts of the same word, a double-hash prefix +is added for "RA" and "M": + +```python +>>> print(tokenized_sequence) +['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] +``` + +These tokens can then be converted into IDs which are understandable by the model. This can be done by directly feeding the sentence to the tokenizer, which leverages the Rust implementation of [🤗 Tokenizers](https://github.com/huggingface/tokenizers) for peak performance. + +```python +>>> inputs = tokenizer(sequence) +``` + +The tokenizer returns a dictionary with all the arguments necessary for its corresponding model to work properly. The +token indices are under the key `input_ids`: + +```python +>>> encoded_sequence = inputs["input_ids"] +>>> print(encoded_sequence) +[101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102] +``` + +Note that the tokenizer automatically adds "special tokens" (if the associated model relies on them) which are special +IDs the model sometimes uses. + +If we decode the previous sequence of ids, + +```python +>>> decoded_sequence = tokenizer.decode(encoded_sequence) +``` + +we will see + +```python +>>> print(decoded_sequence) +[CLS] A Titan RTX has 24GB of VRAM [SEP] +``` + +because this is the way a [`BertModel`] is going to expect its inputs. + +## L + +### labels + +The labels are an optional argument which can be passed in order for the model to compute the loss itself. These labels +should be the expected prediction of the model: it will use the standard loss in order to compute the loss between its +predictions and the expected value (the label). + +These labels are different according to the model head, for example: + +- For sequence classification models, ([`BertForSequenceClassification`]), the model expects a tensor of dimension + `(batch_size)` with each value of the batch corresponding to the expected label of the entire sequence. +- For token classification models, ([`BertForTokenClassification`]), the model expects a tensor of dimension + `(batch_size, seq_length)` with each value corresponding to the expected label of each individual token. +- For masked language modeling, ([`BertForMaskedLM`]), the model expects a tensor of dimension `(batch_size, + seq_length)` with each value corresponding to the expected label of each individual token: the labels being the token + ID for the masked token, and values to be ignored for the rest (usually -100). +- For sequence to sequence tasks, ([`BartForConditionalGeneration`], [`MBartForConditionalGeneration`]), the model + expects a tensor of dimension `(batch_size, tgt_seq_length)` with each value corresponding to the target sequences + associated with each input sequence. During training, both BART and T5 will make the appropriate + `decoder_input_ids` and decoder attention masks internally. They usually do not need to be supplied. This does not + apply to models leveraging the Encoder-Decoder framework. +- For image classification models, ([`ViTForImageClassification`]), the model expects a tensor of dimension + `(batch_size)` with each value of the batch corresponding to the expected label of each individual image. +- For semantic segmentation models, ([`SegformerForSemanticSegmentation`]), the model expects a tensor of dimension + `(batch_size, height, width)` with each value of the batch corresponding to the expected label of each individual pixel. +- For object detection models, ([`DetrForObjectDetection`]), the model expects a list of dictionaries with a + `class_labels` and `boxes` key where each value of the batch corresponds to the expected label and number of bounding boxes of each individual image. +- For automatic speech recognition models, ([`Wav2Vec2ForCTC`]), the model expects a tensor of dimension `(batch_size, + target_length)` with each value corresponding to the expected label of each individual token. + + + +Each model's labels may be different, so be sure to always check the documentation of each model for more information +about their specific labels! + + + +The base models ([`BertModel`]) do not accept labels, as these are the base transformer models, simply outputting +features. + +### large language models (LLM) + +A generic term that refers to transformer language models (GPT-3, BLOOM, OPT) that were trained on a large quantity of data. These models also tend to have a large number of learnable parameters (e.g. 175 billion for GPT-3). + +## M + +### masked language modeling (MLM) + +A pretraining task where the model sees a corrupted version of the texts, usually done by +masking some tokens randomly, and has to predict the original text. + +### multimodal + +A task that combines texts with another kind of inputs (for instance images). + +## N + +### Natural language generation (NLG) + +All tasks related to generating text (for instance, [Write With Transformers](https://transformer.huggingface.co/), translation). + +### Natural language processing (NLP) + +A generic way to say "deal with texts". + +### Natural language understanding (NLU) + +All tasks related to understanding what is in a text (for instance classifying the +whole text, individual words). + +## P + +### pipeline + +A pipeline in 🤗 Transformers is an abstraction referring to a series of steps that are executed in a specific order to preprocess and transform data and return a prediction from a model. Some example stages found in a pipeline might be data preprocessing, feature extraction, and normalization. + +For more details, see [Pipelines for inference](https://huggingface.co/docs/transformers/pipeline_tutorial). + +### PipelineParallel (PP) + +Parallelism technique in which the model is split up vertically (layer-level) across multiple GPUs, so that only one or +several layers of the model are placed on a single GPU. Each GPU processes in parallel different stages of the pipeline +and working on a small chunk of the batch. Learn more about how PipelineParallel works [here](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism). + +### pixel values + +A tensor of the numerical representations of an image that is passed to a model. The pixel values have a shape of [`batch_size`, `num_channels`, `height`, `width`], and are generated from an image processor. + +### pooling + +An operation that reduces a matrix into a smaller matrix, either by taking the maximum or average of the pooled dimension(s). Pooling layers are commonly found between convolutional layers to downsample the feature representation. + +### position IDs + +Contrary to RNNs that have the position of each token embedded within them, transformers are unaware of the position of +each token. Therefore, the position IDs (`position_ids`) are used by the model to identify each token's position in the +list of tokens. + +They are an optional parameter. If no `position_ids` are passed to the model, the IDs are automatically created as +absolute positional embeddings. + +Absolute positional embeddings are selected in the range `[0, config.max_position_embeddings - 1]`. Some models use +other types of positional embeddings, such as sinusoidal position embeddings or relative position embeddings. + +### preprocessing + +The task of preparing raw data into a format that can be easily consumed by machine learning models. For example, text is typically preprocessed by tokenization. To gain a better idea of what preprocessing looks like for other input types, check out the [Preprocess](https://huggingface.co/docs/transformers/preprocessing) tutorial. + +### pretrained model + +A model that has been pretrained on some data (for instance all of Wikipedia). Pretraining methods involve a +self-supervised objective, which can be reading the text and trying to predict the next word (see [causal language +modeling](#causal-language-modeling)) or masking some words and trying to predict them (see [masked language +modeling](#masked-language-modeling-mlm)). + +Speech and vision models have their own pretraining objectives. For example, Wav2Vec2 is a speech model pretrained on a contrastive task which requires the model to identify the "true" speech representation from a set of "false" speech representations. On the other hand, BEiT is a vision model pretrained on a masked image modeling task which masks some of the image patches and requires the model to predict the masked patches (similar to the masked language modeling objective). + +## R + +### recurrent neural network (RNN) + +A type of model that uses a loop over a layer to process texts. + +### representation learning + +A subfield of machine learning which focuses on learning meaningful representations of raw data. Some examples of representation learning techniques include word embeddings, autoencoders, and Generative Adversarial Networks (GANs). + +## S + +### sampling rate + +A measurement in hertz of the number of samples (the audio signal) taken per second. The sampling rate is a result of discretizing a continuous signal such as speech. + +### self-attention + +Each element of the input finds out which other elements of the input they should attend to. + +### self-supervised learning + +A category of machine learning techniques in which a model creates its own learning objective from unlabeled data. It differs from [unsupervised learning](#unsupervised-learning) and [supervised learning](#supervised-learning) in that the learning process is supervised, but not explicitly from the user. + +One example of self-supervised learning is [masked language modeling](#masked-language-modeling-mlm), where a model is passed sentences with a proportion of its tokens removed and learns to predict the missing tokens. + +### semi-supervised learning + +A broad category of machine learning training techniques that leverages a small amount of labeled data with a larger quantity of unlabeled data to improve the accuracy of a model, unlike [supervised learning](#supervised-learning) and [unsupervised learning](#unsupervised-learning). + +An example of a semi-supervised learning approach is "self-training", in which a model is trained on labeled data, and then used to make predictions on the unlabeled data. The portion of the unlabeled data that the model predicts with the most confidence gets added to the labeled dataset and used to retrain the model. + +### sequence-to-sequence (seq2seq) + +Models that generate a new sequence from an input, like translation models, or summarization models (such as +[Bart](model_doc/bart) or [T5](model_doc/t5)). + +### Sharded DDP + +Another name for the foundational [ZeRO](#zero-redundancy-optimizer-zero) concept as used by various other implementations of ZeRO. + +### stride + +In [convolution](#convolution) or [pooling](#pooling), the stride refers to the distance the kernel is moved over a matrix. A stride of 1 means the kernel is moved one pixel over at a time, and a stride of 2 means the kernel is moved two pixels over at a time. + +### supervised learning + +A form of model training that directly uses labeled data to correct and instruct model performance. Data is fed into the model being trained, and its predictions are compared to the known labels. The model updates its weights based on how incorrect its predictions were, and the process is repeated to optimize model performance. + +## T + +### Tensor Parallelism (TP) + +Parallelism technique for training on multiple GPUs in which each tensor is split up into multiple chunks, so instead of +having the whole tensor reside on a single GPU, each shard of the tensor resides on its designated GPU. Shards gets +processed separately and in parallel on different GPUs and the results are synced at the end of the processing step. +This is what is sometimes called horizontal parallelism, as the splitting happens on horizontal level. +Learn more about Tensor Parallelism [here](perf_train_gpu_many#tensor-parallelism). + +### token + +A part of a sentence, usually a word, but can also be a subword (non-common words are often split in subwords) or a +punctuation symbol. + +### token Type IDs + +Some models' purpose is to do classification on pairs of sentences or question answering. + + + +These require two different sequences to be joined in a single "input_ids" entry, which usually is performed with the +help of special tokens, such as the classifier (`[CLS]`) and separator (`[SEP]`) tokens. For example, the BERT model +builds its two sequence input as such: + +```python +>>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] +``` + +We can use our tokenizer to automatically generate such a sentence by passing the two sequences to `tokenizer` as two +arguments (and not a list, like before) like this: + +```python +>>> from transformers import BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") +>>> sequence_a = "HuggingFace is based in NYC" +>>> sequence_b = "Where is HuggingFace based?" + +>>> encoded_dict = tokenizer(sequence_a, sequence_b) +>>> decoded = tokenizer.decode(encoded_dict["input_ids"]) +``` + +which will return: + +```python +>>> print(decoded) +[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP] +``` + +This is enough for some models to understand where one sequence ends and where another begins. However, other models, +such as BERT, also deploy token type IDs (also called segment IDs). They are represented as a binary mask identifying +the two types of sequence in the model. + +The tokenizer returns this mask as the "token_type_ids" entry: + +```python +>>> encoded_dict["token_type_ids"] +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1] +``` + +The first sequence, the "context" used for the question, has all its tokens represented by a `0`, whereas the second +sequence, corresponding to the "question", has all its tokens represented by a `1`. + +Some models, like [`XLNetModel`] use an additional token represented by a `2`. + +### transfer learning + +A technique that involves taking a pretrained model and adapting it to a dataset specific to your task. Instead of training a model from scratch, you can leverage knowledge obtained from an existing model as a starting point. This speeds up the learning process and reduces the amount of training data needed. + +### transformer + +Self-attention based deep learning model architecture. + +## U + +### unsupervised learning + +A form of model training in which data provided to the model is not labeled. Unsupervised learning techniques leverage statistical information of the data distribution to find patterns useful for the task at hand. + +## Z + +### Zero Redundancy Optimizer (ZeRO) + +Parallelism technique which performs sharding of the tensors somewhat similar to [TensorParallel](#tensor-parallelism-tp), +except the whole tensor gets reconstructed in time for a forward or backward computation, therefore the model doesn't need +to be modified. This method also supports various offloading techniques to compensate for limited GPU memory. +Learn more about ZeRO [here](perf_train_gpu_many#zero-data-parallelism). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gpu_selection.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gpu_selection.md new file mode 100644 index 0000000000000000000000000000000000000000..749fcf3c2dda16800cf6a43558fa9863f8c5ec66 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/gpu_selection.md @@ -0,0 +1,94 @@ + + +# GPU selection + +During distributed training, you can specify the number of GPUs to use and in what order. This can be useful when you have GPUs with different computing power and you want to use the faster GPU first. Or you could only use a subset of the available GPUs. The selection process works for both [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) and [DataParallel](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html). You don't need Accelerate or [DeepSpeed integration](./main_classes/deepspeed). + +This guide will show you how to select the number of GPUs to use and the order to use them in. + +## Number of GPUs + +For example, if there are 4 GPUs and you only want to use the first 2, run the command below. + + + + +Use the `--nproc_per_node` to select how many GPUs to use. + +```bash +torchrun --nproc_per_node=2 trainer-program.py ... +``` + + + + +Use `--num_processes` to select how many GPUs to use. + +```bash +accelerate launch --num_processes 2 trainer-program.py ... +``` + + + + +Use `--num_gpus` to select how many GPUs to use. + +```bash +deepspeed --num_gpus 2 trainer-program.py ... +``` + + + + +### Order of GPUs + +To select specific GPUs to use and their order, configure the the `CUDA_VISIBLE_DEVICES` environment variable. It is easiest to set the environment variable in `~/bashrc` or another startup config file. `CUDA_VISIBLE_DEVICES` is used to map which GPUs are used. For example, if there are 4 GPUs (0, 1, 2, 3) and you only want to run GPUs 0 and 2: + +```bash +CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... +``` + +Only the 2 physical GPUs (0 and 2) are "visible" to PyTorch and these are mapped to `cuda:0` and `cuda:1` respectively. You can also reverse the order of the GPUs to use 2 first. The mapping becomes `cuda:1` for GPU 0 and `cuda:0` for GPU 2. + +```bash +CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ... +``` + +You can also set the `CUDA_VISIBLE_DEVICES` environment variable to an empty value to create an environment without GPUs. + +```bash +CUDA_VISIBLE_DEVICES= python trainer-program.py ... +``` + +> [!WARNING] +> As with any environment variable, they can be exported instead of being added to the command line. However, this is not recommended because it can be confusing if you forget how the environment variable was set up and you end up using the wrong GPUs. Instead, it is common practice to set the environment variable for a specific training run on the same command line. + +`CUDA_DEVICE_ORDER` is an alternative environment variable you can use to control how the GPUs are ordered. You can order according to the following. + +1. PCIe bus IDs that matches the order of [`nvidia-smi`](https://developer.nvidia.com/nvidia-system-management-interface) and [`rocm-smi`](https://rocm.docs.amd.com/projects/rocm_smi_lib/en/latest/.doxygen/docBin/html/index.html) for NVIDIA and AMD GPUs respectively. + +```bash +export CUDA_DEVICE_ORDER=PCI_BUS_ID +``` + +2. GPU compute ability. + +```bash +export CUDA_DEVICE_ORDER=FASTEST_FIRST +``` + +The `CUDA_DEVICE_ORDER` is especially useful if your training setup consists of an older and newer GPU, where the older GPU appears first, but you cannot physically swap the cards to make the newer GPU appear first. In this case, set `CUDA_DEVICE_ORDER=FASTEST_FIRST` to always use the newer and faster GPU first (`nvidia-smi` or `rocm-smi` still reports the GPUs in their PCIe order). Or you could also set `export CUDA_VISIBLE_DEVICES=1,0`. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/how_to_hack_models.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/how_to_hack_models.md new file mode 100644 index 0000000000000000000000000000000000000000..cc229f6b01481f9896f87d6323d5149079f1820d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/how_to_hack_models.md @@ -0,0 +1,156 @@ + + +# Customizing model components + +Another way to customize a model is to modify their components, rather than writing a new model entirely, allowing you to tailor a model to your specific use case. For example, you can add new layers or optimize the attention mechanism of an architecture. Customizations are applied directly to a Transformers model so that you can continue to use features such as [`Trainer`], [`PreTrainedModel`], and the [PEFT](https://huggingface.co/docs/peft/en/index) library. + +This guide will show you how to customize a models attention mechanism in order to apply [Low-Rank Adaptation (LoRA)](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora) to it. + +> [!TIP] +> The [clear_import_cache](https://github.com/huggingface/transformers/blob/9985d06add07a4cc691dc54a7e34f54205c04d40/src/transformers/utils/import_utils.py#L2286) utility is very useful when you're iteratively modifying and developing model code. It removes all cached Transformers modules and allows Python to reload the modified code without constantly restarting your environment. +> +> ```py +> from transformers import AutoModel +> from transformers.utils.import_utils import clear_import_cache +> +> model = AutoModel.from_pretrained("bert-base-uncased") +> # modifications to model code +> # clear cache to reload modified code +> clear_import_cache() +> # re-import to use updated code +> model = AutoModel.from_pretrained("bert-base-uncased") +> ``` + +## Attention class + +[Segment Anything](./model_doc/sam) is an image segmentation model, and it combines the query-key-value (`qkv`) projection in its attention mechanisms. To reduce the number of trainable parameters and computational overhead, you can apply LoRA to the `qkv` projection. This requires splitting the `qkv` projection so that you can separately target the `q` and `v` with LoRA. + +1. Create a custom attention class, `SamVisionAttentionSplit`, by subclassing the original `SamVisionAttention` class. In the `__init__`, delete the combined `qkv` and create a separate linear layer for `q`, `k` and `v`. + +```py +import torch +import torch.nn as nn +from transformers.models.sam.modeling_sam import SamVisionAttention + +class SamVisionAttentionSplit(SamVisionAttention, nn.Module): + def __init__(self, config, window_size): + super().__init__(config, window_size) + # remove combined qkv + del self.qkv + # separate q, k, v projections + self.q = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.k = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self.v = nn.Linear(config.hidden_size, config.hidden_size, bias=config.qkv_bias) + self._register_load_state_dict_pre_hook(self.split_q_k_v_load_hook) +``` + +2. The `_split_qkv_load_hook` function splits the pretrained `qkv` weights into separate `q`, `k`, and `v` weights when loading the model to ensure compatibility with any pretrained model. + +```py + def split_q_k_v_load_hook(self, state_dict, prefix, *args): + keys_to_delete = [] + for key in list(state_dict.keys()): + if "qkv." in key: + # split q, k, v from the combined projection + q, k, v = state_dict[key].chunk(3, dim=0) + # replace with individual q, k, v projections + state_dict[key.replace("qkv.", "q.")] = q + state_dict[key.replace("qkv.", "k.")] = k + state_dict[key.replace("qkv.", "v.")] = v + # mark the old qkv key for deletion + keys_to_delete.append(key) + + # remove old qkv keys + for key in keys_to_delete: + del state_dict[key] +``` + +3. In the `forward` pass, `q`, `k`, and `v` are computed separately while the rest of the attention mechanism remains the same. + +```py + def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor: + batch_size, height, width, _ = hidden_states.shape + qkv_shapes = (batch_size * self.num_attention_heads, height * width, -1) + query = self.q(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + key = self.k(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + value = self.v(hidden_states).reshape((batch_size, height * width,self.num_attention_heads, -1)).permute(0,2,1,3).reshape(qkv_shapes) + + attn_weights = (query * self.scale) @ key.transpose(-2, -1) + + if self.use_rel_pos: + attn_weights = self.add_decomposed_rel_pos( + attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width) + ) + + attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype) + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1) + attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1) + attn_output = self.proj(attn_output) + + if output_attentions: + outputs = (attn_output, attn_weights) + else: + outputs = (attn_output, None) + return outputs +``` + +Assign the custom `SamVisionAttentionSplit` class to the original models `SamVisionAttention` module to replace it. All instances of `SamVisionAttention` in the model is replaced with the split attention version. + +Load the model with [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import SamModel +from transformers.models.sam import modeling_sam + +# replace the attention class in the modeling_sam module +modeling_sam.SamVisionAttention = SamVisionAttentionSplit + +# load the pretrained SAM model +model = SamModel.from_pretrained("facebook/sam-vit-base") +``` + +## LoRA + +With separate `q`, `k`, and `v` projections, apply LoRA to `q` and `v`. + +Create a [LoraConfig](https://huggingface.co/docs/peft/package_reference/config#peft.PeftConfig) and specify the rank `r`, `lora_alpha`, `lora_dropout`, `task_type`, and most importantly, the modules to target. + +```py +from peft import LoraConfig, get_peft_model + +config = LoraConfig( + r=16, + lora_alpha=32, + # apply LoRA to q and v + target_modules=["q", "v"], + lora_dropout=0.1, + task_type="mask-generation" +) +``` + +Pass the model and [LoraConfig](https://huggingface.co/docs/peft/package_reference/config#peft.PeftConfig) to [get_peft_model](https://huggingface.co/docs/peft/package_reference/peft_model#peft.get_peft_model) to apply LoRA to the model. + +```py +model = get_peft_model(model, config) +``` + +Call [print_trainable_parameters](https://huggingface.co/docs/peft/package_reference/peft_model#peft.PeftMixedModel.print_trainable_parameters) to view the number of parameters you're training as a result versus the total number of parameters. + +```py +model.print_trainable_parameters() +"trainable params: 608,256 || all params: 94,343,728 || trainable%: 0.6447" +``` \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/hpo_train.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/hpo_train.md new file mode 100644 index 0000000000000000000000000000000000000000..303ff6fb53b471d0f8388aed608247fd99fb7696 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/hpo_train.md @@ -0,0 +1,167 @@ + + +# Hyperparameter search + +Hyperparameter search discovers an optimal set of hyperparameters that produces the best model performance. [`Trainer`] supports several hyperparameter search backends - [Optuna](https://optuna.readthedocs.io/en/stable/index.html), [SigOpt](https://docs.sigopt.com/), [Weights & Biases](https://docs.wandb.ai/), [Ray Tune](https://docs.ray.io/en/latest/tune/index.html) - through [`~Trainer.hyperparameter_search`] to optimize an objective or even multiple objectives. + +This guide will go over how to set up a hyperparameter search for each of the backends. + +```bash +pip install optuna/sigopt/wandb/ray[tune] +``` + +To use [`~Trainer.hyperparameter_search`], you need to create a `model_init` function. This function includes basic model information (arguments and configuration) because it needs to be reinitialized for each search trial in the run. + +> [!WARNING] +> The `model_init` function is incompatible with the [optimizers](./main_classes/trainer#transformers.Trainer.optimizers) parameter. Subclass [`Trainer`] and override the [`~Trainer.create_optimizer_and_scheduler`] method to create a custom optimizer and scheduler. + +An example `model_init` function is shown below. + +```py +def model_init(trial): + return AutoModelForSequenceClassification.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) +``` + +Pass `model_init` to [`Trainer`] along with everything else you need for training. Then you can call [`~Trainer.hyperparameter_search`] to start the search. + +[`~Trainer.hyperparameter_search`] accepts a [direction](./main_classes/trainer#transformers.Trainer.hyperparameter_search.direction) parameter to specify whether to minimize, maximize, or minimize and maximize multiple objectives. You'll also need to set the [backend](./main_classes/trainer#transformers.Trainer.hyperparameter_search.backend) you're using, an [object](./main_classes/trainer#transformers.Trainer.hyperparameter_search.hp_space) containing the hyperparameters to optimize for, the [number of trials](./main_classes/trainer#transformers.Trainer.hyperparameter_search.n_trials) to run, and a [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) to return the objective values. + +> [!TIP] +> If [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) isn't defined, the default [compute_objective](./main_classes/trainer#transformers.Trainer.hyperparameter_search.compute_objective) is called which is the sum of an evaluation metric like F1. + +```py +from transformers import Trainer + +trainer = Trainer( + model=None, + args=training_args, + train_dataset=small_train_dataset, + eval_dataset=small_eval_dataset, + compute_metrics=compute_metrics, + processing_class=tokenizer, + model_init=model_init, + data_collator=data_collator, +) +trainer.hyperparameter_search(...) +``` + +The following examples demonstrate how to perform a hyperparameter search for the learning rate and training batch size using the different backends. + + + + +[Optuna](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/002_configurations.html#sphx-glr-tutorial-10-key-features-002-configurations-py) optimizes categories, integers, and floats. + +```py +def optuna_hp_space(trial): + return { + "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True), + "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [16, 32, 64, 128]), + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="optuna", + hp_space=optuna_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[Ray Tune](https://docs.ray.io/en/latest/tune/api/search_space.html) optimizes floats, integers, and categorical parameters. It also offers multiple sampling distributions for each parameter such as uniform and log-uniform. + +```py +def ray_hp_space(trial): + return { + "learning_rate": tune.loguniform(1e-6, 1e-4), + "per_device_train_batch_size": tune.choice([16, 32, 64, 128]), + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="ray", + hp_space=ray_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[SigOpt](https://docs.sigopt.com/ai-module-api-references/api_reference/objects/object_parameter) optimizes double, integer, and categorical parameters. + +```py +def sigopt_hp_space(trial): + return [ + {"bounds": {"min": 1e-6, "max": 1e-4}, "name": "learning_rate", "type": "double"}, + { + "categorical_values": ["16", "32", "64", "128"], + "name": "per_device_train_batch_size", + "type": "categorical", + }, + ] + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="sigopt", + hp_space=sigopt_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +[Weights & Biases](https://docs.wandb.ai/guides/sweeps/sweep-config-keys) also optimizes integers, floats, and categorical parameters. It also includes support for different search strategies and distribution options. + +```py +def wandb_hp_space(trial): + return { + "method": "random", + "metric": {"name": "objective", "goal": "minimize"}, + "parameters": { + "learning_rate": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, + "per_device_train_batch_size": {"values": [16, 32, 64, 128]}, + }, + } + +best_trials = trainer.hyperparameter_search( + direction=["minimize", "maximize"], + backend="wandb", + hp_space=wandb_hp_space, + n_trials=20, + compute_objective=compute_objective, +) +``` + + + + +## Distributed Data Parallel + +[`Trainer`] only supports hyperparameter search for distributed data parallel (DDP) on the Optuna and SigOpt backends. Only the rank-zero process is used to generate the search trial, and the resulting parameters are passed along to the other ranks. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/image_processors.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/image_processors.md new file mode 100644 index 0000000000000000000000000000000000000000..2e5e466cd5d2f055fc9c28cd973e2292377cadc0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/image_processors.md @@ -0,0 +1,222 @@ + + +# Image processors + +Image processors converts images into pixel values, tensors that represent image colors and size. The pixel values are inputs to a vision or video model. To ensure a pretrained model receives the correct input, an image processor can perform the following operations to make sure an image is exactly like the images a model was pretrained on. + +- [`~BaseImageProcessor.center_crop`] to resize an image +- [`~BaseImageProcessor.normalize`] or [`~BaseImageProcessor.rescale`] pixel values + +Use [`~ImageProcessingMixin.from_pretrained`] to load an image processors configuration (image size, whether to normalize and rescale, etc.) from a vision model on the Hugging Face [Hub](https://hf.co) or local directory. The configuration for each pretrained model is saved in a [preprocessor_config.json](https://huggingface.co/google/vit-base-patch16-224/blob/main/preprocessor_config.json) file. + +```py +from transformers import AutoImageProcessor + +image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +Pass an image to the image processor to transform it into pixel values, and set `return_tensors="pt"` to return PyTorch tensors. Feel free to print out the inputs to see what the image looks like as a tensor. + +```py +from PIL import Image +import requests + +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/image_processor_example.png" +image = Image.open(requests.get(url, stream=True).raw).convert("RGB") +inputs = image_processor(image, return_tensors="pt") +``` + +This guide covers the image processor class and how to preprocess images for vision models. + +## Image processor classes + +Image processors inherit from the [`BaseImageProcessor`] class which provides the [`~BaseImageProcessor.center_crop`], [`~BaseImageProcessor.normalize`], and [`~BaseImageProcessor.rescale`] functions. There are two types of image processors. + +- [`BaseImageProcessor`] is a Python implementation. +- [`BaseImageProcessorFast`] is a faster [torchvision-backed](https://pytorch.org/vision/stable/index.html) version. For a batch of [torch.Tensor](https://pytorch.org/docs/stable/tensors.html) inputs, this can be up to 33x faster. [`BaseImageProcessorFast`] is not available for all vision models at the moment. Refer to a models API documentation to check if it is supported. + +Each image processor subclasses the [`ImageProcessingMixin`] class which provides the [`~ImageProcessingMixin.from_pretrained`] and [`~ImageProcessingMixin.save_pretrained`] methods for loading and saving image processors. + +There are two ways you can load an image processor, with [`AutoImageProcessor`] or a model-specific image processor. + + + + +The [AutoClass](./model_doc/auto) API provides a convenient method to load an image processor without directly specifying the model the image processor is associated with. + +Use [`~AutoImageProcessor.from_pretrained`] to load an image processor, and set `use_fast=True` to load a fast image processor if it's supported. + +```py +from transformers import AutoImageProcessor + +image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224", use_fast=True) +``` + + + + +Each image processor is associated with a specific pretrained vision model, and the image processors configuration contains the models expected size and whether to normalize and resize. + +The image processor can be loaded directly from the model-specific class. Check a models API documentation to see whether it supports a fast image processor. + +```py +from transformers import ViTImageProcessor + +image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") +``` + +To load a fast image processor, use the fast implementation class. + +```py +from transformers import ViTImageProcessorFast + +image_processor = ViTImageProcessorFast.from_pretrained("google/vit-base-patch16-224") +``` + + + + +## Fast image processors + +[`BaseImageProcessorFast`] is based on [torchvision](https://pytorch.org/vision/stable/index.html) and is significantly faster, especially when processing on a GPU. This class can be used as a drop-in replacement for [`BaseImageProcessor`] if it's available for a model because it has the same design. Make sure [torchvision](https://pytorch.org/get-started/locally/#mac-installation) is installed, and set the `use_fast` parameter to `True`. + +```py +from transformers import AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", use_fast=True) +``` + +Control which device processing is performed on with the `device` parameter. Processing is performed on the same device as the input by default if the inputs are tensors, otherwise they are processed on the CPU. The example below places the fast processor on a GPU. + +```py +from torchvision.io import read_image +from transformers import DetrImageProcessorFast + +images = read_image("image.jpg") +processor = DetrImageProcessorFast.from_pretrained("facebook/detr-resnet-50") +images_processed = processor(images, return_tensors="pt", device="cuda") +``` + +
+Benchmarks + +The benchmarks are obtained from an [AWS EC2 g5.2xlarge](https://aws.amazon.com/ec2/instance-types/g5/) instance with a NVIDIA A10G Tensor Core GPU. + +
+ +
+
+ +
+
+ +
+
+ +
+
+ +## Preprocess + +Transformers' vision models expects the input as PyTorch tensors of pixel values. An image processor handles the conversion of images to pixel values, which is represented by the batch size, number of channels, height, and width. To achieve this, an image is resized (center cropped) and the pixel values are normalized and rescaled to the models expected values. + +Image preprocessing is not the same as *image augmentation*. Image augmentation makes changes (brightness, colors, rotatation, etc.) to an image for the purpose of either creating new training examples or prevent overfitting. Image preprocessing makes changes to an image for the purpose of matching a pretrained model's expected input format. + +Typically, images are augmented (to increase performance) and then preprocessed before being passed to a model. You can use any library ([Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb), [Kornia](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)) for augmentation and an image processor for preprocessing. + +This guide uses the torchvision [transforms](https://pytorch.org/vision/stable/transforms.html) module for augmentation. + +Start by loading a small sample of the [food101](https://hf.co/datasets/food101) dataset. + +```py +from datasets import load_dataset + +dataset = load_dataset("food101", split="train[:100]") +``` + +From the [transforms](https://pytorch.org/vision/stable/transforms.html) module, use the [Compose](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) API to chain together [RandomResizedCrop](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) and [ColorJitter](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html). These transforms randomly crop and resize an image, and randomly adjusts an images colors. + +The image size to randomly crop to can be retrieved from the image processor. For some models, an exact height and width are expected while for others, only the `shortest_edge` is required. + +```py +from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose + +size = ( + image_processor.size["shortest_edge"] + if "shortest_edge" in image_processor.size + else (image_processor.size["height"], image_processor.size["width"]) +) +_transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)]) +``` + +Apply the transforms to the images and convert them to the RGB format. Then pass the augmented images to the image processor to return the pixel values. + +The `do_resize` parameter is set to `False` because the images have already been resized in the augmentation step by [RandomResizedCrop](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html). If you don't augment the images, then the image processor automatically resizes and normalizes the images with the `image_mean` and `image_std` values. These values are found in the preprocessor configuration file. + +```py +def transforms(examples): + images = [_transforms(img.convert("RGB")) for img in examples["image"]] + examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"] + return examples +``` + +Apply the combined augmentation and preprocessing function to the entire dataset on the fly with [`~datasets.Dataset.set_transform`]. + +```py +dataset.set_transform(transforms) +``` + +Convert the pixel values back into an image to see how the image has been augmented and preprocessed. + +```py +import numpy as np +import matplotlib.pyplot as plt + +img = dataset[0]["pixel_values"] +plt.imshow(img.permute(1, 2, 0)) +``` + +
+
+ +
before
+
+
+ +
after
+
+
+ +For other vision tasks like object detection or segmentation, the image processor includes post-processing methods to convert a models raw output into meaningful predictions like bounding boxes or segmentation maps. + +### Padding + +Some models, like [DETR](./model_doc/detr), applies [scale augmentation](https://paperswithcode.com/method/image-scale-augmentation) during training which can cause images in a batch to have different sizes. Images with different sizes can't be batched together. + +To fix this, pad the images with the special padding token `0`. Use the [pad](https://github.com/huggingface/transformers/blob/9578c2597e2d88b6f0b304b5a05864fd613ddcc1/src/transformers/models/detr/image_processing_detr.py#L1151) method to pad the images, and define a custom collate function to batch them together. + +```py +def collate_fn(batch): + pixel_values = [item["pixel_values"] for item in batch] + encoding = image_processor.pad(pixel_values, return_tensors="pt") + labels = [item["labels"] for item in batch] + batch = {} + batch["pixel_values"] = encoding["pixel_values"] + batch["pixel_mask"] = encoding["pixel_mask"] + batch["labels"] = labels + return batch +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/index.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/index.md new file mode 100644 index 0000000000000000000000000000000000000000..8120e12937ae377cc2407e45bc4ed0ff6b8f928b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/index.md @@ -0,0 +1,46 @@ + + +# Transformers + +Transformers is a library of pretrained natural language processing, computer vision, audio, and multimodal models for inference and training. Use Transformers to train models on your data, build inference applications, and generate text with large language models. + +Explore the [Hugging Face Hub](https://huggingface.com) today to find a model and use Transformers to help you get started right away. + +## Features + +Transformers provides everything you need for inference or training with state-of-the-art pretrained models. Some of the main features include: + +- [Pipeline](./pipeline_tutorial): Simple and optimized inference class for many machine learning tasks like text generation, image segmentation, automatic speech recognition, document question answering, and more. +- [Trainer](./trainer): A comprehensive trainer that supports features such as mixed precision, torch.compile, and FlashAttention for training and distributed training for PyTorch models. +- [generate](./llm_tutorial): Fast text generation with large language models (LLMs) and vision language models (VLMs), including support for streaming and multiple decoding strategies. + +## Design + +> [!TIP] +> Read our [Philosophy](./philosophy) to learn more about Transformers' design principles. + +Transformers is designed for developers and machine learning engineers and researchers. Its main design principles are: + +1. Fast and easy to use: Every model is implemented from only three main classes (configuration, model, and preprocessor) and can be quickly used for inference or training with [`Pipeline`] or [`Trainer`]. +2. Pretrained models: Reduce your carbon footprint, compute cost and time by using a pretrained model instead of training an entirely new one. Each pretrained model is reproduced as closely as possible to the original model and offers state-of-the-art performance. + + + +Join us on the Hugging Face [Hub](https://huggingface.co/), [Discord](https://discord.com/invite/JfAtkvEtRb), or [forum](https://discuss.huggingface.co/) to collaborate and build models, datasets, and applications together. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/installation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..2c7ddabb878305a6545d9d165d7f552a0a30e2b3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/installation.md @@ -0,0 +1,223 @@ + + +# Installation + +Transformers works with [PyTorch](https://pytorch.org/get-started/locally/), [TensorFlow 2.0](https://www.tensorflow.org/install/pip), and [Flax](https://flax.readthedocs.io/en/latest/). It has been tested on Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, and Flax. + +## Virtual environment + +A virtual environment helps manage different projects and avoids compatibility issues between dependencies. Take a look at the [Install packages in a virtual environment using pip and venv](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/) guide if you're unfamiliar with Python virtual environments. + + + + +Create and activate a virtual environment in your project directory with [venv](https://docs.python.org/3/library/venv.html). + +```bash +python -m venv .env +source ./env/bin/activate +``` + + + + +[uv](https://docs.astral.sh/uv/) is a fast Rust-based Python package and project manager. + +```bash +uv venv .env +source ./env/bin/activate +``` + + + + +## Python + +You can install Transformers with pip or uv. + + + + +[pip](https://pip.pypa.io/en/stable/) is a package installer for Python. Install Transformers with pip in your newly created virtual environment. + +```bash +pip install transformers +``` + + + + +[uv](https://docs.astral.sh/uv/) is a fast Rust-based Python package and project manager. + +```bash +uv pip install transformers +``` + + + + +For GPU acceleration, install the appropriate CUDA drivers for [PyTorch](https://pytorch.org/get-started/locally) and [TensorFlow](https://www.tensorflow.org/install/pip). + +Run the command below to check if your system detects an NVIDIA GPU. + +```bash +nvidia-smi +``` + +To install a CPU-only version of Transformers and a machine learning framework, run the following command. + + + + +```bash +pip install 'transformers[torch]' +uv pip install 'transformers[torch]' +``` + + + + +For Apple M1 hardware, you need to install CMake and pkg-config first. + +```bash +brew install cmake +brew install pkg-config +``` + +Install TensorFlow 2.0. + +```bash +pip install 'transformers[tf-cpu]' +uv pip install 'transformers[tf-cpu]' +``` + + + + +```bash +pip install 'transformers[flax]' +uv pip install 'transformers[flax]' +``` + + + + +Test whether the install was successful with the following command. It should return a label and score for the provided text. + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))" +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +### Source install + +Installing from source installs the *latest* version rather than the *stable* version of the library. It ensures you have the most up-to-date changes in Transformers and it's useful for experimenting with the latest features or fixing a bug that hasn't been officially released in the stable version yet. + +The downside is that the latest version may not always be stable. If you encounter any problems, please open a [GitHub Issue](https://github.com/huggingface/transformers/issues) so we can fix it as soon as possible. + +Install from source with the following command. + +```bash +pip install git+https://github.com/huggingface/transformers +``` + +Check if the install was successful with the command below. It should return a label and score for the provided text. + +```bash +python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))" +[{'label': 'POSITIVE', 'score': 0.9998704791069031}] +``` + +### Editable install + +An [editable install](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs) is useful if you're developing locally with Transformers. It links your local copy of Transformers to the Transformers [repository](https://github.com/huggingface/transformers) instead of copying the files. The files are added to Python's import path. + +```bash +git clone https://github.com/huggingface/transformers.git +cd transformers +pip install -e . +``` + +> [!WARNING] +> You must keep the local Transformers folder to keep using it. + +Update your local version of Transformers with the latest changes in the main repository with the following command. + +```bash +cd ~/transformers/ +git pull +``` + +## conda + +[conda](https://docs.conda.io/projects/conda/en/stable/#) is a language-agnostic package manager. Install Transformers from the [conda-forge](https://anaconda.org/conda-forge/transformers) channel in your newly created virtual environment. + +```bash +conda install conda-forge::transformers +``` + +## Set up + +After installation, you can configure the Transformers cache location or set up the library for offline usage. + +### Cache directory + +When you load a pretrained model with [`~PreTrainedModel.from_pretrained`], the model is downloaded from the Hub and locally cached. + +Every time you load a model, it checks whether the cached model is up-to-date. If it's the same, then the local model is loaded. If it's not the same, the newer model is downloaded and cached. + +The default directory given by the shell environment variable `TRANSFORMERS_CACHE` is `~/.cache/huggingface/hub`. On Windows, the default directory is `C:\Users\username\.cache\huggingface\hub`. + +Cache a model in a different directory by changing the path in the following shell environment variables (listed by priority). + +1. [HF_HUB_CACHE](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhubcache) or `TRANSFORMERS_CACHE` (default) +2. [HF_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhome) +3. [XDG_CACHE_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#xdgcachehome) + `/huggingface` (only if `HF_HOME` is not set) + +Older versions of Transformers uses the shell environment variables `PYTORCH_TRANSFORMERS_CACHE` or `PYTORCH_PRETRAINED_BERT_CACHE`. You should keep these unless you specify the newer shell environment variable `TRANSFORMERS_CACHE`. + +### Offline mode + +To use Transformers in an offline or firewalled environment requires the downloaded and cached files ahead of time. Download a model repository from the Hub with the [`~huggingface_hub.snapshot_download`] method. + +> [!TIP] +> Refer to the [Download files from the Hub](https://hf.co/docs/huggingface_hub/guides/download) guide for more options for downloading files from the Hub. You can download files from specific revisions, download from the CLI, and even filter which files to download from a repository. + +```py +from huggingface_hub import snapshot_download + +snapshot_download(repo_id="meta-llama/Llama-2-7b-hf", repo_type="model") +``` + +Set the environment variable `HF_HUB_OFFLINE=1` to prevent HTTP calls to the Hub when loading a model. + +```bash +HF_HUB_OFFLINE=1 \ +python examples/pytorch/language-modeling/run_clm.py --model_name_or_path meta-llama/Llama-2-7b-hf --dataset_name wikitext ... +``` + +Another option for only loading cached files is to set `local_files_only=True` in [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import LlamaForCausalLM + +model = LlamaForCausalLM.from_pretrained("./path/to/local/directory", local_files_only=True) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/audio_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/audio_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..e6a39c7c1c49a9311934a02aa46fe503d3301ec2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/audio_utils.md @@ -0,0 +1,39 @@ + + +# Utilities for `FeatureExtractors` + +This page lists all the utility functions that can be used by the audio [`FeatureExtractor`] in order to compute special features from a raw audio using common algorithms such as *Short Time Fourier Transform* or *log mel spectrogram*. + +Most of those are only useful if you are studying the code of the audio processors in the library. + +## Audio Transformations + +[[autodoc]] audio_utils.hertz_to_mel + +[[autodoc]] audio_utils.mel_to_hertz + +[[autodoc]] audio_utils.mel_filter_bank + +[[autodoc]] audio_utils.optimal_fft_length + +[[autodoc]] audio_utils.window_function + +[[autodoc]] audio_utils.spectrogram + +[[autodoc]] audio_utils.power_to_db + +[[autodoc]] audio_utils.amplitude_to_db diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/file_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/file_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..6f5657f7743cd44000801133093614bbcbfc61ae --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/file_utils.md @@ -0,0 +1,50 @@ + + +# General Utilities + +This page lists all of Transformers general utility functions that are found in the file `utils.py`. + +Most of those are only useful if you are studying the general code in the library. + + +## Enums and namedtuples + +[[autodoc]] utils.ExplicitEnum + +[[autodoc]] utils.PaddingStrategy + +[[autodoc]] utils.TensorType + +## Special Decorators + +[[autodoc]] utils.add_start_docstrings + +[[autodoc]] utils.add_start_docstrings_to_model_forward + +[[autodoc]] utils.add_end_docstrings + +[[autodoc]] utils.add_code_sample_docstrings + +[[autodoc]] utils.replace_return_docstrings + +## Special Properties + +[[autodoc]] utils.cached_property + +## Other Utilities + +[[autodoc]] utils._LazyModule diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/generation_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/generation_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..d8931342ee45f85fc12b84ddbb26a28569216724 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/generation_utils.md @@ -0,0 +1,446 @@ + + +# Utilities for Generation + +This page lists all the utility functions used by [`~generation.GenerationMixin.generate`]. + +## Generate Outputs + +The output of [`~generation.GenerationMixin.generate`] is an instance of a subclass of +[`~utils.ModelOutput`]. This output is a data structure containing all the information returned +by [`~generation.GenerationMixin.generate`], but that can also be used as tuple or dictionary. + +Here's an example: + +```python +from transformers import GPT2Tokenizer, GPT2LMHeadModel + +tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2") +model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2") + +inputs = tokenizer("Hello, my dog is cute and ", return_tensors="pt") +generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) +``` + +The `generation_output` object is a [`~generation.GenerateDecoderOnlyOutput`], as we can +see in the documentation of that class below, it means it has the following attributes: + +- `sequences`: the generated sequences of tokens +- `scores` (optional): the prediction scores of the language modelling head, for each generation step +- `hidden_states` (optional): the hidden states of the model, for each generation step +- `attentions` (optional): the attention weights of the model, for each generation step + +Here we have the `scores` since we passed along `output_scores=True`, but we don't have `hidden_states` and +`attentions` because we didn't pass `output_hidden_states=True` or `output_attentions=True`. + +You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you +will get `None`. Here for instance `generation_output.scores` are all the generated prediction scores of the +language modeling head, and `generation_output.attentions` is `None`. + +When using our `generation_output` object as a tuple, it only keeps the attributes that don't have `None` values. +Here, for instance, it has two elements, `loss` then `logits`, so + +```python +generation_output[:2] +``` + +will return the tuple `(generation_output.sequences, generation_output.scores)` for instance. + +When using our `generation_output` object as a dictionary, it only keeps the attributes that don't have `None` +values. Here, for instance, it has two keys that are `sequences` and `scores`. + +We document here all output types. + + +### PyTorch + +[[autodoc]] generation.GenerateDecoderOnlyOutput + +[[autodoc]] generation.GenerateEncoderDecoderOutput + +[[autodoc]] generation.GenerateBeamDecoderOnlyOutput + +[[autodoc]] generation.GenerateBeamEncoderDecoderOutput + +### TensorFlow + +[[autodoc]] generation.TFGreedySearchEncoderDecoderOutput + +[[autodoc]] generation.TFGreedySearchDecoderOnlyOutput + +[[autodoc]] generation.TFSampleEncoderDecoderOutput + +[[autodoc]] generation.TFSampleDecoderOnlyOutput + +[[autodoc]] generation.TFBeamSearchEncoderDecoderOutput + +[[autodoc]] generation.TFBeamSearchDecoderOnlyOutput + +[[autodoc]] generation.TFBeamSampleEncoderDecoderOutput + +[[autodoc]] generation.TFBeamSampleDecoderOnlyOutput + +[[autodoc]] generation.TFContrastiveSearchEncoderDecoderOutput + +[[autodoc]] generation.TFContrastiveSearchDecoderOnlyOutput + +### FLAX + +[[autodoc]] generation.FlaxSampleOutput + +[[autodoc]] generation.FlaxGreedySearchOutput + +[[autodoc]] generation.FlaxBeamSearchOutput + +## LogitsProcessor + +A [`LogitsProcessor`] can be used to modify the prediction scores of a language model head for +generation. + +### PyTorch + +[[autodoc]] AlternatingCodebooksLogitsProcessor + - __call__ + +[[autodoc]] ClassifierFreeGuidanceLogitsProcessor + - __call__ + +[[autodoc]] EncoderNoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] EncoderRepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] EpsilonLogitsWarper + - __call__ + +[[autodoc]] EtaLogitsWarper + - __call__ + +[[autodoc]] ExponentialDecayLengthPenalty + - __call__ + +[[autodoc]] ForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] ForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] HammingDiversityLogitsProcessor + - __call__ + +[[autodoc]] InfNanRemoveLogitsProcessor + - __call__ + +[[autodoc]] LogitNormalization + - __call__ + +[[autodoc]] LogitsProcessor + - __call__ + +[[autodoc]] LogitsProcessorList + - __call__ + +[[autodoc]] MinLengthLogitsProcessor + - __call__ + +[[autodoc]] MinNewTokensLengthLogitsProcessor + - __call__ + +[[autodoc]] MinPLogitsWarper + - __call__ + +[[autodoc]] NoBadWordsLogitsProcessor + - __call__ + +[[autodoc]] NoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] PrefixConstrainedLogitsProcessor + - __call__ + +[[autodoc]] RepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] SequenceBiasLogitsProcessor + - __call__ + +[[autodoc]] SuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] SuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] SynthIDTextWatermarkLogitsProcessor + - __call__ + +[[autodoc]] TemperatureLogitsWarper + - __call__ + +[[autodoc]] TopKLogitsWarper + - __call__ + +[[autodoc]] TopPLogitsWarper + - __call__ + +[[autodoc]] TypicalLogitsWarper + - __call__ + +[[autodoc]] UnbatchedClassifierFreeGuidanceLogitsProcessor + - __call__ + +[[autodoc]] WhisperTimeStampLogitsProcessor + - __call__ + +[[autodoc]] WatermarkLogitsProcessor + - __call__ + + +### TensorFlow + +[[autodoc]] TFForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] TFForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] TFForceTokensLogitsProcessor + - __call__ + +[[autodoc]] TFLogitsProcessor + - __call__ + +[[autodoc]] TFLogitsProcessorList + - __call__ + +[[autodoc]] TFLogitsWarper + - __call__ + +[[autodoc]] TFMinLengthLogitsProcessor + - __call__ + +[[autodoc]] TFNoBadWordsLogitsProcessor + - __call__ + +[[autodoc]] TFNoRepeatNGramLogitsProcessor + - __call__ + +[[autodoc]] TFRepetitionPenaltyLogitsProcessor + - __call__ + +[[autodoc]] TFSuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] TFSuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] TFTemperatureLogitsWarper + - __call__ + +[[autodoc]] TFTopKLogitsWarper + - __call__ + +[[autodoc]] TFTopPLogitsWarper + - __call__ + +### FLAX + +[[autodoc]] FlaxForcedBOSTokenLogitsProcessor + - __call__ + +[[autodoc]] FlaxForcedEOSTokenLogitsProcessor + - __call__ + +[[autodoc]] FlaxForceTokensLogitsProcessor + - __call__ + +[[autodoc]] FlaxLogitsProcessor + - __call__ + +[[autodoc]] FlaxLogitsProcessorList + - __call__ + +[[autodoc]] FlaxLogitsWarper + - __call__ + +[[autodoc]] FlaxMinLengthLogitsProcessor + - __call__ + +[[autodoc]] FlaxSuppressTokensAtBeginLogitsProcessor + - __call__ + +[[autodoc]] FlaxSuppressTokensLogitsProcessor + - __call__ + +[[autodoc]] FlaxTemperatureLogitsWarper + - __call__ + +[[autodoc]] FlaxTopKLogitsWarper + - __call__ + +[[autodoc]] FlaxTopPLogitsWarper + - __call__ + +[[autodoc]] FlaxWhisperTimeStampLogitsProcessor + - __call__ + +## StoppingCriteria + +A [`StoppingCriteria`] can be used to change when to stop generation (other than EOS token). Please note that this is exclusively available to our PyTorch implementations. + +[[autodoc]] StoppingCriteria + - __call__ + +[[autodoc]] StoppingCriteriaList + - __call__ + +[[autodoc]] MaxLengthCriteria + - __call__ + +[[autodoc]] MaxTimeCriteria + - __call__ + +[[autodoc]] StopStringCriteria + - __call__ + +[[autodoc]] EosTokenCriteria + - __call__ + +## Constraints + +A [`Constraint`] can be used to force the generation to include specific tokens or sequences in the output. Please note that this is exclusively available to our PyTorch implementations. + +[[autodoc]] Constraint + +[[autodoc]] PhrasalConstraint + +[[autodoc]] DisjunctiveConstraint + +[[autodoc]] ConstraintListState + +## BeamSearch + +[[autodoc]] BeamScorer + - process + - finalize + +[[autodoc]] BeamSearchScorer + - process + - finalize + +[[autodoc]] ConstrainedBeamSearchScorer + - process + - finalize + +## Streamers + +[[autodoc]] TextStreamer + +[[autodoc]] TextIteratorStreamer + +[[autodoc]] AsyncTextIteratorStreamer + +## Caches + +[[autodoc]] Cache + - update + +[[autodoc]] CacheConfig + - update + +[[autodoc]] QuantizedCacheConfig + - validate + +[[autodoc]] DynamicCache + - update + - get_seq_length + - reorder_cache + - to_legacy_cache + - from_legacy_cache + +[[autodoc]] QuantizedCache + - update + - get_seq_length + +[[autodoc]] QuantoQuantizedCache + +[[autodoc]] HQQQuantizedCache + +[[autodoc]] SinkCache + - update + - get_seq_length + - reorder_cache + +[[autodoc]] OffloadedCache + - update + - prefetch_layer + - evict_previous_layer + +[[autodoc]] StaticCache + - update + - get_seq_length + - reset + +[[autodoc]] OffloadedStaticCache + - update + - get_seq_length + - reset + +[[autodoc]] HybridCache + - update + - get_seq_length + - reset + +[[autodoc]] SlidingWindowCache + - update + - reset + +[[autodoc]] EncoderDecoderCache + - get_seq_length + - to_legacy_cache + - from_legacy_cache + - reset + - reorder_cache + +[[autodoc]] MambaCache + - update_conv_state + - update_ssm_state + - reset + +## Watermark Utils + +[[autodoc]] WatermarkingConfig + - __call__ + +[[autodoc]] WatermarkDetector + - __call__ + +[[autodoc]] BayesianDetectorConfig + +[[autodoc]] BayesianDetectorModel + - forward + +[[autodoc]] SynthIDTextWatermarkingConfig + +[[autodoc]] SynthIDTextWatermarkDetector + - __call__ + +## Compile Utils + +[[autodoc]] CompileConfig + - __call__ + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/image_processing_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/image_processing_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..42f99f361703c153865f13914c4adc8a8af4f7aa --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/image_processing_utils.md @@ -0,0 +1,48 @@ + + +# Utilities for Image Processors + +This page lists all the utility functions used by the image processors, mainly the functional +transformations used to process the images. + +Most of those are only useful if you are studying the code of the image processors in the library. + +## Image Transformations + +[[autodoc]] image_transforms.center_crop + +[[autodoc]] image_transforms.center_to_corners_format + +[[autodoc]] image_transforms.corners_to_center_format + +[[autodoc]] image_transforms.id_to_rgb + +[[autodoc]] image_transforms.normalize + +[[autodoc]] image_transforms.pad + +[[autodoc]] image_transforms.rgb_to_id + +[[autodoc]] image_transforms.rescale + +[[autodoc]] image_transforms.resize + +[[autodoc]] image_transforms.to_pil_image + +## ImageProcessingMixin + +[[autodoc]] image_processing_utils.ImageProcessingMixin diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/modeling_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/modeling_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..afc8123558f5c3cd96dff2c45c4f2cbf0070366f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/modeling_utils.md @@ -0,0 +1,83 @@ + + +# Custom Layers and Utilities + +This page lists all the custom layers used by the library, as well as the utility functions it provides for modeling. + +Most of those are only useful if you are studying the code of the models in the library. + + +## Pytorch custom modules + +[[autodoc]] pytorch_utils.Conv1D + +[[autodoc]] modeling_utils.PoolerStartLogits + - forward + +[[autodoc]] modeling_utils.PoolerEndLogits + - forward + +[[autodoc]] modeling_utils.PoolerAnswerClass + - forward + +[[autodoc]] modeling_utils.SquadHeadOutput + +[[autodoc]] modeling_utils.SQuADHead + - forward + +[[autodoc]] modeling_utils.SequenceSummary + - forward + +## PyTorch Helper Functions + +[[autodoc]] pytorch_utils.apply_chunking_to_forward + +[[autodoc]] pytorch_utils.find_pruneable_heads_and_indices + +[[autodoc]] pytorch_utils.prune_layer + +[[autodoc]] pytorch_utils.prune_conv1d_layer + +[[autodoc]] pytorch_utils.prune_linear_layer + +## TensorFlow custom layers + +[[autodoc]] modeling_tf_utils.TFConv1D + +[[autodoc]] modeling_tf_utils.TFSequenceSummary + +## TensorFlow loss functions + +[[autodoc]] modeling_tf_utils.TFCausalLanguageModelingLoss + +[[autodoc]] modeling_tf_utils.TFMaskedLanguageModelingLoss + +[[autodoc]] modeling_tf_utils.TFMultipleChoiceLoss + +[[autodoc]] modeling_tf_utils.TFQuestionAnsweringLoss + +[[autodoc]] modeling_tf_utils.TFSequenceClassificationLoss + +[[autodoc]] modeling_tf_utils.TFTokenClassificationLoss + +## TensorFlow Helper Functions + +[[autodoc]] modeling_tf_utils.get_initializer + +[[autodoc]] modeling_tf_utils.keras_serializable + +[[autodoc]] modeling_tf_utils.shape_list diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/pipelines_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/pipelines_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..6ea6de9a61b8ab5db6fe79ccafa1ed4855d78e9c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/pipelines_utils.md @@ -0,0 +1,44 @@ + + +# Utilities for pipelines + +This page lists all the utility functions the library provides for pipelines. + +Most of those are only useful if you are studying the code of the models in the library. + + +## Argument handling + +[[autodoc]] pipelines.ArgumentHandler + +[[autodoc]] pipelines.ZeroShotClassificationArgumentHandler + +[[autodoc]] pipelines.QuestionAnsweringArgumentHandler + +## Data format + +[[autodoc]] pipelines.PipelineDataFormat + +[[autodoc]] pipelines.CsvPipelineDataFormat + +[[autodoc]] pipelines.JsonPipelineDataFormat + +[[autodoc]] pipelines.PipedPipelineDataFormat + +## Utilities + +[[autodoc]] pipelines.PipelineException diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/time_series_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/time_series_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..11c562fbe32af5a123f122b44cf0e27db8ab61c9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/time_series_utils.md @@ -0,0 +1,29 @@ + + +# Time Series Utilities + +This page lists all the utility functions and classes that can be used for Time Series based models. + +Most of those are only useful if you are studying the code of the time series models or you wish to add to the collection of distributional output classes. + +## Distributional Output + +[[autodoc]] time_series_utils.NormalOutput + +[[autodoc]] time_series_utils.StudentTOutput + +[[autodoc]] time_series_utils.NegativeBinomialOutput diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/tokenization_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/tokenization_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..5aa65099176031bc55e24fa286783d876e2b13ce --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/tokenization_utils.md @@ -0,0 +1,42 @@ + + +# Utilities for Tokenizers + +This page lists all the utility functions used by the tokenizers, mainly the class +[`~tokenization_utils_base.PreTrainedTokenizerBase`] that implements the common methods between +[`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] and the mixin +[`~tokenization_utils_base.SpecialTokensMixin`]. + +Most of those are only useful if you are studying the code of the tokenizers in the library. + +## PreTrainedTokenizerBase + +[[autodoc]] tokenization_utils_base.PreTrainedTokenizerBase + - __call__ + - all + +## SpecialTokensMixin + +[[autodoc]] tokenization_utils_base.SpecialTokensMixin + +## Enums and namedtuples + +[[autodoc]] tokenization_utils_base.TruncationStrategy + +[[autodoc]] tokenization_utils_base.CharSpan + +[[autodoc]] tokenization_utils_base.TokenSpan diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/trainer_utils.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/trainer_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..1bc5e2baae2d6fd329dca311aebe8eb6a8011427 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/internal/trainer_utils.md @@ -0,0 +1,49 @@ + + +# Utilities for Trainer + +This page lists all the utility functions used by [`Trainer`]. + +Most of those are only useful if you are studying the code of the Trainer in the library. + +## Utilities + +[[autodoc]] EvalPrediction + +[[autodoc]] IntervalStrategy + +[[autodoc]] enable_full_determinism + +[[autodoc]] set_seed + +[[autodoc]] torch_distributed_zero_first + +## Callbacks internals + +[[autodoc]] trainer_callback.CallbackHandler + +## Distributed Evaluation + +[[autodoc]] trainer_pt_utils.DistributedTensorGatherer + +## Trainer Argument Parser + +[[autodoc]] HfArgumentParser + +## Debug Utilities + +[[autodoc]] debug_utils.DebugUnderflowOverflow diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/kv_cache.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/kv_cache.md new file mode 100644 index 0000000000000000000000000000000000000000..36f82fb3dc9a70173eab6970ac0b776ca8340044 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/kv_cache.md @@ -0,0 +1,359 @@ + + +# KV cache strategies + +The key-value (KV) vectors are used to calculate attention scores. For autoregressive models, KV scores are calculated *every* time because the model predicts one token at a time. Each prediction depends on the previous tokens, which means the model performs the same computations each time. + +A KV *cache* stores these calculations so they can be reused without recomputing them. Efficient caching is crucial for optimizing model performance because it reduces computation time and improves response rates. Refer to the [Caching](./cache_explanation.md) doc for a more detailed explanation about how a cache works. + +Transformers offers several [`Cache`] classes that implement different caching mechanisms. Some of these [`Cache`] classes are optimized to save memory while others are designed to maximize generation speed. Refer to the table below to compare cache types and use it to help you select the best cache for your use case. + +| Cache Type | Memory Efficient  | Supports torch.compile() | Initialization Recommended | Latency | Long Context Generation | +|------------------------|------------------|--------------------------|----------------------------|---------|-------------------------| +| Dynamic Cache | No | No | No | Mid | No | +| Static Cache | No | Yes | Yes | High | No | +| Offloaded Cache | Yes | No | No | Low | Yes | +| Offloaded Static Cache | No | Yes | Yes | High | Yes | +| Quantized Cache | Yes | No | No | Low | Yes | +| Sliding Window Cache | No | Yes | Yes | High | No | +| Sink Cache | Yes | No | Yes | Mid | Yes | + +This guide introduces you to the different [`Cache`] classes and shows you how to use them for generation. + +## Default cache + +The [`DynamicCache`] is the default cache class for most models. It allows the cache size to grow dynamically in order to store an increasing number of keys and values as generation progresses. + +Disable the cache by configuring `use_cache=False` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +model.generate(**inputs, do_sample=False, max_new_tokens=20, use_cache=False) +``` + +Cache classes can also be initialized first before calling and passing it to the models [past_key_values](https://hf.co/docs/transformers/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput.past_key_values) parameter. This cache initialization strategy is only recommended for some cache types. + +In most other cases, it's easier to define the cache strategy in the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) parameter. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +past_key_values = DynamicCache() +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, past_key_values=past_key_values) +``` + +## Memory efficient caches + +The KV cache can occupy a significant portion of memory and become a [bottleneck](https://hf.co/blog/llama31#inference-memory-requirements) for long-context generation. Memory efficient caches focus on trading off speed for reduced memory usage. This is especially important for large language models (LLMs) and if your hardware is memory constrained. + +### Offloaded cache + +The [`OffloadedCache`] saves GPU memory by moving the KV cache for most model layers to the CPU. Only the current layer cache is maintained on the GPU during a models `forward` iteration over the layers. [`OffloadedCache`] asynchronously prefetches the next layer cache and sends the previous layer cache back to the CPU. + +This cache strategy always generates the same result as [`DynamicCache`] and works as a drop-in replacement or fallback. You may want to use [`OffloadedCache`] if you have a GPU and you're getting out-of-memory (OOM) errors. + +> [!WARNING] +> You may notice a small degradation in generation throughput compared to [`DynamicCache`] depending on your model and generation choices (context size, number of generated tokens, number of beams, etc.). + +Enable [`OffloadedCache`] by configuring `cache_implementation="offloaded"` in either [`GenerationConfig`] or [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +ckpt = "microsoft/Phi-3-mini-4k-instruct" +tokenizer = AutoTokenizer.from_pretrained(ckpt) +model = AutoModelForCausalLM.from_pretrained(ckpt, torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("Fun fact: The shortest", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=23, cache_implementation="offloaded") +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +Fun fact: The shortest war in history was between Britain and Zanzibar on August 27, 1896. +``` + +The example below shows how you can fallback on [`OffloadedCache`] if you run out of memory. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +def resilient_generate(model, *args, **kwargs): + oom = False + try: + return model.generate(*args, **kwargs) + except torch.cuda.OutOfMemoryError as e: + print(e) + print("retrying with cache_implementation='offloaded'") + oom = True + if oom: + torch.cuda.empty_cache() + kwargs["cache_implementation"] = "offloaded" + return model.generate(*args, **kwargs) + +ckpt = "microsoft/Phi-3-mini-4k-instruct" +tokenizer = AutoTokenizer.from_pretrained(ckpt) +model = AutoModelForCausalLM.from_pretrained(ckpt, torch_dtype=torch.float16).to("cuda:0") +prompt = ["okay "*1000 + "Fun fact: The most"] +inputs = tokenizer(prompt, return_tensors="pt").to(model.device) +beams = { "num_beams": 40, "num_beam_groups": 40, "num_return_sequences": 40, "diversity_penalty": 1.0, "max_new_tokens": 23, "early_stopping": True, } +out = resilient_generate(model, **inputs, **beams) +responses = tokenizer.batch_decode(out[:,-28:], skip_special_tokens=True) +``` + +### Quantized cache + +The [`QuantizedCache`] reduces memory requirements by quantizing the KV values to a lower precision. [`QuantizedCache`] currently supports two quantization backends. + +- [`HQQQuantizedCache`] supports int2, int4, and int8 datatypes. +- [`QuantoQuantizedCache`] supports int2 and int4 datatypes. This is the default quantization backend. + +> [!WARNING] +> Quantizing the cache can harm latency if the context length is short and there is enough GPU memory available for generation without enabling cache quantization. Try to find a balance between memory efficiency and latency. + +Enable [`QuantizedCache`] by configuring `cache_implementation="quantized"` in [`GenerationConfig`], and indicate the quantization backend in [`QuantizedCacheConfig`]. Any additional quantization related parameters should also be passed either as a dict or an instance of [`QuantizedCacheConfig`]. You should use the default values for these additional parameters unless you're running out-of-memory. In that case, consider decreasing the residual length. + + + + +For [`HQQQuantizedCache`], we recommend setting the `axis-key` and `axis-value` parameters to `1`. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, HQQQuantizedCache, QuantizedCacheConfig + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="quantized", cache_config={"axis-key": 1, "axis-value": 1, "backend": "hqq"}) +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +I like rock music because it's loud and energetic. It's a great way to express myself and rel +``` + + + + +For [`QuantoQuantizedCache`], we recommend setting the `axis-key` and `axis-value` parameters to `0`. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, QuantoQuantizedCache, QuantizedCacheConfig + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("I like rock music because", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="quantized", cache_config={"nbits": 4, "axis-key": 0, "axis-value": 0, "backend": "quanto"}) +print(tokenizer.batch_decode(out, skip_special_tokens=True)[0]) +I like rock music because it's loud and energetic. It's a great way to express myself and rel +``` + + + + +### Sink cache + +[`SinkCache`] is capable of generating very long sequences ("infinite length" according to the paper) by only retaining a few initial tokens from the sequence. These are called the *sink tokens* because they account for a significant portion of the attention scores during generation. Subsequent tokens are discarded on a sliding windowed basis, and only the latest `window_size` tokens are kept. This means most of the previous knowledge is discarded. + +The sink tokens allow a model to maintain stable performance even when it's dealing with very long text sequences. + +Enable [`SinkCache`] by initializing it first with the [window_length](https://hf.co/docs/transformers/main/en/internal/generation_utils#transformers.SinkCache.window_length) and [num_sink_tokens](https://hf.co/docs/transformers/main/en/internal/generation_utils#transformers.SinkCache.num_sink_tokens) parameters before passing it to [past_key_values](https://hf.co/docs/transformers/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput.past_key_values) in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, SinkCache + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("This is a long story about unicorns, fairies and magic.", return_tensors="pt").to(model.device) + +past_key_values = SinkCache(window_length=256, num_sink_tokens=4) +out = model.generate(**inputs, do_sample=False, max_new_tokens=30, past_key_values=past_key_values) +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +"This is a long story about unicorns, fairies and magic. It is a fantasy world where unicorns and fairies live together in harmony. The story follows a young girl named Lily" +``` + +## Speed optimized caches + +The default [`DynamicCache`] prevents you from taking advantage of just-in-time (JIT) optimizations because the cache size isn't fixed. JIT optimizations enable you to maximize latency at the expense of memory usage. All of the following cache types are compatible with JIT optimizations like [torch.compile](./llm_optims#static-kv-cache-and-torchcompile) to accelerate generation. + +### Static cache + +A [`StaticCache`] pre-allocates a specific maximum cache size for the kv pairs. You can generate up to the maximum cache size without needing to modify it. + +Enable [`StaticCache`] by configuring `cache_implementation="static"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="static") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +"Hello, my name is [Your Name], and I am a [Your Profession] with [Number of Years] of" +``` + +### Offloaded static cache + +The [`OffloadedStaticCache`] is very similar to the [OffloadedCache](#offloaded-cache) except the cache size is set to a maximum cache size. Otherwise, [`OffloadedStaticCache`] only keeps the current layer cache on the GPU and the rest are moved to the CPU. + +Enable [`OffloadedStaticCache`] by configuring `cache_implementation="offloaded_static"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", torch_dtype=torch.float16, device_map="auto") +inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=20, cache_implementation="offloaded_static") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +"Hello, my name is [Your Name], and I am a [Your Profession] with [Number of Years] of" +``` +Cache offloading requires a CUDA GPU. + +### Sliding window cache + +[`SlidingWindowCache`] implements a sliding window over the previous kv pairs, and only keeps the last `sliding_window` tokens. This cache type is designed to only work with models that support *sliding window attention*, such as [Mistral](./model_doc/mistral). Older kv states are discarded and replaced by new kv states. + +Enable [`SlidingWindowCache`] by configuring `cache_implementation="sliding_window"` in [`~GenerationMixin.generate`]. + +```py +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM, SinkCache + +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16).to("cuda:0") +inputs = tokenizer("Yesterday I was on a rock concert and.", return_tensors="pt").to(model.device) + +out = model.generate(**inputs, do_sample=False, max_new_tokens=30, cache_implementation="sliding_window") +tokenizer.batch_decode(out, skip_special_tokens=True)[0] +``` + +## Model caches + +Some model types, like encoder-decoder models or [Gemma2](./model_doc/gemma2) and [Mamba](./model_doc/mamba), have dedicated cache classes. + +### Encoder-decoder cache + +[`EncoderDecoderCache`] is designed for encoder-decoder models. It manages both the self-attention and cross-attention caches to ensure storage and retrieval of previous kv pairs. It is possible to individually set a different cache type for the encoder and decoder. + +This cache type doesn't require any setup. It can be used when calling [`~GenerationMixin.generate`] or a models `forward` method. + +> [!TIP] +> The [`EncoderDecoderCache`] currently only supports [Whisper](./model_doc/whisper). + +### Model-specific caches + +Some models have a unique way of storing past kv pairs or states that is not compatible with any other cache classes. + +[Gemma2](./model_doc/gemma2) requires [`HybridCache`], which uses a combination of [`SlidingWindowCache`] for sliding window attention and [`StaticCache`] for global attention under the hood. + +[Mamba](./model_doc/mamba) requires [`MambaCache`] because the model doesn't have an attention mechanism or kv states. + +## Iterative generation + +A cache can also work in iterative generation settings where there is back-and-forth interaction with a model (chatbots). Like regular generation, iterative generation with a cache allows a model to efficiently handle ongoing conversations without recomputing the entire context at each step. + +For iterative generation with a cache, start by initializing an empty cache class and then you can feed in your new prompts. Keep track of dialogue history with a [chat template](./chat_templating). + +If you're using [`SinkCache`], the inputs need to be truncated to the maximum length because [`SinkCache`] can generate text that exceeds its maximum window size. However, the first input shouldn't exceed the maximum cache length. + +The example below demonstrates how to use a cache for iterative generation. + +```py +import torch +from transformers import AutoTokenizer,AutoModelForCausalLM +from transformers.cache_utils import ( + DynamicCache, + SinkCache, + StaticCache, + SlidingWindowCache, + QuantoQuantizedCache, + QuantizedCacheConfig, +) + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map='auto') +tokenizer = AutoTokenizer.from_pretrained(model_id) + +user_prompts = ["Hello, what's your name?", "Btw, yesterday I was on a rock concert."] + +past_key_values = DynamicCache() +max_cache_length = past_key_values.get_max_length() + +messages = [] +for prompt in user_prompts: + messages.append({"role": "user", "content": prompt}) + inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) + if isinstance(past_key_values, SinkCache): + inputs = {k: v[:, -max_cache_length:] for k, v in inputs.items()} + input_length = inputs["input_ids"].shape[1] + outputs = model.generate(**inputs, do_sample=False, max_new_tokens=256, past_key_values=past_key_values) + completion = tokenizer.decode(outputs[0, input_length: ], skip_special_tokens=True) + messages.append({"role": "assistant", "content": completion}) +``` + +## Prefill a cache + +In some situations, you may want to fill a [`Cache`] with kv pairs for a certain prefix prompt and reuse it to generate different sequences. + +The example below initializes a [`StaticCache`], and then caches an initial prompt. Now you can generate several sequences from the prefilled prompt. + +```py +import copy +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache, StaticCache + +model_id = "meta-llama/Llama-2-7b-chat-hf" +model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="cuda") +tokenizer = AutoTokenizer.from_pretrained(model_id) + +# Init StaticCache with big enough max-length (1024 tokens for the below example) +# You can also init a DynamicCache, if that suits you better +prompt_cache = StaticCache(config=model.config, max_batch_size=1, max_cache_len=1024, device="cuda", dtype=torch.bfloat16) + +INITIAL_PROMPT = "You are a helpful assistant. " +inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors="pt").to("cuda") +# This is the common prompt cached, we need to run forward without grad to be able to copy +with torch.no_grad(): + prompt_cache = model(**inputs_initial_prompt, past_key_values = prompt_cache).past_key_values + +prompts = ["Help me to write a blogpost about travelling.", "What is the capital of France?"] +responses = [] +for prompt in prompts: + new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors="pt").to("cuda") + past_key_values = copy.deepcopy(prompt_cache) + outputs = model.generate(**new_inputs, past_key_values=past_key_values,max_new_tokens=20) + response = tokenizer.batch_decode(outputs)[0] + responses.append(response) + +print(responses) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_optims.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_optims.md new file mode 100644 index 0000000000000000000000000000000000000000..7c9bc154ab6eb6e16cf3630011716cd99c1959cd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_optims.md @@ -0,0 +1,420 @@ + + +# Optimizing inference + +Inference with large language models (LLMs) can be challenging because they have to store and handle billions of parameters. To load a 70B parameter [Llama 2](https://hf.co/meta-llama/Llama-2-70b-hf) model, it requires 256GB of memory for full precision weights and 128GB of memory for half-precision weights. The most powerful GPUs today - the A100 and H100 - only have 80GB of memory. + +On top of the memory requirements, inference is slow because LLMs are called repeatedly to generate the next token. The input sequence increases as generation progresses, which takes longer and longer to process. + +This guide will show you how to optimize LLM inference to accelerate generation and reduce memory usage. + +> [!TIP] +> Try out [Text Generation Inference (TGI)](https://hf.co/docs/text-generation-inference), a Hugging Face library dedicated to deploying and serving highly optimized LLMs for inference. + +## Static kv-cache and torch.compile + +LLMs compute key-value (kv) values for each input token, and it performs the same kv computation each time because the generated output becomes part of the input. However, performing the same kv computation every time is not very efficient. + +A *kv-cache* stores the past keys and values instead of recomputing them each time. As a result, the kv-cache is dynamic and it grows with each generation step which prevents you from taking advantage of [torch.compile](./perf_torch_compile), a powerful optimization method that fuses PyTorch code into optimized kernels. + +The *static kv-cache* solves this issue by pre-allocating the kv-cache size to a maximum value, so you can combine it with [torch.compile](./perf_torch_compile) for up to a 4x speed up. Your speed up may vary depending on the model size (larger models have a smaller speed up) and hardware. + +> [!WARNING] +> Follow this [issue](https://github.com/huggingface/transformers/issues/28981) to track which models (Llama, Gemma, Mistral, etc.) support a static kv-cache and torch.compile. + +Depending on your task, there are several ways you can use the static kv-cache. + +1. For basic use cases, set [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) to `"static"` (recommended). +2. For multi-turn generation or a custom generation loop, initialize and handle [`StaticCache`] directly. +3. For more unique hardware or use cases, it may be better to compile the entire [`~GenerationMixin.generate`] function into a single graph. + +> [!TIP] +> Regardless of how you use the static kv-cache and torch.compile, left-pad your inputs with [pad_to_multiple_of](https://hf.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizer.__call__.pad_to_multiple_of) to a limited set of values to avoid shape-related recompilations. + + + + +1. Set the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) to `"static"` in a models [`GenerationConfig`]. +2. Call [torch.compile](./perf_torch_compile) to compile the forward pass with the static kv-cache. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.generation_config.cache_implementation = "static" + +model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) + +outputs = model.generate(**input_ids) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference'] +``` + +Under the hood, [`~GenerationMixin.generate`] attempts to reuse the same cache object to avoid recompilation at each call, which is critical to get the most out of [torch.compile](./perf_torch_compile). Be aware of the following to avoid triggering recompilation or if generation is slower than expected. + +1. If the batch size changes or the maximum output length increases between calls, the cache is reinitialized and recompiled. +2. The first several calls of the compiled function are slower because it is being compiled. + + + + +Directly initialize a [`StaticCache`] object and pass it to the `past_key_values` parameter in [`~GenerationMixin.generate`]. The [`StaticCache`] keeps the cache contents, so you can pass it to a new [`~GenerationMixin.generate`] call to continue generation, similar to a dynamic cache. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, StaticCache +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) +prompt_length = input_ids.input_ids.shape[1] +model.generation_config.max_new_tokens = 16 + +past_key_values = StaticCache( + config=model.config, + batch_size=1, + # If you plan to reuse the cache, make sure the cache length is large enough for all cases + max_cache_len=prompt_length+(model.generation_config.max_new_tokens*2), + device=model.device, + dtype=model.dtype +) +outputs = model.generate(**input_ids, past_key_values=past_key_values) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference frames. 2'] + +# pass in the generated text and the same cache object to continue generation from where it left off. Optionally, in a +# multi-turn conversation, append the new user input to the generated text. +new_input_ids = outputs +outputs = model.generate(new_input_ids, past_key_values=past_key_values) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference frames. 2. The speed of light is constant in all inertial reference frames. 3.'] +``` + +> [!TIP] +> To reuse [`StaticCache`] on a new prompt, use [`~StaticCache.reset`] to reset the cache contents between calls. + +Another option for using [`StaticCache`] is to pass it to a models forward pass using the same `past_key_values` argument. This allows you to write your own custom decoding function to decode the next token given the current token, position, and cache position of previously generated tokens. + +```py +from transformers import LlamaTokenizer, LlamaForCausalLM, StaticCache, logging +from transformers.testing_utils import CaptureLogger +import torch +from accelerate.test_utils.testing import get_backend + +prompts = [ + "Simply put, the theory of relativity states that ", + "My favorite all time favorite condiment is ketchup.", +] + +NUM_TOKENS_TO_GENERATE = 40 +torch_device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) + +tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", pad_token="", padding_side="right") +model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", device_map="sequential") +inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) + +def decode_one_tokens(model, cur_token, input_pos, cache_position, past_key_values): + logits = model( + cur_token, + position_ids=input_pos, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True + )[0] + new_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + return new_token +``` + +To enable static kv-cache and [torch.compile](./perf_torch_compile) with [`StaticCache`], follow the steps below. + +1. Initialize [`StaticCache`] before using the model for inference to configure parameters like the maximum batch size and sequence length. +2. Call [torch.compile](./perf_torch_compile) on the model to compile the forward pass with the static kv-cache. +3. se SDPBackend.MATH in the [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html) context manager to enable the native PyTorch C++ implementation of scaled dot product attention to speed up inference even more. + +```py +from torch.nn.attention import SDPBackend, sdpa_kernel + +batch_size, seq_length = inputs["input_ids"].shape +with torch.no_grad(): + past_key_values = StaticCache( + config=model.config, batch_size=2, max_cache_len=4096, device=torch_device, dtype=model.dtype + ) + cache_position = torch.arange(seq_length, device=torch_device) + generated_ids = torch.zeros( + batch_size, seq_length + NUM_TOKENS_TO_GENERATE + 1, dtype=torch.int, device=torch_device + ) + generated_ids[:, cache_position] = inputs["input_ids"].to(torch_device).to(torch.int) + + logits = model( + **inputs, cache_position=cache_position, past_key_values=past_key_values,return_dict=False, use_cache=True + )[0] + next_token = torch.argmax(logits[:, -1], dim=-1)[:, None] + generated_ids[:, seq_length] = next_token[:, 0] + + decode_one_tokens = torch.compile(decode_one_tokens, mode="reduce-overhead", fullgraph=True) + cache_position = torch.tensor([seq_length + 1], device=torch_device) + for _ in range(1, NUM_TOKENS_TO_GENERATE): + with sdpa_kernel(SDPBackend.MATH): + next_token = decode_one_tokens(model, next_token.clone(), None, cache_position, past_key_values) + generated_ids[:, cache_position] = next_token.int() + cache_position += 1 + +text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) +text +['Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light is the same for all observers, and 3) the laws of physics are the same for all observers.', + 'My favorite all time favorite condiment is ketchup. I love it on everything. I love it on my eggs, my fries, my chicken, my burgers, my hot dogs, my sandwiches, my salads, my p'] +``` + + + + +Compiling the entire [`~GenerationMixin.generate`] function also compiles the input preparation logit processor operations, and more, in addition to the forward pass. With this approach, you don't need to initialize [`StaticCache`] or set the [cache_implementation](https://hf.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.cache_implementation) parameter. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" # To prevent long warnings :) + +tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b") +model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", torch_dtype="auto", device_map="auto") + +model.generate = torch.compile(model.generate, mode="reduce-overhead", fullgraph=True) +input_text = "The theory of special relativity states " +input_ids = tokenizer(input_text, return_tensors="pt").to(model.device.type) + +outputs = model.generate(**input_ids) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The theory of special relativity states 1. The speed of light is constant in all inertial reference'] +``` + +This usage pattern is more appropriate for unique hardware or use cases, but there are several drawbacks to consider. + +1. Compilation is much slower. +2. Parameters must be configured through [`GenerationConfig`]. +3. Many warnings and exceptions are suppressed. We recommend testing the uncompiled model first. +4. Many features are unavailable at the moment. For example, generation does not stop if an `EOS` token is selected. + + + + +## Decoding strategies + +Decoding can also be optimized to accelerate generation. You can use a lightweight assistant model to generate candidate tokens faster than the LLM itself or you can use a variant of this decoding strategy that works especially well for input-grounded tasks. + +### Speculative decoding + +> [!TIP] +> For a more in-depth explanation, take a look at the [Assisted Generation: a new direction toward low-latency text generation](https://hf.co/blog/assisted-generation) blog post! + +For each input token, the model weights are loaded each time during the forward pass, which is slow and cumbersome when a model has billions of parameters. Speculative decoding alleviates this slowdown by using a second smaller and faster assistant model to generate candidate tokens that are verified by the larger model in a single forward pass. If the verified tokens are correct, the LLM essentially gets them for "free" without having to generate them itself. There is no degradation in accuracy because the verification forward pass ensures the same outputs are generated as if the LLM had generated them on its own. + +To get the largest speed up, the assistant model should be a lot smaller than the LLM so that it can generate tokens quickly. The assistant and LLM model must also share the same tokenizer to avoid re-encoding and decoding tokens. + +> [!WARNING] +> Speculative decoding is only supported for the greedy search and sampling decoding strategies, and it doesn't support batched inputs. + +Enable speculative decoding by loading an assistant model and passing it to [`~GenerationMixin.generate`]. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +from accelerate.test_utils.testing import get_backend + +device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, assistant_model=assistant_model) +tokenizer.batch_decode(outputs, skip_special_tokens=True) +["Einstein's theory of relativity states that the speed of light is constant. "] +``` + + + + +For speculative sampling decoding, add the [do_sample](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.do_sample) and [temperature](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.temperature) parameters to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +from accelerate.test_utils.testing import get_backend + +device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("Einstein's theory of relativity states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=True, temperature=0.7) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +["Einstein's theory of relativity states that motion in the universe is not a straight line.\n"] +``` + + + + +### Prompt lookup decoding + +Prompt lookup decoding is a variant of speculative decoding that is also compatible with greedy search and sampling. Prompt lookup works especially well for input-grounded tasks - such as summarization - where there is often overlapping words between the prompt and output. These overlapping n-grams are used as the LLM candidate tokens. + +To enable prompt lookup decoding, specify the number of tokens that should be overlapping in the [prompt_lookup_num_tokens](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.prompt_lookup_num_tokens) parameter. Then pass this parameter to [`~GenerationMixin.generate`]. + + + + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +from accelerate.test_utils.testing import get_backend + +device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("The second law of thermodynamics states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +assistant_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m").to(device) +outputs = model.generate(**inputs, prompt_lookup_num_tokens=3) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['The second law of thermodynamics states that entropy increases with temperature. '] +``` + + + + +For prompt lookup decoding with sampling, add the [do_sample](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.do_sample) and [temperature](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig.temperature) parameters to [`~GenerationMixin.generate`]. + +```py +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +from accelerate.test_utils.testing import get_backend + +device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) + +tokenizer = AutoTokenizer.from_pretrained("facebook/opt-1.3b") +inputs = tokenizer("The second law of thermodynamics states", return_tensors="pt").to(device) + +model = AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b", torch_dtype="auto").to(device) +outputs = model.generate(**inputs, prompt_lookup_num_tokens=3, do_sample=True, temperature=0.7) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +["The second law of thermodynamics states that energy cannot be created nor destroyed. It's not a"] +``` + + + + +## Attention + +A known issue with transformer models is that the self-attention mechanism grows quadratically in compute and memory with the number of input tokens. This limitation is only magnified in LLMs which handles much longer sequences. To address this, try FlashAttention2 or PyTorch's scaled dot product attention (SDPA), which are more memory efficient attention implementations. + +### FlashAttention-2 + +FlashAttention and [FlashAttention-2](./perf_infer_gpu_one#flashattention-2) break up the attention computation into smaller chunks and reduces the number of intermediate read/write operations to the GPU memory to speed up inference. FlashAttention-2 improves on the original FlashAttention algorithm by also parallelizing over sequence length dimension and better partitioning work on the hardware to reduce synchronization and communication overhead. + +To use FlashAttention-2, set [attn_implementation](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.PreTrainedModel.from_pretrained.attn_implementation) to `"flash_attention_2"` in [`~PreTrainedModel.from_pretrained`]. + +```py +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + +quant_config = BitsAndBytesConfig(load_in_8bit=True) +model = AutoModelForCausalLM.from_pretrained( + "google/gemma-2b", + quantization_config=quant_config, + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2", +) +``` + +### PyTorch scaled dot product attention + +Scaled dot product attention (SDPA) is automatically enabled in PyTorch 2.0 and it supports FlashAttention, xFormers, and PyTorch's C++ implementation. SDPA chooses the most performant attention algorithm if you're using a CUDA backend. For other backends, SDPA defaults to the PyTorch C++ implementation. + +> [!TIP] +> SDPA automaticallysupports FlashAttention-2 as long as you have the latest PyTorch version installed. + +Use the [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html) context manager to explicitly enable or disable any of the four attention algorithms. For example, use `SDPBackend.FLASH_ATTENTION` to enable FlashAttention. + +```py +import torch +from torch.nn.attention import SDPBackend, sdpa_kernel +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained( + "google/gemma-2b", + torch_dtype=torch.bfloat16, +) + +with sdpa_kernel(SDPBackend.FLASH_ATTENTION): + outputs = model.generate(**inputs) +``` + +## Quantization + +Quantization reduces the size of model weights by storing them in a lower precision. This translates to lower memory usage and makes loading LLMs for inference more accessible if you're constrained by GPU memory. + +If you aren't limited by your GPU, you don't necessarily need to quantize your model because it can increase latency slightly (except for AWQ and fused AWQ modules) due to the extra step required to quantize and dequantize the weights. + +> [!TIP] +> There are many quantization libraries (see the [Quantization](./quantization) guide for more details) available, such as Quanto, AQLM, VPTQ, AWQ, and AutoGPTQ. Feel free to try them out and see which one works best for your use case. We also recommend reading the [Overview of natively supported quantization schemes in 🤗 Transformers](https://hf.co/blog/overview-quantization-transformers) blog post which compares AutoGPTQ and bitsandbytes. + +Use the Model Memory Calculator below to estimate and compare how much memory is required to load a model. For example, try estimating the memory required to load [Mistral-7B-v0.1](https://hf.co/mistralai/Mistral-7B-v0.1). + + + +To load a model in half-precision, set the [torch_dtype](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.PreTrainedModel.from_pretrained.torch_dtype) parameter in [`~transformers.AutoModelForCausalLM.from_pretrained`] to `torch.bfloat16`. This requires 13.74GB of memory. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM +import torch + +model = AutoModelForCausalLM.from_pretrained( + "mistralai/Mistral-7B-v0.1", torch_dtype=torch.bfloat16, device_map="auto", +) +``` + +To load a quantized model (8-bit or 4-bit), try [bitsandbytes](https://hf.co/docs/bitsandbytes) and set the [load_in_4bit](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.BitsAndBytesConfig.load_in_4bit) or [load_in_8bit](https://hf.co/docs/transformers/main/en/main_classes/text_generation#transformers.BitsAndBytesConfig.load_in_8bit) parameters to `True`. Loading the model in 8-bits only requires 6.87 GB of memory. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig +import torch + +quant_config = BitsAndBytesConfig(load_in_8bit=True) +model = AutoModelForCausalLM.from_pretrained( + "mistralai/Mistral-7B-v0.1", quantization_config=quant_config, device_map="auto" +) +``` diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..d86765720241d08805b8f3fd49b9a45fadb83726 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial.md @@ -0,0 +1,289 @@ + + +# Text generation + +[[open-in-colab]] + +Text generation is the most popular application for large language models (LLMs). A LLM is trained to generate the next word (token) given some initial text (prompt) along with its own generated outputs up to a predefined length or when it reaches an end-of-sequence (`EOS`) token. + +In Transformers, the [`~GenerationMixin.generate`] API handles text generation, and it is available for all models with generative capabilities. + +This guide will show you the basics of text generation with [`~GenerationMixin.generate`] and some common pitfalls to avoid. + +## Default generate + +Before you begin, it's helpful to install [bitsandbytes](https://hf.co/docs/bitsandbytes/index) to quantize really large models to reduce their memory usage. + +```bash +!pip install -U transformers bitsandbytes +``` +Bitsandbytes supports multiple backends in addition to CUDA-based GPUs. Refer to the multi-backend installation [guide](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend) to learn more. + +Load a LLM with [`~PreTrainedModel.from_pretrained`] and add the following two parameters to reduce the memory requirements. + +- `device_map="auto"` enables Accelerates' [Big Model Inference](./models#big-model-inference) feature for automatically initiating the model skeleton and loading and dispatching the model weights across all available devices, starting with the fastest device (GPU). +- `quantization_config` is a configuration object that defines the quantization settings. This examples uses bitsandbytes as the quantization backend (see the [Quantization](./quantization/overview) section for more available backends) and it loads the model in [4-bits](./quantization/bitsandbytes). + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig + +quantization_config = BitsAndBytesConfig(load_in_4bit=True) +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto", quantization_config=quantization_config) +``` + +Tokenize your input, and set the [`~PreTrainedTokenizer.padding_side`] parameter to `"left"` because a LLM is not trained to continue generation from padding tokens. The tokenizer returns the input ids and attention mask. + +> [!TIP] +> Process more than one prompt at a time by passing a list of strings to the tokenizer. Batch the inputs to improve throughput at a small cost to latency and memory. + +```py +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda") +``` + +Pass the inputs to [`~GenerationMixin.generate`] to generate tokens, and [`~PreTrainedTokenizer.batch_decode`] the generated tokens back to text. + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +"A list of colors: red, blue, green, yellow, orange, purple, pink," +``` + +## Generation configuration + +All generation settings are contained in [`GenerationConfig`]. In the example above, the generation settings are derived from the `generation_config.json` file of [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1). A default decoding strategy is used when no configuration is saved with a model. + +Inspect the configuration through the `generation_config` attribute. It only shows values that are different from the default configuration, in this case, the `bos_token_id` and `eos_token_id`. + +```py +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto") +model.generation_config +GenerationConfig { + "bos_token_id": 1, + "eos_token_id": 2 +} +``` + +You can customize [`~GenerationMixin.generate`] by overriding the parameters and values in [`GenerationConfig`]. Some of the most commonly adjusted parameters are [max_new_tokens](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.max_new_tokens), [num_beams](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.num_beams), [do_sample](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.do_sample), and [num_return_sequences](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig.num_return_sequences). + +```py +# enable beam search sampling strategy +model.generate(**inputs, num_beams=4, do_sample=True) +``` + +[`~GenerationMixin.generate`] can also be extended with external libraries or custom code. The `logits_processor` parameter accepts custom [`LogitsProcessor`] instances for manipulating the next token probability distribution. `stopping_criteria` supports custom [`StoppingCriteria`] to stop text generation. Check out the [logits-processor-zoo](https://github.com/NVIDIA/logits-processor-zoo) for more examples of external [`~GenerationMixin.generate`]-compatible extensions. + +Refer to the [Generation strategies](./generation_strategies) guide to learn more about search, sampling, and decoding strategies. + +### Saving + +Create an instance of [`GenerationConfig`] and specify the decoding parameters you want. + +```py +from transformers import AutoModelForCausalLM, GenerationConfig + +model = AutoModelForCausalLM.from_pretrained("my_account/my_model") +generation_config = GenerationConfig( + max_new_tokens=50, do_sample=True, top_k=50, eos_token_id=model.config.eos_token_id +) +``` + +Use [`~GenerationConfig.save_pretrained`] to save a specific generation configuration and set the `push_to_hub` parameter to `True` to upload it to the Hub. + +```py +generation_config.save_pretrained("my_account/my_model", push_to_hub=True) +``` + +Leave the `config_file_name` parameter empty. This parameter should be used when storing multiple generation configurations in a single directory. It gives you a way to specify which generation configuration to load. You can create different configurations for different generative tasks (creative text generation with sampling, summarization with beam search) for use with a single model. + +```py +from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, GenerationConfig + +tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small") +model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") + +translation_generation_config = GenerationConfig( + num_beams=4, + early_stopping=True, + decoder_start_token_id=0, + eos_token_id=model.config.eos_token_id, + pad_token=model.config.pad_token_id, +) + +translation_generation_config.save_pretrained("/tmp", config_file_name="translation_generation_config.json", push_to_hub=True) + +generation_config = GenerationConfig.from_pretrained("/tmp", config_file_name="translation_generation_config.json") +inputs = tokenizer("translate English to French: Configuration files are easy to use!", return_tensors="pt") +outputs = model.generate(**inputs, generation_config=generation_config) +print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +``` + +## Pitfalls + +The section below covers some common issues you may encounter during text generation and how to solve them. + +### Output length + +[`~GenerationMixin.generate`] returns up to 20 tokens by default unless otherwise specified in a models [`GenerationConfig`]. It is highly recommended to manually set the number of generated tokens with the [`max_new_tokens`] parameter to control the output length. [Decoder-only](https://hf.co/learn/nlp-course/chapter1/6?fw=pt) models returns the initial prompt along with the generated tokens. + +```py +model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda") +``` + + + + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5' +``` + + + + +```py +generated_ids = model.generate(**model_inputs, max_new_tokens=50) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,' +``` + + + + +### Decoding strategy + +The default decoding strategy in [`~GenerationMixin.generate`] is *greedy search*, which selects the next most likely token, unless otherwise specified in a models [`GenerationConfig`]. While this decoding strategy works well for input-grounded tasks (transcription, translation), it is not optimal for more creative use cases (story writing, chat applications). + +For example, enable a [multinomial sampling](./generation_strategies#multinomial-sampling) strategy to generate more diverse outputs. Refer to the [Generation strategy](./generation_strategies) guide for more decoding strategies. + +```py +model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda") +``` + + + + +```py +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + + + + +```py +generated_ids = model.generate(**model_inputs, do_sample=True) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + + + + +### Padding side + +Inputs need to be padded if they don't have the same length. But LLMs aren't trained to continue generation from padding tokens, which means the [`~PreTrainedTokenizer.padding_side`] parameter needs to be set to the left of the input. + + + + +```py +model_inputs = tokenizer( + ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +).to("cuda") +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 33333333333' +``` + + + + +```py +tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left") +tokenizer.pad_token = tokenizer.eos_token +model_inputs = tokenizer( + ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt" +).to("cuda") +generated_ids = model.generate(**model_inputs) +tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +'1, 2, 3, 4, 5, 6,' +``` + + + + +### Prompt format + +Some models and tasks expect a certain input prompt format, and if the format is incorrect, the model returns a suboptimal output. You can learn more about prompting in the [prompt engineering](./tasks/prompting) guide. + +For example, a chat model expects the input as a [chat template](./chat_templating). Your prompt should include a `role` and `content` to indicate who is participating in the conversation. If you try to pass your prompt as a single string, the model doesn't always return the expected output. + +```py +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha") +model = AutoModelForCausalLM.from_pretrained( + "HuggingFaceH4/zephyr-7b-alpha", device_map="auto", load_in_4bit=True +) +``` + + + + +```py +prompt = """How many cats does it take to change a light bulb? Reply as a pirate.""" +model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +input_length = model_inputs.input_ids.shape[1] +generated_ids = model.generate(**model_inputs, max_new_tokens=50) +print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"Aye, matey! 'Tis a simple task for a cat with a keen eye and nimble paws. First, the cat will climb up the ladder, carefully avoiding the rickety rungs. Then, with" +``` + + + + +```py +messages = [ + { + "role": "system", + "content": "You are a friendly chatbot who always responds in the style of a pirate", + }, + {"role": "user", "content": "How many cats does it take to change a light bulb?"}, +] +model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda") +input_length = model_inputs.shape[1] +generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=50) +print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) +"Arr, matey! According to me beliefs, 'twas always one cat to hold the ladder and another to climb up it an’ change the light bulb, but if yer looking to save some catnip, maybe yer can +``` + + + + +## Resources + +Take a look below for some more specific and specialized text generation libraries. + +- [Optimum](https://github.com/huggingface/optimum): an extension of Transformers focused on optimizing training and inference on specific hardware devices +- [Outlines](https://github.com/dottxt-ai/outlines): a library for constrained text generation (generate JSON files for example). +- [SynCode](https://github.com/uiuc-focal-lab/syncode): a library for context-free grammar guided generation (JSON, SQL, Python). +- [Text Generation Inference](https://github.com/huggingface/text-generation-inference): a production-ready server for LLMs. +- [Text generation web UI](https://github.com/oobabooga/text-generation-webui): a Gradio web UI for text generation. +- [logits-processor-zoo](https://github.com/NVIDIA/logits-processor-zoo): additional logits processors for controlling text generation. \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial_optimization.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial_optimization.md new file mode 100644 index 0000000000000000000000000000000000000000..c7c53765a2f8a9fc20dc12c9b1fc9223a1cc1d95 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/llm_tutorial_optimization.md @@ -0,0 +1,782 @@ + + +# Optimizing LLMs for Speed and Memory + +[[open-in-colab]] + +Large Language Models (LLMs) such as GPT3/4, [Falcon](https://huggingface.co/tiiuae/falcon-40b), and [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) are rapidly advancing in their ability to tackle human-centric tasks, establishing themselves as essential tools in modern knowledge-based industries. +Deploying these models in real-world tasks remains challenging, however: + +- To exhibit near-human text understanding and generation capabilities, LLMs currently require to be composed of billions of parameters (see [Kaplan et al](https://arxiv.org/abs/2001.08361), [Wei et. al](https://arxiv.org/abs/2206.07682)). This consequently amplifies the memory demands for inference. +- In many real-world tasks, LLMs need to be given extensive contextual information. This necessitates the model's capability to manage very long input sequences during inference. + +The crux of these challenges lies in augmenting the computational and memory capabilities of LLMs, especially when handling expansive input sequences. + +In this guide, we will go over the effective techniques for efficient LLM deployment: + +1. **Lower Precision:** Research has shown that operating at reduced numerical precision, namely [8-bit and 4-bit](./main_classes/quantization.md) can achieve computational advantages without a considerable decline in model performance. + +2. **Flash Attention:** Flash Attention is a variation of the attention algorithm that not only provides a more memory-efficient approach but also realizes increased efficiency due to optimized GPU memory utilization. + +3. **Architectural Innovations:** Considering that LLMs are always deployed in the same way during inference, namely autoregressive text generation with a long input context, specialized model architectures have been proposed that allow for more efficient inference. The most important advancement in model architectures hereby are [Alibi](https://arxiv.org/abs/2108.12409), [Rotary embeddings](https://arxiv.org/abs/2104.09864), [Multi-Query Attention (MQA)](https://arxiv.org/abs/1911.02150) and [Grouped-Query-Attention (GQA)]((https://arxiv.org/abs/2305.13245)). + +Throughout this guide, we will offer an analysis of auto-regressive generation from a tensor's perspective. We delve into the pros and cons of adopting lower precision, provide a comprehensive exploration of the latest attention algorithms, and discuss improved LLM architectures. While doing so, we run practical examples showcasing each of the feature improvements. + +## 1. Lower Precision + +Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors. + +At the time of writing this guide, LLMs consist of at least a couple billion parameters. Each parameter thereby is made of a decimal number, e.g. `4.5689` which is usually stored in either [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format), or [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) format. This allows us to easily compute the memory requirement to load the LLM into memory: + +> *Loading the weights of a model having X billion parameters requires roughly 4 * X GB of VRAM in float32 precision* + +Nowadays, models are however rarely trained in full float32 precision, but usually in bfloat16 precision or less frequently in float16 precision. Therefore the rule of thumb becomes: + +> *Loading the weights of a model having X billion parameters requires roughly 2 * X GB of VRAM in bfloat16/float16 precision* + +For shorter text inputs (less than 1024 tokens), the memory requirement for inference is very much dominated by the memory requirement to load the weights. Therefore, for now, let's assume that the memory requirement for inference is equal to the memory requirement to load the model into the GPU VRAM. + +To give some examples of how much VRAM it roughly takes to load a model in bfloat16: + +- **GPT3** requires 2 \* 175 GB = **350 GB** VRAM +- [**Bloom**](https://huggingface.co/bigscience/bloom) requires 2 \* 176 GB = **352 GB** VRAM +- [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) requires 2 \* 70 GB = **140 GB** VRAM +- [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) requires 2 \* 40 GB = **80 GB** VRAM +- [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) requires 2 \* 30 GB = **60 GB** VRAM +- [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) requires 2 \* 15.5 = **31 GB** VRAM + +As of writing this document, the largest GPU chip on the market is the A100 & H100 offering 80GB of VRAM. Most of the models listed before require more than 80GB just to be loaded and therefore necessarily require [tensor parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) and/or [pipeline parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +🤗 Transformers now supports tensor parallelism for supported models having `base_tp_plan` in their respective config classes. Learn more about Tensor Parallelism [here](perf_train_gpu_many#tensor-parallelism). Furthermore, if you're interested in writing models in a tensor-parallelism-friendly way, feel free to have a look at [the text-generation-inference library](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling). + +Naive pipeline parallelism is supported out of the box. For this, simply load the model with `device="auto"` which will automatically place the different layers on the available GPUs as explained [here](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference). +Note, however that while very effective, this naive pipeline parallelism does not tackle the issues of GPU idling. For this more advanced pipeline parallelism is required as explained [here](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism). + +If you have access to an 8 x 80GB A100 node, you could load BLOOM as follows + +```bash +!pip install transformers accelerate bitsandbytes optimum +``` +```python +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0) +``` + +By using `device_map="auto"` the attention layers would be equally distributed over all available GPUs. + +In this guide, we will use [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) as it can be run on a single 40 GB A100 GPU device chip. Note that all memory and speed optimizations that we will apply going forward, are equally applicable to models that require model or tensor parallelism. + +Since the model is loaded in bfloat16 precision, using our rule of thumb above, we would expect the memory requirement to run inference with `bigcode/octocoder` to be around 31 GB VRAM. Let's give it a try. + +We first load the model and tokenizer and then pass both to Transformers' [pipeline](https://huggingface.co/docs/transformers/main_classes/pipelines) object. + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline +import torch + +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0) +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +```python +prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:" + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +Nice, we can now directly use the result to convert bytes into Gigabytes. + +```python +def bytes_to_giga_bytes(bytes): + return bytes / 1024 / 1024 / 1024 +``` + +Let's call [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) to measure the peak GPU memory allocation. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +```bash +29.0260648727417 +``` + +Close enough to our back-of-the-envelope computation! We can see the number is not exactly correct as going from bytes to kilobytes requires a multiplication of 1024 instead of 1000. Therefore the back-of-the-envelope formula can also be understood as an "at most X GB" computation. +Note that if we had tried to run the model in full float32 precision, a whopping 64 GB of VRAM would have been required. + +> Almost all models are trained in bfloat16 nowadays, there is no reason to run the model in full float32 precision if [your GPU supports bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). Float32 won't give better inference results than the precision that was used to train the model. + +If you are unsure in which format the model weights are stored on the Hub, you can always look into the checkpoint's config under `"torch_dtype"`, *e.g.* [here](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). It is recommended to set the model to the same precision type as written in the config when loading with `from_pretrained(..., torch_dtype=...)` except when the original type is float32 in which case one can use both `float16` or `bfloat16` for inference. + + +Let's define a `flush(...)` function to free all allocated memory so that we can accurately measure the peak allocated GPU memory. + +```python +del pipe +del model + +import gc +import torch + +def flush(): + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() +``` + +Let's call it now for the next experiment. + +```python +flush() +``` +From the Accelerate library, you can also use a device-agnostic utility method called [release_memory](https://github.com/huggingface/accelerate/blob/29be4788629b772a3b722076e433b5b3b5c85da3/src/accelerate/utils/memory.py#L63), which takes various hardware backends like XPU, MLU, NPU, MPS, and more into account. + +```python +from accelerate.utils import release_memory +# ... + +release_memory(model) +``` + +Now what if your GPU does not have 32 GB of VRAM? It has been found that model weights can be quantized to 8-bit or 4-bits without a significant loss in performance (see [Dettmers et al.](https://arxiv.org/abs/2208.07339)). +Model can be quantized to even 3 or 2 bits with an acceptable loss in performance as shown in the recent [GPTQ paper](https://arxiv.org/abs/2210.17323) 🤯. + +Without going into too many details, quantization schemes aim at reducing the precision of weights while trying to keep the model's inference results as accurate as possible (*a.k.a* as close as possible to bfloat16). +Note that quantization works especially well for text generation since all we care about is choosing the *set of most likely next tokens* and don't really care about the exact values of the next token *logit* distribution. +All that matters is that the next token *logit* distribution stays roughly the same so that an `argmax` or `topk` operation gives the same results. + +There are various quantization techniques, which we won't discuss in detail here, but in general, all quantization techniques work as follows: + +- 1. Quantize all weights to the target precision +- 2. Load the quantized weights, and pass the input sequence of vectors in bfloat16 precision +- 3. Dynamically dequantize weights to bfloat16 to perform the computation with their input vectors in bfloat16 precision + +In a nutshell, this means that *inputs-weight matrix* multiplications, with \\( X \\) being the *inputs*, \\( W \\) being a weight matrix and \\( Y \\) being the output: + +$$ Y = X * W $$ + +are changed to + +$$ Y = X * \text{dequantize}(W) $$ + +for every matrix multiplication. Dequantization and re-quantization is performed sequentially for all weight matrices as the inputs run through the network graph. + +Therefore, inference time is often **not** reduced when using quantized weights, but rather increases. +Enough theory, let's give it a try! To quantize the weights with Transformers, you need to make sure that +the [`bitsandbytes`](https://github.com/bitsandbytes-foundation/bitsandbytes) library is installed. + +```bash +!pip install bitsandbytes +``` + +We can then load models in 8-bit quantization by simply adding a `load_in_8bit=True` flag to `from_pretrained`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0) +``` + +Now, let's run our example again and measure the memory usage. + +```python +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single +``` + +Nice, we're getting the same result as before, so no loss in accuracy! Let's look at how much memory was used this time. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +15.219234466552734 +``` + +Significantly less! We're down to just a bit over 15 GBs and could therefore run this model on consumer GPUs like the 4090. +We're seeing a very nice gain in memory efficiency and more or less no degradation to the model's output. However, we can also notice a slight slow-down during inference. + + +We delete the models and flush the memory again. +```python +del model +del pipe +``` + +```python +flush() +``` + +Let's see what peak GPU memory consumption 4-bit quantization gives. Quantizing the model to 4-bit can be done with the same API as before - this time by passing `load_in_4bit=True` instead of `load_in_8bit=True`. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, low_cpu_mem_usage=True, pad_token_id=0) + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):] +result +``` + +**Output**: +``` +Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument +``` + +We're almost seeing the same output text as before - just the `python` is missing just before the code snippet. Let's see how much memory was required. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +9.543574333190918 +``` + +Just 9.5GB! That's really not a lot for a >15 billion parameter model. + +While we see very little degradation in accuracy for our model here, 4-bit quantization can in practice often lead to different results compared to 8-bit quantization or full `bfloat16` inference. It is up to the user to try it out. + +Also note that inference here was again a bit slower compared to 8-bit quantization which is due to the more aggressive quantization method used for 4-bit quantization leading to \\( \text{quantize} \\) and \\( \text{dequantize} \\) taking longer during inference. + +```python +del model +del pipe +``` +```python +flush() +``` + +Overall, we saw that running OctoCoder in 8-bit precision reduced the required GPU VRAM from 32G GPU VRAM to only 15GB and running the model in 4-bit precision further reduces the required GPU VRAM to just a bit over 9GB. + +4-bit quantization allows the model to be run on GPUs such as RTX3090, V100, and T4 which are quite accessible for most people. + +For more information on quantization and to see how one can quantize models to require even less GPU VRAM memory than 4-bit, we recommend looking into the [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60) implementation. + +> As a conclusion, it is important to remember that model quantization trades improved memory efficiency against accuracy and in some cases inference time. + +If GPU memory is not a constraint for your use case, there is often no need to look into quantization. However many GPUs simply can't run LLMs without quantization methods and in this case, 4-bit and 8-bit quantization schemes are extremely useful tools. + +For more in-detail usage information, we strongly recommend taking a look at the [Transformers Quantization Docs](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage). +Next, let's look into how we can improve computational and memory efficiency by using better algorithms and an improved model architecture. + +## 2. Flash Attention + +Today's top-performing LLMs share more or less the same fundamental architecture that consists of feed-forward layers, activation layers, layer normalization layers, and most crucially, self-attention layers. + +Self-attention layers are central to Large Language Models (LLMs) in that they enable the model to understand the contextual relationships between input tokens. +However, the peak GPU memory consumption for self-attention layers grows *quadratically* both in compute and memory complexity with number of input tokens (also called *sequence length*) that we denote in the following by \\( N \\) . +While this is not really noticeable for shorter input sequences (of up to 1000 input tokens), it becomes a serious problem for longer input sequences (at around 16000 input tokens). + +Let's take a closer look. The formula to compute the output \\( \mathbf{O} \\) of a self-attention layer for an input \\( \mathbf{X} \\) of length \\( N \\) is: + +$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$ + +\\( \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) is thereby the input sequence to the attention layer. The projections \\( \mathbf{Q} \\) and \\( \mathbf{K} \\) will each consist of \\( N \\) vectors resulting in the \\( \mathbf{QK}^T \\) being of size \\( N^2 \\) . + +LLMs usually have multiple attention heads, thus doing multiple self-attention computations in parallel. +Assuming, the LLM has 40 attention heads and runs in bfloat16 precision, we can calculate the memory requirement to store the \\( \mathbf{QK^T} \\) matrices to be \\( 40 * 2 * N^2 \\) bytes. For \\( N=1000 \\) only around 50 MB of VRAM are needed, however, for \\( N=16000 \\) we would need 19 GB of VRAM, and for \\( N=100,000 \\) we would need almost 1TB just to store the \\( \mathbf{QK}^T \\) matrices. + +Long story short, the default self-attention algorithm quickly becomes prohibitively memory-expensive for large input contexts. + +As LLMs improve in text comprehension and generation, they are applied to increasingly complex tasks. While models once handled the translation or summarization of a few sentences, they now manage entire pages, demanding the capability to process extensive input lengths. + +How can we get rid of the exorbitant memory requirements for large input lengths? We need a new way to compute the self-attention mechanism that gets rid of the \\( QK^T \\) matrix. [Tri Dao et al.](https://arxiv.org/abs/2205.14135) developed exactly such a new algorithm and called it **Flash Attention**. + +In a nutshell, Flash Attention breaks the \\(\mathbf{V} \times \text{Softmax}(\mathbf{QK}^T\\)) computation apart and instead computes smaller chunks of the output by iterating over multiple softmax computation steps: + +$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \text{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations} $$ + +with \\( s^a_{ij} \\) and \\( s^b_{ij} \\) being some softmax normalization statistics that need to be recomputed for every \\( i \\) and \\( j \\) . + +Please note that the whole Flash Attention is a bit more complex and is greatly simplified here as going in too much depth is out of scope for this guide. The reader is invited to take a look at the well-written [Flash Attention paper](https://arxiv.org/abs/2205.14135) for more details. + +The main takeaway here is: + +> By keeping track of softmax normalization statistics and by using some smart mathematics, Flash Attention gives **numerical identical** outputs compared to the default self-attention layer at a memory cost that only increases linearly with \\( N \\) . + +Looking at the formula, one would intuitively say that Flash Attention must be much slower compared to the default self-attention formula as more computation needs to be done. Indeed Flash Attention requires more FLOPs compared to normal attention as the softmax normalization statistics have to constantly be recomputed (see [paper](https://arxiv.org/abs/2205.14135) for more details if interested) + +> However, Flash Attention is much faster in inference compared to default attention which comes from its ability to significantly reduce the demands on the slower, high-bandwidth memory of the GPU (VRAM), focusing instead on the faster on-chip memory (SRAM). + +Essentially, Flash Attention makes sure that all intermediate write and read operations can be done using the fast *on-chip* SRAM memory instead of having to access the slower VRAM memory to compute the output vector \\( \mathbf{O} \\) . + +In practice, there is currently absolutely no reason to **not** use Flash Attention if available. The algorithm gives mathematically the same outputs, and is both faster and more memory-efficient. + +Let's look at a practical example. + +Our OctoCoder model now gets a significantly longer input prompt which includes a so-called *system prompt*. System prompts are used to steer the LLM into a better assistant that is tailored to the users' task. +In the following, we use a system prompt that will make OctoCoder a better coding assistant. + +```python +system_prompt = """Below are a series of dialogues between various people and an AI technical assistant. +The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable. +The assistant is happy to help with code questions and will do their best to understand exactly what is needed. +It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer. +That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful. + +The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests). +The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data. + +----- + +Question: Write a function that takes two lists and returns a list that has alternating elements from each input list. + +Answer: Sure. Here is a function that does that. + +def alternating(list1, list2): + results = [] + for i in range(len(list1)): + results.append(list1[i]) + results.append(list2[i]) + return results + +Question: Can you write some test cases for this function? + +Answer: Sure, here are some tests. + +assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3] +assert alternating([True, False], [4, 5]) == [True, 4, False, 5] +assert alternating([], []) == [] + +Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end. + +Answer: Here is the modified function. + +def alternating(list1, list2): + results = [] + for i in range(min(len(list1), len(list2))): + results.append(list1[i]) + results.append(list2[i]) + if len(list1) > len(list2): + results.extend(list1[i+1:]) + else: + results.extend(list2[i+1:]) + return results + +----- +""" +``` +For demonstration purposes, we duplicate the system prompt by ten so that the input length is long enough to observe Flash Attention's memory savings. +We append the original text prompt `"Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"` + +```python +long_prompt = 10 * system_prompt + prompt +``` + +We instantiate our model again in bfloat16 precision. + +```python +model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto") +tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder") + +pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) +``` + +Let's now run the model just like before *without Flash Attention* and measure the peak GPU memory requirement and inference time. + +```python +import time + +start_time = time.time() +result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**Output**: +``` +Generated in 10.96854019165039 seconds. +Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef +```` + +We're getting the same output as before, however this time, the model repeats the answer multiple times until it's 60 tokens cut-off. This is not surprising as we've repeated the system prompt ten times for demonstration purposes and thus cued the model to repeat itself. + +**Note** that the system prompt should not be repeated ten times in real-world applications - one time is enough! + +Let's measure the peak GPU memory requirement. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +```bash +37.668193340301514 +``` + +As we can see the peak GPU memory requirement is now significantly higher than in the beginning, which is largely due to the longer input sequence. Also the generation takes a little over a minute now. + +We call `flush()` to free GPU memory for our next experiment. + +```python +flush() +``` + +For comparison, let's run the same function, but enable Flash Attention instead. +To do so, we convert the model to [BetterTransformer](https://huggingface.co/docs/optimum/bettertransformer/overview) and by doing so enabling PyTorch's [SDPA self-attention](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) which in turn is able to use Flash Attention. + +```python +model.to_bettertransformer() +``` + +Now we run the exact same code snippet as before and under the hood Transformers will make use of Flash Attention. + +```py +start_time = time.time() +with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): + result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):] + +print(f"Generated in {time.time() - start_time} seconds.") +result +``` + +**Output**: +``` +Generated in 3.0211617946624756 seconds. + Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef +``` + +We're getting the exact same result as before, but can observe a very significant speed-up thanks to Flash Attention. + +Let's measure the memory consumption one last time. + +```python +bytes_to_giga_bytes(torch.cuda.max_memory_allocated()) +``` + +**Output**: +``` +32.617331981658936 +``` + +And we're almost back to our original 29GB peak GPU memory from the beginning. + +We can observe that we only use roughly 100MB more GPU memory when passing a very long input sequence with Flash Attention compared to passing a short input sequence as done in the beginning. + +```py +flush() +``` + +For more information on how to use Flash Attention, please have a look at [this doc page](https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2). + +## 3. Architectural Innovations + +So far we have looked into improving computational and memory efficiency by: + +- Casting the weights to a lower precision format +- Replacing the self-attention algorithm with a more memory- and compute efficient version + +Let's now look into how we can change the architecture of an LLM so that it is most effective and efficient for task that require long text inputs, *e.g.*: +- Retrieval augmented Questions Answering, +- Summarization, +- Chat + +Note that *chat* not only requires the LLM to handle long text inputs, but it also necessitates that the LLM is able to efficiently handle the back-and-forth dialogue between user and assistant (such as ChatGPT). + +Once trained, the fundamental LLM architecture is difficult to change, so it is important to make considerations about the LLM's tasks beforehand and accordingly optimize the model's architecture. +There are two important components of the model architecture that quickly become memory and/or performance bottlenecks for large input sequences. + +- The positional embeddings +- The key-value cache + +Let's go over each component in more detail + +### 3.1 Improving positional embeddings of LLMs + +Self-attention puts each token in relation to each other's tokens. +As an example, the \\( \text{Softmax}(\mathbf{QK}^T) \\) matrix of the text input sequence *"Hello", "I", "love", "you"* could look as follows: + +![](/blog/assets/163_optimize_llm/self_attn_tokens.png) + +Each word token is given a probability mass at which it attends all other word tokens and, therefore is put into relation with all other word tokens. E.g. the word *"love"* attends to the word *"Hello"* with 5%, to *"I"* with 30%, and to itself with 65%. + +A LLM based on self-attention, but without position embeddings would have great difficulties in understanding the positions of the text inputs to each other. +This is because the probability score computed by \\( \mathbf{QK}^T \\) relates each word token to each other word token in \\( O(1) \\) computations regardless of their relative positional distance to each other. +Therefore, for the LLM without position embeddings each token appears to have the same distance to all other tokens, *e.g.* differentiating between *"Hello I love you"* and *"You love I hello"* would be very challenging. + +For the LLM to understand sentence order, an additional *cue* is needed and is usually applied in the form of *positional encodings* (or also called *positional embeddings*). +Positional encodings, encode the position of each token into a numerical presentation that the LLM can leverage to better understand sentence order. + +The authors of the [*Attention Is All You Need*](https://arxiv.org/abs/1706.03762) paper introduced sinusoidal positional embeddings \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) . +where each vector \\( \mathbf{p}_i \\) is computed as a sinusoidal function of its position \\( i \\) . +The positional encodings are then simply added to the input sequence vectors \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) thereby cueing the model to better learn sentence order. + +Instead of using fixed position embeddings, others (such as [Devlin et al.](https://arxiv.org/abs/1810.04805)) used learned positional encodings for which the positional embeddings +\\( \mathbf{P} \\) are learned during training. + +Sinusoidal and learned position embeddings used to be the predominant methods to encode sentence order into LLMs, but a couple of problems related to these positional encodings were found: + + 1. Sinusoidal and learned position embeddings are both absolute positional embeddings, *i.e.* encoding a unique embedding for each position id: \\( 0, \ldots, N \\) . As shown by [Huang et al.](https://arxiv.org/abs/2009.13658) and [Su et al.](https://arxiv.org/abs/2104.09864), absolute positional embeddings lead to poor LLM performance for long text inputs. For long text inputs, it is advantageous if the model learns the relative positional distance input tokens have to each other instead of their absolute position. + 2. When using learned position embeddings, the LLM has to be trained on a fixed input length \\( N \\), which makes it difficult to extrapolate to an input length longer than what it was trained on. + +Recently, relative positional embeddings that can tackle the above mentioned problems have become more popular, most notably: + +- [Rotary Position Embedding (RoPE)](https://arxiv.org/abs/2104.09864) +- [ALiBi](https://arxiv.org/abs/2108.12409) + +Both *RoPE* and *ALiBi* argue that it's best to cue the LLM about sentence order directly in the self-attention algorithm as it's there that word tokens are put into relation with each other. More specifically, sentence order should be cued by modifying the \\( \mathbf{QK}^T \\) computation. + +Without going into too many details, *RoPE* notes that positional information can be encoded into query-key pairs, *e.g.* \\( \mathbf{q}_i \\) and \\( \mathbf{x}_j \\) by rotating each vector by an angle \\( \theta * i \\) and \\( \theta * j \\) respectively with \\( i, j \\) describing each vectors sentence position: + +$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j. $$ + +\\( \mathbf{R}_{\theta, i - j} \\) thereby represents a rotational matrix. \\( \theta \\) is *not* learned during training, but instead set to a pre-defined value that depends on the maximum input sequence length during training. + +> By doing so, the probability score between \\( \mathbf{q}_i \\) and \\( \mathbf{q}_j \\) is only affected if \\( i \ne j \\) and solely depends on the relative distance \\( i - j \\) regardless of each vector's specific positions \\( i \\) and \\( j \\) . + +*RoPE* is used in multiple of today's most important LLMs, such as: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**Llama**](https://arxiv.org/abs/2302.13971) +- [**PaLM**](https://arxiv.org/abs/2204.02311) + +As an alternative, *ALiBi* proposes a much simpler relative position encoding scheme. The relative distance that input tokens have to each other is added as a negative integer scaled by a pre-defined value `m` to each query-key entry of the \\( \mathbf{QK}^T \\) matrix right before the softmax computation. + +![](/blog/assets/163_optimize_llm/alibi.png) + +As shown in the [ALiBi](https://arxiv.org/abs/2108.12409) paper, this simple relative positional encoding allows the model to retain a high performance even at very long text input sequences. + +*ALiBi* is used in multiple of today's most important LLMs, such as: + +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +Both *RoPE* and *ALiBi* position encodings can extrapolate to input lengths not seen during training whereas it has been shown that extrapolation works much better out-of-the-box for *ALiBi* as compared to *RoPE*. +For ALiBi, one simply increases the values of the lower triangular position matrix to match the length of the input sequence. +For *RoPE*, keeping the same \\( \theta \\) that was used during training leads to poor results when passing text inputs much longer than those seen during training, *c.f* [Press et al.](https://arxiv.org/abs/2108.12409). However, the community has found a couple of effective tricks that adapt \\( \theta \\), thereby allowing *RoPE* position embeddings to work well for extrapolated text input sequences (see [here](https://github.com/huggingface/transformers/pull/24653)). + +> Both RoPE and ALiBi are relative positional embeddings that are *not* learned during training, but instead are based on the following intuitions: + - Positional cues about the text inputs should be given directly to the \\( QK^T \\) matrix of the self-attention layer + - The LLM should be incentivized to learn a constant *relative* distance positional encodings have to each other + - The further text input tokens are from each other, the lower the probability of their query-value probability. Both RoPE and ALiBi lower the query-key probability of tokens far away from each other. RoPE by decreasing their vector product by increasing the angle between the query-key vectors. ALiBi by adding large negative numbers to the vector product + +In conclusion, LLMs that are intended to be deployed in tasks that require handling large text inputs are better trained with relative positional embeddings, such as RoPE and ALiBi. Also note that even if an LLM with RoPE and ALiBi has been trained only on a fixed length of say \\( N_1 = 2048 \\) it can still be used in practice with text inputs much larger than \\( N_1 \\), like \\( N_2 = 8192 > N_1 \\) by extrapolating the positional embeddings. + +### 3.2 The key-value cache + +Auto-regressive text generation with LLMs works by iteratively putting in an input sequence, sampling the next token, appending the next token to the input sequence, and continuing to do so until the LLM produces a token that signifies that the generation has finished. + +Please have a look at [Transformer's Generate Text Tutorial](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) to get a more visual explanation of how auto-regressive generation works. + +Let's run a quick code snippet to show how auto-regressive works in practice. We will simply take the most likely next token via `torch.argmax`. + +```python +input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits = model(input_ids)["logits"][:, -1:] + next_token_id = torch.argmax(next_logits,dim=-1) + + input_ids = torch.cat([input_ids, next_token_id], dim=-1) + print("shape of input_ids", input_ids.shape) + +generated_text = tokenizer.batch_decode(input_ids[:, -5:]) +generated_text +``` + +**Output**: +``` +shape of input_ids torch.Size([1, 21]) +shape of input_ids torch.Size([1, 22]) +shape of input_ids torch.Size([1, 23]) +shape of input_ids torch.Size([1, 24]) +shape of input_ids torch.Size([1, 25]) +[' Here is a Python function'] +``` + +As we can see every time we increase the text input tokens by the just sampled token. + +With very few exceptions, LLMs are trained using the [causal language modeling objective](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) and therefore mask the upper triangle matrix of the attention score - this is why in the two diagrams above the attention scores are left blank (*a.k.a* have 0 probability). For a quick recap on causal language modeling you can refer to the [*Illustrated Self Attention blog*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention). + +As a consequence, tokens *never* depend on previous tokens, more specifically the \\( \mathbf{q}_i \\) vector is never put in relation with any key, values vectors \\( \mathbf{k}_j, \mathbf{v}_j \\) if \\( j > i \\) . Instead \\( \mathbf{q}_i \\) only attends to previous key-value vectors \\( \mathbf{k}_{m < i}, \mathbf{v}_{m < i} \text{ , for } m \in \{0, \ldots i - 1\} \\). In order to reduce unnecessary computation, one can therefore cache each layer's key-value vectors for all previous timesteps. + +In the following, we will tell the LLM to make use of the key-value cache by retrieving and forwarding it for each forward pass. +In Transformers, we can retrieve the key-value cache by passing the `use_cache` flag to the `forward` call and can then pass it with the current token. + +```python +past_key_values = None # past_key_values is the key-value cache +generated_tokens = [] +next_token_id = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda") + +for _ in range(5): + next_logits, past_key_values = model(next_token_id, past_key_values=past_key_values, use_cache=True).to_tuple() + next_logits = next_logits[:, -1:] + next_token_id = torch.argmax(next_logits, dim=-1) + + print("shape of input_ids", next_token_id.shape) + print("length of key-value cache", len(past_key_values[0][0])) # past_key_values are of shape [num_layers, 0 for k, 1 for v, batch_size, length, hidden_dim] + generated_tokens.append(next_token_id.item()) + +generated_text = tokenizer.batch_decode(generated_tokens) +generated_text +``` + +**Output**: +``` +shape of input_ids torch.Size([1, 1]) +length of key-value cache 20 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 21 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 22 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 23 +shape of input_ids torch.Size([1, 1]) +length of key-value cache 24 +[' Here', ' is', ' a', ' Python', ' function'] +``` + +As one can see, when using the key-value cache the text input tokens are *not* increased in length, but remain a single input vector. The length of the key-value cache on the other hand is increased by one at every decoding step. + +> Making use of the key-value cache means that the \\( \mathbf{QK}^T \\) is essentially reduced to \\( \mathbf{q}_c\mathbf{K}^T \\) with \\( \mathbf{q}_c \\) being the query projection of the currently passed input token which is *always* just a single vector. + +Using the key-value cache has two advantages: +- Significant increase in computational efficiency as less computations are performed compared to computing the full \\( \mathbf{QK}^T \\) matrix. This leads to an increase in inference speed +- The maximum required memory is not increased quadratically with the number of generated tokens, but only increases linearly. + +> One should *always* make use of the key-value cache as it leads to identical results and a significant speed-up for longer input sequences. Transformers has the key-value cache enabled by default when making use of the text pipeline or the [`generate` method](https://huggingface.co/docs/transformers/main_classes/text_generation). We have an entire guide dedicated to caches [here](./kv_cache). + + + +Note that, despite our advice to use key-value caches, your LLM output may be slightly different when you use them. This is a property of the matrix multiplication kernels themselves -- you can read more about it [here](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535). + + + +#### 3.2.1 Multi-round conversation + +The key-value cache is especially useful for applications such as chat where multiple passes of auto-regressive decoding are required. Let's look at an example. + +``` +User: How many people live in France? +Assistant: Roughly 75 million people live in France +User: And how many are in Germany? +Assistant: Germany has ca. 81 million inhabitants +``` + +In this chat, the LLM runs auto-regressive decoding twice: + 1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step. + 2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`. + +Two things should be noted here: + 1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`. + 2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g. would be the case when using an encoder-decoder architecture). + +In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface. + +```python +# Generation as usual +prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here" +model_inputs = tokenizer(prompt, return_tensors='pt') +generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True) +decoded_output = tokenizer.batch_decode(generation_output.sequences)[0] + +# Piping the returned `past_key_values` to speed up the next conversation round +prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here" +model_inputs = tokenizer(prompt, return_tensors='pt') +generation_output = model.generate( + **model_inputs, + past_key_values=generation_output.past_key_values, + max_new_tokens=60, + return_dict_in_generate=True +) +tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):] +``` + +**Output**: +``` + is a modified version of the function that returns Mega bytes instead. + +def bytes_to_megabytes(bytes): + return bytes / 1024 / 1024 + +Answer: The function takes a number of bytes as input and returns the number of +``` + +Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat. Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads. + +Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before. +The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers. +Computing this for our LLM at a hypothetical input sequence length of 16000 gives: + +```python +config = model.config +2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head +``` + +**Output**: +``` +7864320000 +``` + +Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves! +Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections. + +#### 3.2.2 Multi-Query-Attention (MQA) + +[Multi-Query-Attention](https://arxiv.org/abs/1911.02150) was proposed in Noam Shazeer's *Fast Transformer Decoding: One Write-Head is All You Need* paper. As the title says, Noam found out that instead of using `n_head` key-value projections weights, one can use a single head-value projection weight pair that is shared across all attention heads without that the model's performance significantly degrades. + +> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones. + +As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000. + +In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following. +In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://arxiv.org/abs/1911.02150). + +The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix. + +MQA has seen wide adoption by the community and is now used by many of the most popular LLMs: + +- [**Falcon**](https://huggingface.co/tiiuae/falcon-40b) +- [**PaLM**](https://arxiv.org/abs/2204.02311) +- [**MPT**](https://huggingface.co/mosaicml/mpt-30b) +- [**BLOOM**](https://huggingface.co/bigscience/bloom) + +Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA. + +#### 3.2.3 Grouped-Query-Attention (GQA) + +[Grouped-Query-Attention](https://arxiv.org/abs/2305.13245), as proposed by Ainslie et al. from Google, found that using MQA can often lead to quality degradation compared to using vanilla multi-key-value head projections. The paper argues that more model performance can be kept by less drastically reducing the number of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance. + +Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences. + +GQA was only recently proposed which is why there is less adoption at the time of writing this notebook. +The most notable application of GQA is [Llama-v2](https://huggingface.co/meta-llama/Llama-2-70b-hf). + +> As a conclusion, it is strongly recommended to make use of either GQA or MQA if the LLM is deployed with auto-regressive decoding and is required to handle large input sequences as is the case for example for chat. + + +## Conclusion + +The research community is constantly coming up with new, nifty ways to speed up inference time for ever-larger LLMs. As an example, one such promising research direction is [speculative decoding](https://arxiv.org/abs/2211.17192) where "easy tokens" are generated by smaller, faster language models and only "hard tokens" are generated by the LLM itself. Going into more detail is out of the scope of this notebook, but can be read upon in this [nice blog post](https://huggingface.co/blog/assisted-generation). + +The reason massive LLMs such as GPT3/4, Llama-2-70b, Claude, PaLM can run so quickly in chat-interfaces such as [Hugging Face Chat](https://huggingface.co/chat/) or ChatGPT is to a big part thanks to the above-mentioned improvements in precision, algorithms, and architecture. +Going forward, accelerators such as GPUs, TPUs, etc... will only get faster and allow for more memory, but one should nevertheless always make sure to use the best available algorithms and architectures to get the most bang for your buck 🤗 diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/agent.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/agent.md new file mode 100644 index 0000000000000000000000000000000000000000..ed0486b60128ec84c9b99099cb4b8f5e5163508b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/agent.md @@ -0,0 +1,167 @@ + + +# Agents & Tools + + + +Transformers Agents is an experimental API which is subject to change at any time. Results returned by the agents +can vary as the APIs or underlying models are prone to change. + + + +To learn more about agents and tools make sure to read the [introductory guide](../transformers_agents). This page +contains the API docs for the underlying classes. + +## Agents + +We provide two types of agents, based on the main [`Agent`] class: +- [`CodeAgent`] acts in one shot, generating code to solve the task, then executes it at once. +- [`ReactAgent`] acts step by step, each step consisting of one thought, then one tool call and execution. It has two classes: + - [`ReactJsonAgent`] writes its tool calls in JSON. + - [`ReactCodeAgent`] writes its tool calls in Python code. + +### Agent + +[[autodoc]] Agent + +### CodeAgent + +[[autodoc]] CodeAgent + +### React agents + +[[autodoc]] ReactAgent + +[[autodoc]] ReactJsonAgent + +[[autodoc]] ReactCodeAgent + +### ManagedAgent + +[[autodoc]] ManagedAgent + +## Tools + +### load_tool + +[[autodoc]] load_tool + +### tool + +[[autodoc]] tool + +### Tool + +[[autodoc]] Tool + +### Toolbox + +[[autodoc]] Toolbox + +### PipelineTool + +[[autodoc]] PipelineTool + +### launch_gradio_demo + +[[autodoc]] launch_gradio_demo + +### stream_to_gradio + +[[autodoc]] stream_to_gradio + +### ToolCollection + +[[autodoc]] ToolCollection + +## Engines + +You're free to create and use your own engines to be usable by the Agents framework. +These engines have the following specification: +1. Follow the [messages format](../chat_templating.md) for its input (`List[Dict[str, str]]`) and return a string. +2. Stop generating outputs *before* the sequences passed in the argument `stop_sequences` + +### TransformersEngine + +For convenience, we have added a `TransformersEngine` that implements the points above, taking a pre-initialized `Pipeline` as input. + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TransformersEngine + +>>> model_name = "HuggingFaceTB/SmolLM-135M-Instruct" +>>> tokenizer = AutoTokenizer.from_pretrained(model_name) +>>> model = AutoModelForCausalLM.from_pretrained(model_name) + +>>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) + +>>> engine = TransformersEngine(pipe) +>>> engine([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]) + +"What a " +``` + +[[autodoc]] TransformersEngine + +### HfApiEngine + +The `HfApiEngine` is an engine that wraps an [HF Inference API](https://huggingface.co/docs/api-inference/index) client for the execution of the LLM. + +```python +>>> from transformers import HfApiEngine + +>>> messages = [ +... {"role": "user", "content": "Hello, how are you?"}, +... {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, +... {"role": "user", "content": "No need to help, take it easy."}, +... ] + +>>> HfApiEngine()(messages, stop_sequences=["conversation"]) + +"That's very kind of you to say! It's always nice to have a relaxed " +``` + +[[autodoc]] HfApiEngine + + +## Agent Types + +Agents can handle any type of object in-between tools; tools, being completely multimodal, can accept and return +text, image, audio, video, among other types. In order to increase compatibility between tools, as well as to +correctly render these returns in ipython (jupyter, colab, ipython notebooks, ...), we implement wrapper classes +around these types. + +The wrapped objects should continue behaving as initially; a text object should still behave as a string, an image +object should still behave as a `PIL.Image`. + +These types have three specific purposes: + +- Calling `to_raw` on the type should return the underlying object +- Calling `to_string` on the type should return the object as a string: that can be the string in case of an `AgentText` + but will be the path of the serialized version of the object in other instances +- Displaying it in an ipython kernel should display the object correctly + +### AgentText + +[[autodoc]] transformers.agents.agent_types.AgentText + +### AgentImage + +[[autodoc]] transformers.agents.agent_types.AgentImage + +### AgentAudio + +[[autodoc]] transformers.agents.agent_types.AgentAudio diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/backbones.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/backbones.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1fc1dcbe1f202d9527441a6f625e5049054e9a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/backbones.md @@ -0,0 +1,60 @@ + + +# Backbone + +A backbone is a model used for feature extraction for higher level computer vision tasks such as object detection and image classification. Transformers provides an [`AutoBackbone`] class for initializing a Transformers backbone from pretrained model weights, and two utility classes: + +* [`~utils.BackboneMixin`] enables initializing a backbone from Transformers or [timm](https://hf.co/docs/timm/index) and includes functions for returning the output features and indices. +* [`~utils.BackboneConfigMixin`] sets the output features and indices of the backbone configuration. + +[timm](https://hf.co/docs/timm/index) models are loaded with the [`TimmBackbone`] and [`TimmBackboneConfig`] classes. + +Backbones are supported for the following models: + +* [BEiT](../model_doc/beit) +* [BiT](../model_doc/bit) +* [ConvNext](../model_doc/convnext) +* [ConvNextV2](../model_doc/convnextv2) +* [DiNAT](../model_doc/dinat) +* [DINOV2](../model_doc/dinov2) +* [FocalNet](../model_doc/focalnet) +* [MaskFormer](../model_doc/maskformer) +* [NAT](../model_doc/nat) +* [ResNet](../model_doc/resnet) +* [Swin Transformer](../model_doc/swin) +* [Swin Transformer v2](../model_doc/swinv2) +* [ViTDet](../model_doc/vitdet) + +## AutoBackbone + +[[autodoc]] AutoBackbone + +## BackboneMixin + +[[autodoc]] utils.BackboneMixin + +## BackboneConfigMixin + +[[autodoc]] utils.BackboneConfigMixin + +## TimmBackbone + +[[autodoc]] models.timm_backbone.TimmBackbone + +## TimmBackboneConfig + +[[autodoc]] models.timm_backbone.TimmBackboneConfig diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/callback.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/callback.md new file mode 100644 index 0000000000000000000000000000000000000000..99f76b7b05e43f855d2f76485bc8cbed42618541 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/callback.md @@ -0,0 +1,137 @@ + + +# Callbacks + +Callbacks are objects that can customize the behavior of the training loop in the PyTorch +[`Trainer`] (this feature is not yet implemented in TensorFlow) that can inspect the training loop +state (for progress reporting, logging on TensorBoard or other ML platforms...) and take decisions (like early +stopping). + +Callbacks are "read only" pieces of code, apart from the [`TrainerControl`] object they return, they +cannot change anything in the training loop. For customizations that require changes in the training loop, you should +subclass [`Trainer`] and override the methods you need (see [trainer](trainer) for examples). + +By default, `TrainingArguments.report_to` is set to `"all"`, so a [`Trainer`] will use the following callbacks. + +- [`DefaultFlowCallback`] which handles the default behavior for logging, saving and evaluation. +- [`PrinterCallback`] or [`ProgressCallback`] to display progress and print the + logs (the first one is used if you deactivate tqdm through the [`TrainingArguments`], otherwise + it's the second one). +- [`~integrations.TensorBoardCallback`] if tensorboard is accessible (either through PyTorch >= 1.4 + or tensorboardX). +- [`~integrations.WandbCallback`] if [wandb](https://www.wandb.com/) is installed. +- [`~integrations.CometCallback`] if [comet_ml](https://www.comet.com/site/) is installed. +- [`~integrations.MLflowCallback`] if [mlflow](https://www.mlflow.org/) is installed. +- [`~integrations.NeptuneCallback`] if [neptune](https://neptune.ai/) is installed. +- [`~integrations.AzureMLCallback`] if [azureml-sdk](https://pypi.org/project/azureml-sdk/) is + installed. +- [`~integrations.CodeCarbonCallback`] if [codecarbon](https://pypi.org/project/codecarbon/) is + installed. +- [`~integrations.ClearMLCallback`] if [clearml](https://github.com/allegroai/clearml) is installed. +- [`~integrations.DagsHubCallback`] if [dagshub](https://dagshub.com/) is installed. +- [`~integrations.FlyteCallback`] if [flyte](https://flyte.org/) is installed. +- [`~integrations.DVCLiveCallback`] if [dvclive](https://dvc.org/doc/dvclive) is installed. +- [`~integrations.SwanLabCallback`] if [swanlab](http://swanlab.cn/) is installed. + +If a package is installed but you don't wish to use the accompanying integration, you can change `TrainingArguments.report_to` to a list of just those integrations you want to use (e.g. `["azure_ml", "wandb"]`). + +The main class that implements callbacks is [`TrainerCallback`]. It gets the +[`TrainingArguments`] used to instantiate the [`Trainer`], can access that +Trainer's internal state via [`TrainerState`], and can take some actions on the training loop via +[`TrainerControl`]. + + +## Available Callbacks + +Here is the list of the available [`TrainerCallback`] in the library: + +[[autodoc]] integrations.CometCallback + - setup + +[[autodoc]] DefaultFlowCallback + +[[autodoc]] PrinterCallback + +[[autodoc]] ProgressCallback + +[[autodoc]] EarlyStoppingCallback + +[[autodoc]] integrations.TensorBoardCallback + +[[autodoc]] integrations.WandbCallback + - setup + +[[autodoc]] integrations.MLflowCallback + - setup + +[[autodoc]] integrations.AzureMLCallback + +[[autodoc]] integrations.CodeCarbonCallback + +[[autodoc]] integrations.NeptuneCallback + +[[autodoc]] integrations.ClearMLCallback + +[[autodoc]] integrations.DagsHubCallback + +[[autodoc]] integrations.FlyteCallback + +[[autodoc]] integrations.DVCLiveCallback + - setup + +[[autodoc]] integrations.SwanLabCallback + - setup + +## TrainerCallback + +[[autodoc]] TrainerCallback + +Here is an example of how to register a custom callback with the PyTorch [`Trainer`]: + +```python +class MyCallback(TrainerCallback): + "A callback that prints a message at the beginning of training" + + def on_train_begin(self, args, state, control, **kwargs): + print("Starting training") + + +trainer = Trainer( + model, + args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + callbacks=[MyCallback], # We can either pass the callback class this way or an instance of it (MyCallback()) +) +``` + +Another way to register a callback is to call `trainer.add_callback()` as follows: + +```python +trainer = Trainer(...) +trainer.add_callback(MyCallback) +# Alternatively, we can pass an instance of the callback class +trainer.add_callback(MyCallback()) +``` + +## TrainerState + +[[autodoc]] TrainerState + +## TrainerControl + +[[autodoc]] TrainerControl diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/configuration.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..0cfef06d3ce9caba4b91ed57e99124ba7c32122a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/configuration.md @@ -0,0 +1,32 @@ + + +# Configuration + +The base class [`PretrainedConfig`] implements the common methods for loading/saving a configuration +either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded +from HuggingFace's AWS S3 repository). + +Each derived config class implements model specific attributes. Common attributes present in all config classes are: +`hidden_size`, `num_attention_heads`, and `num_hidden_layers`. Text models further implement: +`vocab_size`. + + +## PretrainedConfig + +[[autodoc]] PretrainedConfig + - push_to_hub + - all diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/data_collator.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/data_collator.md new file mode 100644 index 0000000000000000000000000000000000000000..0da904f1131a9ecdc7adaead8bbbef0b87393678 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/data_collator.md @@ -0,0 +1,76 @@ + + +# Data Collator + +Data collators are objects that will form a batch by using a list of dataset elements as input. These elements are of +the same type as the elements of `train_dataset` or `eval_dataset`. + +To be able to build batches, data collators may apply some processing (like padding). Some of them (like +[`DataCollatorForLanguageModeling`]) also apply some random data augmentation (like random masking) +on the formed batch. + +Examples of use can be found in the [example scripts](../examples) or [example notebooks](../notebooks). + + +## Default data collator + +[[autodoc]] data.data_collator.default_data_collator + +## DefaultDataCollator + +[[autodoc]] data.data_collator.DefaultDataCollator + +## DataCollatorWithPadding + +[[autodoc]] data.data_collator.DataCollatorWithPadding + +## DataCollatorForTokenClassification + +[[autodoc]] data.data_collator.DataCollatorForTokenClassification + +## DataCollatorForSeq2Seq + +[[autodoc]] data.data_collator.DataCollatorForSeq2Seq + +## DataCollatorForLanguageModeling + +[[autodoc]] data.data_collator.DataCollatorForLanguageModeling + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorForWholeWordMask + +[[autodoc]] data.data_collator.DataCollatorForWholeWordMask + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorForPermutationLanguageModeling + +[[autodoc]] data.data_collator.DataCollatorForPermutationLanguageModeling + - numpy_mask_tokens + - tf_mask_tokens + - torch_mask_tokens + +## DataCollatorWithFlattening + +[[autodoc]] data.data_collator.DataCollatorWithFlattening + +# DataCollatorForMultipleChoice + +[[autodoc]] data.data_collator.DataCollatorForMultipleChoice diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/deepspeed.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..0b9e28656c0938be4264ae945e999b728a8e0fe7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/deepspeed.md @@ -0,0 +1,32 @@ + + +# DeepSpeed + +[DeepSpeed](https://github.com/deepspeedai/DeepSpeed), powered by Zero Redundancy Optimizer (ZeRO), is an optimization library for training and fitting very large models onto a GPU. It is available in several ZeRO stages, where each stage progressively saves more GPU memory by partitioning the optimizer state, gradients, parameters, and enabling offloading to a CPU or NVMe. DeepSpeed is integrated with the [`Trainer`] class and most of the setup is automatically taken care of for you. + +However, if you want to use DeepSpeed without the [`Trainer`], Transformers provides a [`HfDeepSpeedConfig`] class. + + + +Learn more about using DeepSpeed with [`Trainer`] in the [DeepSpeed](../deepspeed) guide. + + + +## HfDeepSpeedConfig + +[[autodoc]] integrations.HfDeepSpeedConfig + - all diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/executorch.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/executorch.md new file mode 100644 index 0000000000000000000000000000000000000000..3178085c9135be8a9721d2f24dfd3b427dbe5259 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/executorch.md @@ -0,0 +1,33 @@ + + + +# ExecuTorch + +[`ExecuTorch`](https://github.com/pytorch/executorch) is an end-to-end solution for enabling on-device inference capabilities across mobile and edge devices including wearables, embedded devices and microcontrollers. It is part of the PyTorch ecosystem and supports the deployment of PyTorch models with a focus on portability, productivity, and performance. + +ExecuTorch introduces well defined entry points to perform model, device, and/or use-case specific optimizations such as backend delegation, user-defined compiler transformations, memory planning, and more. The first step in preparing a PyTorch model for execution on an edge device using ExecuTorch is to export the model. This is achieved through the use of a PyTorch API called [`torch.export`](https://pytorch.org/docs/stable/export.html). + + +## ExecuTorch Integration + +An integration point is being developed to ensure that 🤗 Transformers can be exported using `torch.export`. The goal of this integration is not only to enable export but also to ensure that the exported artifact can be further lowered and optimized to run efficiently in `ExecuTorch`, particularly for mobile and edge use cases. + +[[autodoc]] TorchExportableModuleWithStaticCache + - forward + +[[autodoc]] convert_and_export_with_cache diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/feature_extractor.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/feature_extractor.md new file mode 100644 index 0000000000000000000000000000000000000000..d79c531be6df0dd4802aa7b8eddf9f6ecfe916ea --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/feature_extractor.md @@ -0,0 +1,39 @@ + + +# Feature Extractor + +A feature extractor is in charge of preparing input features for audio or vision models. This includes feature extraction from sequences, e.g., pre-processing audio files to generate Log-Mel Spectrogram features, feature extraction from images, e.g., cropping image files, but also padding, normalization, and conversion to NumPy, PyTorch, and TensorFlow tensors. + + +## FeatureExtractionMixin + +[[autodoc]] feature_extraction_utils.FeatureExtractionMixin + - from_pretrained + - save_pretrained + +## SequenceFeatureExtractor + +[[autodoc]] SequenceFeatureExtractor + - pad + +## BatchFeature + +[[autodoc]] BatchFeature + +## ImageFeatureExtractionMixin + +[[autodoc]] image_utils.ImageFeatureExtractionMixin diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/image_processor.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/image_processor.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf6ae95577f70ab2c58785874484368bd4629fc --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/image_processor.md @@ -0,0 +1,79 @@ + + +# Image Processor + +An image processor is in charge of preparing input features for vision models and post processing their outputs. This includes transformations such as resizing, normalization, and conversion to PyTorch, TensorFlow, Flax and Numpy tensors. It may also include model specific post-processing such as converting logits to segmentation masks. + +Fast image processors are available for a few models and more will be added in the future. They are based on the [torchvision](https://pytorch.org/vision/stable/index.html) library and provide a significant speed-up, especially when processing on GPU. +They have the same API as the base image processors and can be used as drop-in replacements. +To use a fast image processor, you need to install the `torchvision` library, and set the `use_fast` argument to `True` when instantiating the image processor: + +```python +from transformers import AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", use_fast=True) +``` +Note that `use_fast` will be set to `True` by default in a future release. + +When using a fast image processor, you can also set the `device` argument to specify the device on which the processing should be done. By default, the processing is done on the same device as the inputs if the inputs are tensors, or on the CPU otherwise. + +```python +from torchvision.io import read_image +from transformers import DetrImageProcessorFast + +images = read_image("image.jpg") +processor = DetrImageProcessorFast.from_pretrained("facebook/detr-resnet-50") +images_processed = processor(images, return_tensors="pt", device="cuda") +``` + +Here are some speed comparisons between the base and fast image processors for the `DETR` and `RT-DETR` models, and how they impact overall inference time: + +
+ +
+
+ +
+ +
+ +
+
+ +
+ +These benchmarks were run on an [AWS EC2 g5.2xlarge instance](https://aws.amazon.com/ec2/instance-types/g5/), utilizing an NVIDIA A10G Tensor Core GPU. + + +## ImageProcessingMixin + +[[autodoc]] image_processing_utils.ImageProcessingMixin + - from_pretrained + - save_pretrained + +## BatchFeature + +[[autodoc]] BatchFeature + +## BaseImageProcessor + +[[autodoc]] image_processing_utils.BaseImageProcessor + + +## BaseImageProcessorFast + +[[autodoc]] image_processing_utils_fast.BaseImageProcessorFast diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/keras_callbacks.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/keras_callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..c9932300dbc56986f107650a474a03233dcc3ae6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/keras_callbacks.md @@ -0,0 +1,28 @@ + + +# Keras callbacks + +When training a Transformers model with Keras, there are some library-specific callbacks available to automate common +tasks: + +## KerasMetricCallback + +[[autodoc]] KerasMetricCallback + +## PushToHubCallback + +[[autodoc]] PushToHubCallback diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/logging.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbdf9ae27ed1ce61b1a45556c569c7b9eb4b628 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/logging.md @@ -0,0 +1,119 @@ + + +# Logging + +🤗 Transformers has a centralized logging system, so that you can setup the verbosity of the library easily. + +Currently the default verbosity of the library is `WARNING`. + +To change the level of verbosity, just use one of the direct setters. For instance, here is how to change the verbosity +to the INFO level. + +```python +import transformers + +transformers.logging.set_verbosity_info() +``` + +You can also use the environment variable `TRANSFORMERS_VERBOSITY` to override the default verbosity. You can set it +to one of the following: `debug`, `info`, `warning`, `error`, `critical`, `fatal`. For example: + +```bash +TRANSFORMERS_VERBOSITY=error ./myprogram.py +``` + +Additionally, some `warnings` can be disabled by setting the environment variable +`TRANSFORMERS_NO_ADVISORY_WARNINGS` to a true value, like *1*. This will disable any warning that is logged using +[`logger.warning_advice`]. For example: + +```bash +TRANSFORMERS_NO_ADVISORY_WARNINGS=1 ./myprogram.py +``` + +Here is an example of how to use the same logger as the library in your own module or script: + +```python +from transformers.utils import logging + +logging.set_verbosity_info() +logger = logging.get_logger("transformers") +logger.info("INFO") +logger.warning("WARN") +``` + + +All the methods of this logging module are documented below, the main ones are +[`logging.get_verbosity`] to get the current level of verbosity in the logger and +[`logging.set_verbosity`] to set the verbosity to the level of your choice. In order (from the least +verbose to the most verbose), those levels (with their corresponding int values in parenthesis) are: + +- `transformers.logging.CRITICAL` or `transformers.logging.FATAL` (int value, 50): only report the most + critical errors. +- `transformers.logging.ERROR` (int value, 40): only report errors. +- `transformers.logging.WARNING` or `transformers.logging.WARN` (int value, 30): only reports error and + warnings. This is the default level used by the library. +- `transformers.logging.INFO` (int value, 20): reports error, warnings and basic information. +- `transformers.logging.DEBUG` (int value, 10): report all information. + +By default, `tqdm` progress bars will be displayed during model download. [`logging.disable_progress_bar`] and [`logging.enable_progress_bar`] can be used to suppress or unsuppress this behavior. + +## `logging` vs `warnings` + +Python has two logging systems that are often used in conjunction: `logging`, which is explained above, and `warnings`, +which allows further classification of warnings in specific buckets, e.g., `FutureWarning` for a feature or path +that has already been deprecated and `DeprecationWarning` to indicate an upcoming deprecation. + +We use both in the `transformers` library. We leverage and adapt `logging`'s `captureWarnings` method to allow +management of these warning messages by the verbosity setters above. + +What does that mean for developers of the library? We should respect the following heuristics: +- `warnings` should be favored for developers of the library and libraries dependent on `transformers` +- `logging` should be used for end-users of the library using it in every-day projects + +See reference of the `captureWarnings` method below. + +[[autodoc]] logging.captureWarnings + +## Base setters + +[[autodoc]] logging.set_verbosity_error + +[[autodoc]] logging.set_verbosity_warning + +[[autodoc]] logging.set_verbosity_info + +[[autodoc]] logging.set_verbosity_debug + +## Other functions + +[[autodoc]] logging.get_verbosity + +[[autodoc]] logging.set_verbosity + +[[autodoc]] logging.get_logger + +[[autodoc]] logging.enable_default_handler + +[[autodoc]] logging.disable_default_handler + +[[autodoc]] logging.enable_explicit_format + +[[autodoc]] logging.reset_format + +[[autodoc]] logging.enable_progress_bar + +[[autodoc]] logging.disable_progress_bar diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/model.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/model.md new file mode 100644 index 0000000000000000000000000000000000000000..15345a7b2af3fb0db28358e9904bf83df4aff272 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/model.md @@ -0,0 +1,73 @@ + + +# Models + +The base classes [`PreTrainedModel`], [`TFPreTrainedModel`], and +[`FlaxPreTrainedModel`] implement the common methods for loading/saving a model either from a local +file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's AWS +S3 repository). + +[`PreTrainedModel`] and [`TFPreTrainedModel`] also implement a few methods which +are common among all the models to: + +- resize the input token embeddings when new tokens are added to the vocabulary +- prune the attention heads of the model. + +The other methods that are common to each model are defined in [`~modeling_utils.ModuleUtilsMixin`] +(for the PyTorch models) and [`~modeling_tf_utils.TFModuleUtilsMixin`] (for the TensorFlow models) or +for text generation, [`~generation.GenerationMixin`] (for the PyTorch models), +[`~generation.TFGenerationMixin`] (for the TensorFlow models) and +[`~generation.FlaxGenerationMixin`] (for the Flax/JAX models). + + +## PreTrainedModel + +[[autodoc]] PreTrainedModel + - push_to_hub + - all + +Custom models should also include a `_supports_assign_param_buffer`, which determines if superfast init can apply +on the particular model. Signs that your model needs this are if `test_save_and_load_from_pretrained` fails. If so, +set this to `False`. + +## ModuleUtilsMixin + +[[autodoc]] modeling_utils.ModuleUtilsMixin + +## TFPreTrainedModel + +[[autodoc]] TFPreTrainedModel + - push_to_hub + - all + +## TFModelUtilsMixin + +[[autodoc]] modeling_tf_utils.TFModelUtilsMixin + +## FlaxPreTrainedModel + +[[autodoc]] FlaxPreTrainedModel + - push_to_hub + - all + +## Pushing to the Hub + +[[autodoc]] utils.PushToHubMixin + +## Sharded checkpoints + +[[autodoc]] modeling_utils.load_sharded_checkpoint diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/onnx.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/onnx.md new file mode 100644 index 0000000000000000000000000000000000000000..81d31c97e88dde23f3807cbcbc05820c3f06a48d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/onnx.md @@ -0,0 +1,54 @@ + + +# Exporting 🤗 Transformers models to ONNX + +🤗 Transformers provides a `transformers.onnx` package that enables you to +convert model checkpoints to an ONNX graph by leveraging configuration objects. + +See the [guide](../serialization) on exporting 🤗 Transformers models for more +details. + +## ONNX Configurations + +We provide three abstract classes that you should inherit from, depending on the +type of model architecture you wish to export: + +* Encoder-based models inherit from [`~onnx.config.OnnxConfig`] +* Decoder-based models inherit from [`~onnx.config.OnnxConfigWithPast`] +* Encoder-decoder models inherit from [`~onnx.config.OnnxSeq2SeqConfigWithPast`] + +### OnnxConfig + +[[autodoc]] onnx.config.OnnxConfig + +### OnnxConfigWithPast + +[[autodoc]] onnx.config.OnnxConfigWithPast + +### OnnxSeq2SeqConfigWithPast + +[[autodoc]] onnx.config.OnnxSeq2SeqConfigWithPast + +## ONNX Features + +Each ONNX configuration is associated with a set of _features_ that enable you +to export models for different types of topologies or tasks. + +### FeaturesManager + +[[autodoc]] onnx.features.FeaturesManager + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/optimizer_schedules.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/optimizer_schedules.md new file mode 100644 index 0000000000000000000000000000000000000000..9815b430ab0cdc2c1fc51f2e6e62b95844cc2833 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/optimizer_schedules.md @@ -0,0 +1,79 @@ + + +# Optimization + +The `.optimization` module provides: + +- an optimizer with weight decay fixed that can be used to fine-tuned models, and +- several schedules in the form of schedule objects that inherit from `_LRSchedule`: +- a gradient accumulation class to accumulate the gradients of multiple batches + +## AdamW (PyTorch) + +[[autodoc]] AdamW + +## AdaFactor (PyTorch) + +[[autodoc]] Adafactor + +## AdamWeightDecay (TensorFlow) + +[[autodoc]] AdamWeightDecay + +[[autodoc]] create_optimizer + +## Schedules + +### Learning Rate Schedules (PyTorch) + +[[autodoc]] SchedulerType + +[[autodoc]] get_scheduler + +[[autodoc]] get_constant_schedule + +[[autodoc]] get_constant_schedule_with_warmup + + + +[[autodoc]] get_cosine_schedule_with_warmup + + + +[[autodoc]] get_cosine_with_hard_restarts_schedule_with_warmup + + + +[[autodoc]] get_linear_schedule_with_warmup + + + +[[autodoc]] get_polynomial_decay_schedule_with_warmup + +[[autodoc]] get_inverse_sqrt_schedule + +[[autodoc]] get_wsd_schedule + +### Warmup (TensorFlow) + +[[autodoc]] WarmUp + +## Gradient Strategies + +### GradientAccumulator (TensorFlow) + +[[autodoc]] GradientAccumulator diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/output.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/output.md new file mode 100644 index 0000000000000000000000000000000000000000..300213d4513ebbf832e22828ac8be3164d5b95e6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/output.md @@ -0,0 +1,321 @@ + + +# Model outputs + +All models have outputs that are instances of subclasses of [`~utils.ModelOutput`]. Those are +data structures containing all the information returned by the model, but that can also be used as tuples or +dictionaries. + +Let's see how this looks in an example: + +```python +from transformers import BertTokenizer, BertForSequenceClassification +import torch + +tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +model = BertForSequenceClassification.from_pretrained("google-bert/bert-base-uncased") + +inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") +labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 +outputs = model(**inputs, labels=labels) +``` + +The `outputs` object is a [`~modeling_outputs.SequenceClassifierOutput`], as we can see in the +documentation of that class below, it means it has an optional `loss`, a `logits`, an optional `hidden_states` and +an optional `attentions` attribute. Here we have the `loss` since we passed along `labels`, but we don't have +`hidden_states` and `attentions` because we didn't pass `output_hidden_states=True` or +`output_attentions=True`. + + + +When passing `output_hidden_states=True` you may expect the `outputs.hidden_states[-1]` to match `outputs.last_hidden_state` exactly. +However, this is not always the case. Some models apply normalization or subsequent process to the last hidden state when it's returned. + + + + +You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you +will get `None`. Here for instance `outputs.loss` is the loss computed by the model, and `outputs.attentions` is +`None`. + +When considering our `outputs` object as tuple, it only considers the attributes that don't have `None` values. +Here for instance, it has two elements, `loss` then `logits`, so + +```python +outputs[:2] +``` + +will return the tuple `(outputs.loss, outputs.logits)` for instance. + +When considering our `outputs` object as dictionary, it only considers the attributes that don't have `None` +values. Here for instance, it has two keys that are `loss` and `logits`. + +We document here the generic model outputs that are used by more than one model type. Specific output types are +documented on their corresponding model page. + +## ModelOutput + +[[autodoc]] utils.ModelOutput + - to_tuple + +## BaseModelOutput + +[[autodoc]] modeling_outputs.BaseModelOutput + +## BaseModelOutputWithPooling + +[[autodoc]] modeling_outputs.BaseModelOutputWithPooling + +## BaseModelOutputWithCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithCrossAttentions + +## BaseModelOutputWithPoolingAndCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions + +## BaseModelOutputWithPast + +[[autodoc]] modeling_outputs.BaseModelOutputWithPast + +## BaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_outputs.BaseModelOutputWithPastAndCrossAttentions + +## Seq2SeqModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqModelOutput + +## CausalLMOutput + +[[autodoc]] modeling_outputs.CausalLMOutput + +## CausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_outputs.CausalLMOutputWithCrossAttentions + +## CausalLMOutputWithPast + +[[autodoc]] modeling_outputs.CausalLMOutputWithPast + +## MaskedLMOutput + +[[autodoc]] modeling_outputs.MaskedLMOutput + +## Seq2SeqLMOutput + +[[autodoc]] modeling_outputs.Seq2SeqLMOutput + +## NextSentencePredictorOutput + +[[autodoc]] modeling_outputs.NextSentencePredictorOutput + +## SequenceClassifierOutput + +[[autodoc]] modeling_outputs.SequenceClassifierOutput + +## Seq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_outputs.Seq2SeqSequenceClassifierOutput + +## MultipleChoiceModelOutput + +[[autodoc]] modeling_outputs.MultipleChoiceModelOutput + +## TokenClassifierOutput + +[[autodoc]] modeling_outputs.TokenClassifierOutput + +## QuestionAnsweringModelOutput + +[[autodoc]] modeling_outputs.QuestionAnsweringModelOutput + +## Seq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqQuestionAnsweringModelOutput + +## Seq2SeqSpectrogramOutput + +[[autodoc]] modeling_outputs.Seq2SeqSpectrogramOutput + +## SemanticSegmenterOutput + +[[autodoc]] modeling_outputs.SemanticSegmenterOutput + +## ImageClassifierOutput + +[[autodoc]] modeling_outputs.ImageClassifierOutput + +## ImageClassifierOutputWithNoAttention + +[[autodoc]] modeling_outputs.ImageClassifierOutputWithNoAttention + +## DepthEstimatorOutput + +[[autodoc]] modeling_outputs.DepthEstimatorOutput + +## Wav2Vec2BaseModelOutput + +[[autodoc]] modeling_outputs.Wav2Vec2BaseModelOutput + +## XVectorOutput + +[[autodoc]] modeling_outputs.XVectorOutput + +## Seq2SeqTSModelOutput + +[[autodoc]] modeling_outputs.Seq2SeqTSModelOutput + +## Seq2SeqTSPredictionOutput + +[[autodoc]] modeling_outputs.Seq2SeqTSPredictionOutput + +## SampleTSPredictionOutput + +[[autodoc]] modeling_outputs.SampleTSPredictionOutput + +## TFBaseModelOutput + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutput + +## TFBaseModelOutputWithPooling + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPooling + +## TFBaseModelOutputWithPoolingAndCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions + +## TFBaseModelOutputWithPast + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPast + +## TFBaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions + +## TFSeq2SeqModelOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqModelOutput + +## TFCausalLMOutput + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutput + +## TFCausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions + +## TFCausalLMOutputWithPast + +[[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithPast + +## TFMaskedLMOutput + +[[autodoc]] modeling_tf_outputs.TFMaskedLMOutput + +## TFSeq2SeqLMOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqLMOutput + +## TFNextSentencePredictorOutput + +[[autodoc]] modeling_tf_outputs.TFNextSentencePredictorOutput + +## TFSequenceClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFSequenceClassifierOutput + +## TFSeq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqSequenceClassifierOutput + +## TFMultipleChoiceModelOutput + +[[autodoc]] modeling_tf_outputs.TFMultipleChoiceModelOutput + +## TFTokenClassifierOutput + +[[autodoc]] modeling_tf_outputs.TFTokenClassifierOutput + +## TFQuestionAnsweringModelOutput + +[[autodoc]] modeling_tf_outputs.TFQuestionAnsweringModelOutput + +## TFSeq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_tf_outputs.TFSeq2SeqQuestionAnsweringModelOutput + +## FlaxBaseModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutput + +## FlaxBaseModelOutputWithPast + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPast + +## FlaxBaseModelOutputWithPooling + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPooling + +## FlaxBaseModelOutputWithPastAndCrossAttentions + +[[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions + +## FlaxSeq2SeqModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqModelOutput + +## FlaxCausalLMOutputWithCrossAttentions + +[[autodoc]] modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions + +## FlaxMaskedLMOutput + +[[autodoc]] modeling_flax_outputs.FlaxMaskedLMOutput + +## FlaxSeq2SeqLMOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqLMOutput + +## FlaxNextSentencePredictorOutput + +[[autodoc]] modeling_flax_outputs.FlaxNextSentencePredictorOutput + +## FlaxSequenceClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxSequenceClassifierOutput + +## FlaxSeq2SeqSequenceClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqSequenceClassifierOutput + +## FlaxMultipleChoiceModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxMultipleChoiceModelOutput + +## FlaxTokenClassifierOutput + +[[autodoc]] modeling_flax_outputs.FlaxTokenClassifierOutput + +## FlaxQuestionAnsweringModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxQuestionAnsweringModelOutput + +## FlaxSeq2SeqQuestionAnsweringModelOutput + +[[autodoc]] modeling_flax_outputs.FlaxSeq2SeqQuestionAnsweringModelOutput diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/peft.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/peft.md new file mode 100644 index 0000000000000000000000000000000000000000..85790f120ebf41a249bd0776ee2d45bfa3c92a41 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/peft.md @@ -0,0 +1,23 @@ + + +# PEFT + +The [`~integrations.PeftAdapterMixin`] provides functions from the [PEFT](https://huggingface.co/docs/peft/index) library for managing adapters with Transformers. This mixin currently supports LoRA, IA3, and AdaLora. Prefix tuning methods (prompt tuning, prompt learning) aren't supported because they can't be injected into a torch module. + +[[autodoc]] integrations.PeftAdapterMixin + - load_adapter + - add_adapter + - set_adapter + - disable_adapters + - enable_adapters + - active_adapters + - get_adapter_state_dict diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/pipelines.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/pipelines.md new file mode 100644 index 0000000000000000000000000000000000000000..59e474fcc49f7523f74a44cf761738e4aea9fcea --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/pipelines.md @@ -0,0 +1,501 @@ + + +# Pipelines + +The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of +the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity +Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering. See the +[task summary](../task_summary) for examples of use. + +There are two categories of pipeline abstractions to be aware about: + +- The [`pipeline`] which is the most powerful object encapsulating all other pipelines. +- Task-specific pipelines are available for [audio](#audio), [computer vision](#computer-vision), [natural language processing](#natural-language-processing), and [multimodal](#multimodal) tasks. + +## The pipeline abstraction + +The *pipeline* abstraction is a wrapper around all the other available pipelines. It is instantiated as any other +pipeline but can provide additional quality of life. + +Simple call on one item: + +```python +>>> pipe = pipeline("text-classification") +>>> pipe("This restaurant is awesome") +[{'label': 'POSITIVE', 'score': 0.9998743534088135}] +``` + +If you want to use a specific model from the [hub](https://huggingface.co) you can ignore the task if the model on +the hub already defines it: + +```python +>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli") +>>> pipe("This restaurant is awesome") +[{'label': 'NEUTRAL', 'score': 0.7313136458396912}] +``` + +To call a pipeline on many items, you can call it with a *list*. + +```python +>>> pipe = pipeline("text-classification") +>>> pipe(["This restaurant is awesome", "This restaurant is awful"]) +[{'label': 'POSITIVE', 'score': 0.9998743534088135}, + {'label': 'NEGATIVE', 'score': 0.9996669292449951}] +``` + +To iterate over full datasets it is recommended to use a `dataset` directly. This means you don't need to allocate +the whole dataset at once, nor do you need to do batching yourself. This should work just as fast as custom loops on +GPU. If it doesn't don't hesitate to create an issue. + +```python +import datasets +from transformers import pipeline +from transformers.pipelines.pt_utils import KeyDataset +from tqdm.auto import tqdm + +pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0) +dataset = datasets.load_dataset("superb", name="asr", split="test") + +# KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item +# as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset +for out in tqdm(pipe(KeyDataset(dataset, "file"))): + print(out) + # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} + # {"text": ....} + # .... +``` + +For ease of use, a generator is also possible: + + +```python +from transformers import pipeline + +pipe = pipeline("text-classification") + + +def data(): + while True: + # This could come from a dataset, a database, a queue or HTTP request + # in a server + # Caveat: because this is iterative, you cannot use `num_workers > 1` variable + # to use multiple threads to preprocess data. You can still have 1 thread that + # does the preprocessing while the main runs the big inference + yield "This is a test" + + +for out in pipe(data()): + print(out) + # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} + # {"text": ....} + # .... +``` + +[[autodoc]] pipeline + +## Pipeline batching + +All pipelines can use batching. This will work +whenever the pipeline uses its streaming ability (so when passing lists or `Dataset` or `generator`). + +```python +from transformers import pipeline +from transformers.pipelines.pt_utils import KeyDataset +import datasets + +dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised") +pipe = pipeline("text-classification", device=0) +for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): + print(out) + # [{'label': 'POSITIVE', 'score': 0.9998743534088135}] + # Exactly the same output as before, but the content are passed + # as batches to the model +``` + + + +However, this is not automatically a win for performance. It can be either a 10x speedup or 5x slowdown depending +on hardware, data and the actual model being used. + +Example where it's mostly a speedup: + + + +```python +from transformers import pipeline +from torch.utils.data import Dataset +from tqdm.auto import tqdm + +pipe = pipeline("text-classification", device=0) + + +class MyDataset(Dataset): + def __len__(self): + return 5000 + + def __getitem__(self, i): + return "This is a test" + + +dataset = MyDataset() + +for batch_size in [1, 8, 64, 256]: + print("-" * 30) + print(f"Streaming batch_size={batch_size}") + for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)): + pass +``` + +``` +# On GTX 970 +------------------------------ +Streaming no batching +100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s] +------------------------------ +Streaming batch_size=8 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s] +------------------------------ +Streaming batch_size=64 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s] +------------------------------ +Streaming batch_size=256 +100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s] +(diminishing returns, saturated the GPU) +``` + +Example where it's most a slowdown: + +```python +class MyDataset(Dataset): + def __len__(self): + return 5000 + + def __getitem__(self, i): + if i % 64 == 0: + n = 100 + else: + n = 1 + return "This is a test" * n +``` + +This is a occasional very long sentence compared to the other. In that case, the **whole** batch will need to be 400 +tokens long, so the whole batch will be [64, 400] instead of [64, 4], leading to the high slowdown. Even worse, on +bigger batches, the program simply crashes. + + +``` +------------------------------ +Streaming no batching +100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s] +------------------------------ +Streaming batch_size=8 +100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s] +------------------------------ +Streaming batch_size=64 +100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s] +------------------------------ +Streaming batch_size=256 + 0%| | 0/1000 [00:00 + for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)): +.... + q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head) +RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch) +``` + +There are no good (general) solutions for this problem, and your mileage may vary depending on your use cases. Rule of +thumb: + +For users, a rule of thumb is: + +- **Measure performance on your load, with your hardware. Measure, measure, and keep measuring. Real numbers are the + only way to go.** +- If you are latency constrained (live product doing inference), don't batch. +- If you are using CPU, don't batch. +- If you are using throughput (you want to run your model on a bunch of static data), on GPU, then: + + - If you have no clue about the size of the sequence_length ("natural" data), by default don't batch, measure and + try tentatively to add it, add OOM checks to recover when it will fail (and it will at some point if you don't + control the sequence_length.) + - If your sequence_length is super regular, then batching is more likely to be VERY interesting, measure and push + it until you get OOMs. + - The larger the GPU the more likely batching is going to be more interesting +- As soon as you enable batching, make sure you can handle OOMs nicely. + +## Pipeline chunk batching + +`zero-shot-classification` and `question-answering` are slightly specific in the sense, that a single input might yield +multiple forward pass of a model. Under normal circumstances, this would yield issues with `batch_size` argument. + +In order to circumvent this issue, both of these pipelines are a bit specific, they are `ChunkPipeline` instead of +regular `Pipeline`. In short: + + +```python +preprocessed = pipe.preprocess(inputs) +model_outputs = pipe.forward(preprocessed) +outputs = pipe.postprocess(model_outputs) +``` + +Now becomes: + + +```python +all_model_outputs = [] +for preprocessed in pipe.preprocess(inputs): + model_outputs = pipe.forward(preprocessed) + all_model_outputs.append(model_outputs) +outputs = pipe.postprocess(all_model_outputs) +``` + +This should be very transparent to your code because the pipelines are used in +the same way. + +This is a simplified view, since the pipeline can handle automatically the batch to ! Meaning you don't have to care +about how many forward passes you inputs are actually going to trigger, you can optimize the `batch_size` +independently of the inputs. The caveats from the previous section still apply. + +## Pipeline FP16 inference +Models can be run in FP16 which can be significantly faster on GPU while saving memory. Most models will not suffer noticeable performance loss from this. The larger the model, the less likely that it will. + +To enable FP16 inference, you can simply pass `torch_dtype=torch.float16` or `torch_dtype='float16'` to the pipeline constructor. Note that this only works for models with a PyTorch backend. Your inputs will be converted to FP16 internally. + +## Pipeline custom code + +If you want to override a specific pipeline. + +Don't hesitate to create an issue for your task at hand, the goal of the pipeline is to be easy to use and support most +cases, so `transformers` could maybe support your use case. + + +If you want to try simply you can: + +- Subclass your pipeline of choice + +```python +class MyPipeline(TextClassificationPipeline): + def postprocess(): + # Your code goes here + scores = scores * 100 + # And here + + +my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...) +# or if you use *pipeline* function, then: +my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline) +``` + +That should enable you to do all the custom code you want. + + +## Implementing a pipeline + +[Implementing a new pipeline](../add_new_pipeline) + +## Audio + +Pipelines available for audio tasks include the following. + +### AudioClassificationPipeline + +[[autodoc]] AudioClassificationPipeline + - __call__ + - all + +### AutomaticSpeechRecognitionPipeline + +[[autodoc]] AutomaticSpeechRecognitionPipeline + - __call__ + - all + +### TextToAudioPipeline + +[[autodoc]] TextToAudioPipeline + - __call__ + - all + + +### ZeroShotAudioClassificationPipeline + +[[autodoc]] ZeroShotAudioClassificationPipeline + - __call__ + - all + +## Computer vision + +Pipelines available for computer vision tasks include the following. + +### DepthEstimationPipeline +[[autodoc]] DepthEstimationPipeline + - __call__ + - all + +### ImageClassificationPipeline + +[[autodoc]] ImageClassificationPipeline + - __call__ + - all + +### ImageSegmentationPipeline + +[[autodoc]] ImageSegmentationPipeline + - __call__ + - all + +### ImageToImagePipeline + +[[autodoc]] ImageToImagePipeline + - __call__ + - all + +### ObjectDetectionPipeline + +[[autodoc]] ObjectDetectionPipeline + - __call__ + - all + +### VideoClassificationPipeline + +[[autodoc]] VideoClassificationPipeline + - __call__ + - all + +### ZeroShotImageClassificationPipeline + +[[autodoc]] ZeroShotImageClassificationPipeline + - __call__ + - all + +### ZeroShotObjectDetectionPipeline + +[[autodoc]] ZeroShotObjectDetectionPipeline + - __call__ + - all + +## Natural Language Processing + +Pipelines available for natural language processing tasks include the following. + +### FillMaskPipeline + +[[autodoc]] FillMaskPipeline + - __call__ + - all + +### QuestionAnsweringPipeline + +[[autodoc]] QuestionAnsweringPipeline + - __call__ + - all + +### SummarizationPipeline + +[[autodoc]] SummarizationPipeline + - __call__ + - all + +### TableQuestionAnsweringPipeline + +[[autodoc]] TableQuestionAnsweringPipeline + - __call__ + +### TextClassificationPipeline + +[[autodoc]] TextClassificationPipeline + - __call__ + - all + +### TextGenerationPipeline + +[[autodoc]] TextGenerationPipeline + - __call__ + - all + +### Text2TextGenerationPipeline + +[[autodoc]] Text2TextGenerationPipeline + - __call__ + - all + +### TokenClassificationPipeline + +[[autodoc]] TokenClassificationPipeline + - __call__ + - all + +### TranslationPipeline + +[[autodoc]] TranslationPipeline + - __call__ + - all + +### ZeroShotClassificationPipeline + +[[autodoc]] ZeroShotClassificationPipeline + - __call__ + - all + +## Multimodal + +Pipelines available for multimodal tasks include the following. + +### DocumentQuestionAnsweringPipeline + +[[autodoc]] DocumentQuestionAnsweringPipeline + - __call__ + - all + +### FeatureExtractionPipeline + +[[autodoc]] FeatureExtractionPipeline + - __call__ + - all + +### ImageFeatureExtractionPipeline + +[[autodoc]] ImageFeatureExtractionPipeline + - __call__ + - all + +### ImageToTextPipeline + +[[autodoc]] ImageToTextPipeline + - __call__ + - all + +### ImageTextToTextPipeline + +[[autodoc]] ImageTextToTextPipeline + - __call__ + - all + +### MaskGenerationPipeline + +[[autodoc]] MaskGenerationPipeline + - __call__ + - all + +### VisualQuestionAnsweringPipeline + +[[autodoc]] VisualQuestionAnsweringPipeline + - __call__ + - all + +## Parent class: `Pipeline` + +[[autodoc]] Pipeline diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/processors.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/processors.md new file mode 100644 index 0000000000000000000000000000000000000000..5e943fc9fdd5cc8f55daf78efd3c767ae4975e7a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/processors.md @@ -0,0 +1,163 @@ + + +# Processors + +Processors can mean two different things in the Transformers library: +- the objects that pre-process inputs for multi-modal models such as [Wav2Vec2](../model_doc/wav2vec2) (speech and text) + or [CLIP](../model_doc/clip) (text and vision) +- deprecated objects that were used in older versions of the library to preprocess data for GLUE or SQUAD. + +## Multi-modal processors + +Any multi-modal model will require an object to encode or decode the data that groups several modalities (among text, +vision and audio). This is handled by objects called processors, which group together two or more processing objects +such as tokenizers (for the text modality), image processors (for vision) and feature extractors (for audio). + +Those processors inherit from the following base class that implements the saving and loading functionality: + +[[autodoc]] ProcessorMixin + +## Deprecated processors + +All processors follow the same architecture which is that of the +[`~data.processors.utils.DataProcessor`]. The processor returns a list of +[`~data.processors.utils.InputExample`]. These +[`~data.processors.utils.InputExample`] can be converted to +[`~data.processors.utils.InputFeatures`] in order to be fed to the model. + +[[autodoc]] data.processors.utils.DataProcessor + +[[autodoc]] data.processors.utils.InputExample + +[[autodoc]] data.processors.utils.InputFeatures + +## GLUE + +[General Language Understanding Evaluation (GLUE)](https://gluebenchmark.com/) is a benchmark that evaluates the +performance of models across a diverse set of existing NLU tasks. It was released together with the paper [GLUE: A +multi-task benchmark and analysis platform for natural language understanding](https://openreview.net/pdf?id=rJ4km2R5t7) + +This library hosts a total of 10 processors for the following tasks: MRPC, MNLI, MNLI (mismatched), CoLA, SST2, STSB, +QQP, QNLI, RTE and WNLI. + +Those processors are: + +- [`~data.processors.utils.MrpcProcessor`] +- [`~data.processors.utils.MnliProcessor`] +- [`~data.processors.utils.MnliMismatchedProcessor`] +- [`~data.processors.utils.Sst2Processor`] +- [`~data.processors.utils.StsbProcessor`] +- [`~data.processors.utils.QqpProcessor`] +- [`~data.processors.utils.QnliProcessor`] +- [`~data.processors.utils.RteProcessor`] +- [`~data.processors.utils.WnliProcessor`] + +Additionally, the following method can be used to load values from a data file and convert them to a list of +[`~data.processors.utils.InputExample`]. + +[[autodoc]] data.processors.glue.glue_convert_examples_to_features + + +## XNLI + +[The Cross-Lingual NLI Corpus (XNLI)](https://www.nyu.edu/projects/bowman/xnli/) is a benchmark that evaluates the +quality of cross-lingual text representations. XNLI is crowd-sourced dataset based on [*MultiNLI*](http://www.nyu.edu/projects/bowman/multinli/): pairs of text are labeled with textual entailment annotations for 15 +different languages (including both high-resource language such as English and low-resource languages such as Swahili). + +It was released together with the paper [XNLI: Evaluating Cross-lingual Sentence Representations](https://arxiv.org/abs/1809.05053) + +This library hosts the processor to load the XNLI data: + +- [`~data.processors.utils.XnliProcessor`] + +Please note that since the gold labels are available on the test set, evaluation is performed on the test set. + +An example using these processors is given in the [run_xnli.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_xnli.py) script. + + +## SQuAD + +[The Stanford Question Answering Dataset (SQuAD)](https://rajpurkar.github.io/SQuAD-explorer//) is a benchmark that +evaluates the performance of models on question answering. Two versions are available, v1.1 and v2.0. The first version +(v1.1) was released together with the paper [SQuAD: 100,000+ Questions for Machine Comprehension of Text](https://arxiv.org/abs/1606.05250). The second version (v2.0) was released alongside the paper [Know What You Don't +Know: Unanswerable Questions for SQuAD](https://arxiv.org/abs/1806.03822). + +This library hosts a processor for each of the two versions: + +### Processors + +Those processors are: + +- [`~data.processors.utils.SquadV1Processor`] +- [`~data.processors.utils.SquadV2Processor`] + +They both inherit from the abstract class [`~data.processors.utils.SquadProcessor`] + +[[autodoc]] data.processors.squad.SquadProcessor + - all + +Additionally, the following method can be used to convert SQuAD examples into +[`~data.processors.utils.SquadFeatures`] that can be used as model inputs. + +[[autodoc]] data.processors.squad.squad_convert_examples_to_features + + +These processors as well as the aforementioned method can be used with files containing the data as well as with the +*tensorflow_datasets* package. Examples are given below. + + +### Example usage + +Here is an example using the processors as well as the conversion method using data files: + +```python +# Loading a V2 processor +processor = SquadV2Processor() +examples = processor.get_dev_examples(squad_v2_data_dir) + +# Loading a V1 processor +processor = SquadV1Processor() +examples = processor.get_dev_examples(squad_v1_data_dir) + +features = squad_convert_examples_to_features( + examples=examples, + tokenizer=tokenizer, + max_seq_length=max_seq_length, + doc_stride=args.doc_stride, + max_query_length=max_query_length, + is_training=not evaluate, +) +``` + +Using *tensorflow_datasets* is as easy as using a data file: + +```python +# tensorflow_datasets only handle Squad V1. +tfds_examples = tfds.load("squad") +examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=evaluate) + +features = squad_convert_examples_to_features( + examples=examples, + tokenizer=tokenizer, + max_seq_length=max_seq_length, + doc_stride=args.doc_stride, + max_query_length=max_query_length, + is_training=not evaluate, +) +``` + +Another example using these processors is given in the [run_squad.py](https://github.com/huggingface/transformers/tree/main/examples/legacy/question-answering/run_squad.py) script. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/quantization.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/quantization.md new file mode 100644 index 0000000000000000000000000000000000000000..6da5b8ce69b5e3aac0c91700751cb4a789670af2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/quantization.md @@ -0,0 +1,90 @@ + + +# Quantization + +Quantization techniques reduce memory and computational costs by representing weights and activations with lower-precision data types like 8-bit integers (int8). This enables loading larger models you normally wouldn't be able to fit into memory, and speeding up inference. Transformers supports the AWQ and GPTQ quantization algorithms and it supports 8-bit and 4-bit quantization with bitsandbytes. + +Quantization techniques that aren't supported in Transformers can be added with the [`HfQuantizer`] class. + + + +Learn how to quantize models in the [Quantization](../quantization) guide. + + + +## QuantoConfig + +[[autodoc]] QuantoConfig + +## AqlmConfig + +[[autodoc]] AqlmConfig + +## VptqConfig + +[[autodoc]] VptqConfig + +## AwqConfig + +[[autodoc]] AwqConfig + +## EetqConfig +[[autodoc]] EetqConfig + +## GPTQConfig + +[[autodoc]] GPTQConfig + +## BitsAndBytesConfig + +[[autodoc]] BitsAndBytesConfig + +## HfQuantizer + +[[autodoc]] quantizers.base.HfQuantizer + +## HiggsConfig + +[[autodoc]] HiggsConfig + +## HqqConfig + +[[autodoc]] HqqConfig + +## FbgemmFp8Config + +[[autodoc]] FbgemmFp8Config + +## CompressedTensorsConfig + +[[autodoc]] CompressedTensorsConfig + +## TorchAoConfig + +[[autodoc]] TorchAoConfig + +## BitNetConfig + +[[autodoc]] BitNetConfig + +## SpQRConfig + +[[autodoc]] SpQRConfig + +## FineGrainedFP8Config + +[[autodoc]] FineGrainedFP8Config diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/text_generation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/text_generation.md new file mode 100644 index 0000000000000000000000000000000000000000..76a0f1381cd6bc413d575c80ec974fe26682bb75 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/text_generation.md @@ -0,0 +1,59 @@ + + +# Generation + +Each framework has a generate method for text generation implemented in their respective `GenerationMixin` class: + +- PyTorch [`~generation.GenerationMixin.generate`] is implemented in [`~generation.GenerationMixin`]. +- TensorFlow [`~generation.TFGenerationMixin.generate`] is implemented in [`~generation.TFGenerationMixin`]. +- Flax/JAX [`~generation.FlaxGenerationMixin.generate`] is implemented in [`~generation.FlaxGenerationMixin`]. + +Regardless of your framework of choice, you can parameterize the generate method with a [`~generation.GenerationConfig`] +class instance. Please refer to this class for the complete list of generation parameters, which control the behavior +of the generation method. + +To learn how to inspect a model's generation configuration, what are the defaults, how to change the parameters ad hoc, +and how to create and save a customized generation configuration, refer to the +[text generation strategies guide](../generation_strategies). The guide also explains how to use related features, +like token streaming. + +## GenerationConfig + +[[autodoc]] generation.GenerationConfig + - from_pretrained + - from_model_config + - save_pretrained + - update + - validate + - get_generation_mode + +## GenerationMixin + +[[autodoc]] GenerationMixin + - generate + - compute_transition_scores + +## TFGenerationMixin + +[[autodoc]] TFGenerationMixin + - generate + - compute_transition_scores + +## FlaxGenerationMixin + +[[autodoc]] FlaxGenerationMixin + - generate diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/tokenizer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/tokenizer.md new file mode 100644 index 0000000000000000000000000000000000000000..83d2ae5df6a7fb1179edb400ff6ee8b616680db8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/tokenizer.md @@ -0,0 +1,104 @@ + + +# Tokenizer + +A tokenizer is in charge of preparing the inputs for a model. The library contains tokenizers for all the models. Most +of the tokenizers are available in two flavors: a full python implementation and a "Fast" implementation based on the +Rust library [🤗 Tokenizers](https://github.com/huggingface/tokenizers). The "Fast" implementations allows: + +1. a significant speed-up in particular when doing batched tokenization and +2. additional methods to map between the original string (character and words) and the token space (e.g. getting the + index of the token comprising a given character or the span of characters corresponding to a given token). + +The base classes [`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] +implement the common methods for encoding string inputs in model inputs (see below) and instantiating/saving python and +"Fast" tokenizers either from a local file or directory or from a pretrained tokenizer provided by the library +(downloaded from HuggingFace's AWS S3 repository). They both rely on +[`~tokenization_utils_base.PreTrainedTokenizerBase`] that contains the common methods, and +[`~tokenization_utils_base.SpecialTokensMixin`]. + +[`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] thus implement the main +methods for using all the tokenizers: + +- Tokenizing (splitting strings in sub-word token strings), converting tokens strings to ids and back, and + encoding/decoding (i.e., tokenizing and converting to integers). +- Adding new tokens to the vocabulary in a way that is independent of the underlying structure (BPE, SentencePiece...). +- Managing special tokens (like mask, beginning-of-sentence, etc.): adding them, assigning them to attributes in the + tokenizer for easy access and making sure they are not split during tokenization. + +[`BatchEncoding`] holds the output of the +[`~tokenization_utils_base.PreTrainedTokenizerBase`]'s encoding methods (`__call__`, +`encode_plus` and `batch_encode_plus`) and is derived from a Python dictionary. When the tokenizer is a pure python +tokenizer, this class behaves just like a standard python dictionary and holds the various model inputs computed by +these methods (`input_ids`, `attention_mask`...). When the tokenizer is a "Fast" tokenizer (i.e., backed by +HuggingFace [tokenizers library](https://github.com/huggingface/tokenizers)), this class provides in addition +several advanced alignment methods which can be used to map between the original string (character and words) and the +token space (e.g., getting the index of the token comprising a given character or the span of characters corresponding +to a given token). + + +# Multimodal Tokenizer + +Apart from that each tokenizer can be a "multimodal" tokenizer which means that the tokenizer will hold all relevant special tokens +as part of tokenizer attributes for easier access. For example, if the tokenizer is loaded from a vision-language model like LLaVA, you will +be able to access `tokenizer.image_token_id` to obtain the special image token used as a placeholder. + +To enable extra special tokens for any type of tokenizer, you have to add the following lines and save the tokenizer. Extra special tokens do not +have to be modality related and can ne anything that the model often needs access to. In the below code, tokenizer at `output_dir` will have direct access +to three more special tokens. + +```python +vision_tokenizer = AutoTokenizer.from_pretrained( + "llava-hf/llava-1.5-7b-hf", + extra_special_tokens={"image_token": "", "boi_token": "", "eoi_token": ""} +) +print(vision_tokenizer.image_token, vision_tokenizer.image_token_id) +("", 32000) +``` + +## PreTrainedTokenizer + +[[autodoc]] PreTrainedTokenizer + - __call__ + - add_tokens + - add_special_tokens + - apply_chat_template + - batch_decode + - decode + - encode + - push_to_hub + - all + +## PreTrainedTokenizerFast + +The [`PreTrainedTokenizerFast`] depend on the [tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the 🤗 tokenizers library can be +loaded very simply into 🤗 transformers. Take a look at the [Using tokenizers from 🤗 tokenizers](../fast_tokenizers) page to understand how this is done. + +[[autodoc]] PreTrainedTokenizerFast + - __call__ + - add_tokens + - add_special_tokens + - apply_chat_template + - batch_decode + - decode + - encode + - push_to_hub + - all + +## BatchEncoding + +[[autodoc]] BatchEncoding diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/trainer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..21ba9ed935e2731e9872d767295b13b2d11df50f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/main_classes/trainer.md @@ -0,0 +1,54 @@ + + +# Trainer + +The [`Trainer`] class provides an API for feature-complete training in PyTorch, and it supports distributed training on multiple GPUs/TPUs, mixed precision for [NVIDIA GPUs](https://nvidia.github.io/apex/), [AMD GPUs](https://rocm.docs.amd.com/en/latest/rocm.html), and [`torch.amp`](https://pytorch.org/docs/stable/amp.html) for PyTorch. [`Trainer`] goes hand-in-hand with the [`TrainingArguments`] class, which offers a wide range of options to customize how a model is trained. Together, these two classes provide a complete training API. + +[`Seq2SeqTrainer`] and [`Seq2SeqTrainingArguments`] inherit from the [`Trainer`] and [`TrainingArguments`] classes and they're adapted for training models for sequence-to-sequence tasks such as summarization or translation. + + + +The [`Trainer`] class is optimized for 🤗 Transformers models and can have surprising behaviors +when used with other models. When using it with your own model, make sure: + +- your model always return tuples or subclasses of [`~utils.ModelOutput`] +- your model can compute the loss if a `labels` argument is provided and that loss is returned as the first + element of the tuple (if your model returns tuples) +- your model can accept multiple label arguments (use `label_names` in [`TrainingArguments`] to indicate their name to the [`Trainer`]) but none of them should be named `"label"` + + + +## Trainer[[api-reference]] + +[[autodoc]] Trainer + - all + +## Seq2SeqTrainer + +[[autodoc]] Seq2SeqTrainer + - evaluate + - predict + +## TrainingArguments + +[[autodoc]] TrainingArguments + - all + +## Seq2SeqTrainingArguments + +[[autodoc]] Seq2SeqTrainingArguments + - all diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/albert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/albert.md new file mode 100644 index 0000000000000000000000000000000000000000..21cd57675e536c916e31a41d6c4739184f696869 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/albert.md @@ -0,0 +1,307 @@ + + +# ALBERT + +
+PyTorch +TensorFlow +Flax +SDPA +
+ +## Overview + +The ALBERT model was proposed in [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, +Radu Soricut. It presents two parameter-reduction techniques to lower memory consumption and increase the training +speed of BERT: + +- Splitting the embedding matrix into two smaller matrices. +- Using repeating layers split among groups. + +The abstract from the paper is the following: + +*Increasing model size when pretraining natural language representations often results in improved performance on +downstream tasks. However, at some point further model increases become harder due to GPU/TPU memory limitations, +longer training times, and unexpected model degradation. To address these problems, we present two parameter-reduction +techniques to lower memory consumption and increase the training speed of BERT. Comprehensive empirical evidence shows +that our proposed methods lead to models that scale much better compared to the original BERT. We also use a +self-supervised loss that focuses on modeling inter-sentence coherence, and show it consistently helps downstream tasks +with multi-sentence inputs. As a result, our best model establishes new state-of-the-art results on the GLUE, RACE, and +SQuAD benchmarks while having fewer parameters compared to BERT-large.* + +This model was contributed by [lysandre](https://huggingface.co/lysandre). This model jax version was contributed by +[kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/google-research/ALBERT). + +## Usage tips + +- ALBERT is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather + than the left. +- ALBERT uses repeating layers which results in a small memory footprint, however the computational cost remains + similar to a BERT-like architecture with the same number of hidden layers as it has to iterate through the same + number of (repeating) layers. +- Embedding size E is different from hidden size H justified because the embeddings are context independent (one embedding vector represents one token), whereas hidden states are context dependent (one hidden state represents a sequence of tokens) so it's more logical to have H >> E. Also, the embedding matrix is large since it's V x E (V being the vocab size). If E < H, it has less parameters. +- Layers are split in groups that share parameters (to save memory). +Next sentence prediction is replaced by a sentence ordering prediction: in the inputs, we have two sentences A and B (that are consecutive) and we either feed A followed by B or B followed by A. The model must predict if they have been swapped or not. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import AlbertModel +model = AlbertModel.from_pretrained("albert/albert-base-v1", torch_dtype=torch.float16, attn_implementation="sdpa") +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (GeForce RTX 2060-8GB, PyTorch 2.3.1, OS Ubuntu 20.04) with `float16`, we saw the +following speedups during training and inference. + +#### Training for 100 iterations + +|batch_size|seq_len|Time per batch (eager - s)| Time per batch (sdpa - s)| Speedup (%)| Eager peak mem (MB)| sdpa peak mem (MB)| Mem saving (%)| +|----------|-------|--------------------------|--------------------------|------------|--------------------|-------------------|---------------| +|2 |256 |0.028 |0.024 |14.388 |358.411 |321.088 |11.624 | +|2 |512 |0.049 |0.041 |17.681 |753.458 |602.660 |25.022 | +|4 |256 |0.044 |0.039 |12.246 |679.534 |602.660 |12.756 | +|4 |512 |0.090 |0.076 |18.472 |1434.820 |1134.140 |26.512 | +|8 |256 |0.081 |0.072 |12.664 |1283.825 |1134.140 |13.198 | +|8 |512 |0.170 |0.143 |18.957 |2820.398 |2219.695 |27.062 | + +#### Inference with 50 batches + +|batch_size|seq_len|Per token latency eager (ms)|Per token latency SDPA (ms)|Speedup (%) |Mem eager (MB)|Mem BT (MB)|Mem saved (%)| +|----------|-------|----------------------------|---------------------------|------------|--------------|-----------|-------------| +|4 |128 |0.083 |0.071 |16.967 |48.319 |48.45 |-0.268 | +|4 |256 |0.148 |0.127 |16.37 |63.4 |63.922 |-0.817 | +|4 |512 |0.31 |0.247 |25.473 |110.092 |94.343 |16.693 | +|8 |128 |0.137 |0.124 |11.102 |63.4 |63.66 |-0.409 | +|8 |256 |0.271 |0.231 |17.271 |91.202 |92.246 |-1.132 | +|8 |512 |0.602 |0.48 |25.47 |186.159 |152.564 |22.021 | +|16 |128 |0.252 |0.224 |12.506 |91.202 |91.722 |-0.567 | +|16 |256 |0.526 |0.448 |17.604 |148.378 |150.467 |-1.388 | +|16 |512 |1.203 |0.96 |25.365 |338.293 |271.102 |24.784 | + +This model was contributed by [lysandre](https://huggingface.co/lysandre). This model jax version was contributed by +[kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/google-research/ALBERT). + + +## Resources + + +The resources provided in the following sections consist of a list of official Hugging Face and community (indicated by 🌎) resources to help you get started with AlBERT. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + + + +- [`AlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification). + + +- [`TFAlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification). + +- [`FlaxAlbertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb). +- Check the [Text classification task guide](../tasks/sequence_classification) on how to use the model. + + + + + +- [`AlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification). + + +- [`TFAlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). + + + +- [`FlaxAlbertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/token-classification). +- [Token classification](https://huggingface.co/course/chapter7/2?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Token classification task guide](../tasks/token_classification) on how to use the model. + + + +- [`AlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFAlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxAlbertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Masked language modeling task guide](../tasks/masked_language_modeling) on how to use the model. + + + +- [`AlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb). +- [`TFAlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). +- [`FlaxAlbertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/question-answering). +- [Question answering](https://huggingface.co/course/chapter7/7?fw=pt) chapter of the 🤗 Hugging Face Course. +- Check the [Question answering task guide](../tasks/question_answering) on how to use the model. + +**Multiple choice** + +- [`AlbertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb). +- [`TFAlbertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb). + +- Check the [Multiple choice task guide](../tasks/multiple_choice) on how to use the model. + + +## AlbertConfig + +[[autodoc]] AlbertConfig + +## AlbertTokenizer + +[[autodoc]] AlbertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## AlbertTokenizerFast + +[[autodoc]] AlbertTokenizerFast + +## Albert specific outputs + +[[autodoc]] models.albert.modeling_albert.AlbertForPreTrainingOutput + +[[autodoc]] models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutput + + + + +## AlbertModel + +[[autodoc]] AlbertModel + - forward + +## AlbertForPreTraining + +[[autodoc]] AlbertForPreTraining + - forward + +## AlbertForMaskedLM + +[[autodoc]] AlbertForMaskedLM + - forward + +## AlbertForSequenceClassification + +[[autodoc]] AlbertForSequenceClassification + - forward + +## AlbertForMultipleChoice + +[[autodoc]] AlbertForMultipleChoice + +## AlbertForTokenClassification + +[[autodoc]] AlbertForTokenClassification + - forward + +## AlbertForQuestionAnswering + +[[autodoc]] AlbertForQuestionAnswering + - forward + + + + + +## TFAlbertModel + +[[autodoc]] TFAlbertModel + - call + +## TFAlbertForPreTraining + +[[autodoc]] TFAlbertForPreTraining + - call + +## TFAlbertForMaskedLM + +[[autodoc]] TFAlbertForMaskedLM + - call + +## TFAlbertForSequenceClassification + +[[autodoc]] TFAlbertForSequenceClassification + - call + +## TFAlbertForMultipleChoice + +[[autodoc]] TFAlbertForMultipleChoice + - call + +## TFAlbertForTokenClassification + +[[autodoc]] TFAlbertForTokenClassification + - call + +## TFAlbertForQuestionAnswering + +[[autodoc]] TFAlbertForQuestionAnswering + - call + + + + +## FlaxAlbertModel + +[[autodoc]] FlaxAlbertModel + - __call__ + +## FlaxAlbertForPreTraining + +[[autodoc]] FlaxAlbertForPreTraining + - __call__ + +## FlaxAlbertForMaskedLM + +[[autodoc]] FlaxAlbertForMaskedLM + - __call__ + +## FlaxAlbertForSequenceClassification + +[[autodoc]] FlaxAlbertForSequenceClassification + - __call__ + +## FlaxAlbertForMultipleChoice + +[[autodoc]] FlaxAlbertForMultipleChoice + - __call__ + +## FlaxAlbertForTokenClassification + +[[autodoc]] FlaxAlbertForTokenClassification + - __call__ + +## FlaxAlbertForQuestionAnswering + +[[autodoc]] FlaxAlbertForQuestionAnswering + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/align.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/align.md new file mode 100644 index 0000000000000000000000000000000000000000..b2920bdc2bace29574350689cc7f9ee91576b948 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/align.md @@ -0,0 +1,108 @@ + + +# ALIGN + +
+PyTorch +
+ +## Overview + +The ALIGN model was proposed in [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://arxiv.org/abs/2102.05918) by Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig. ALIGN is a multi-modal vision and language model. It can be used for image-text similarity and for zero-shot image classification. ALIGN features a dual-encoder architecture with [EfficientNet](efficientnet) as its vision encoder and [BERT](bert) as its text encoder, and learns to align visual and text representations with contrastive learning. Unlike previous work, ALIGN leverages a massive noisy dataset and shows that the scale of the corpus can be used to achieve SOTA representations with a simple recipe. + +The abstract from the paper is the following: + +*Pre-trained representations are becoming crucial for many NLP and perception tasks. While representation learning in NLP has transitioned to training on raw text without human annotations, visual and vision-language representations still rely heavily on curated training datasets that are expensive or require expert knowledge. For vision applications, representations are mostly learned using datasets with explicit class labels such as ImageNet or OpenImages. For vision-language, popular datasets like Conceptual Captions, MSCOCO, or CLIP all involve a non-trivial data collection (and cleaning) process. This costly curation process limits the size of datasets and hence hinders the scaling of trained models. In this paper, we leverage a noisy dataset of over one billion image alt-text pairs, obtained without expensive filtering or post-processing steps in the Conceptual Captions dataset. A simple dual-encoder architecture learns to align visual and language representations of the image and text pairs using a contrastive loss. We show that the scale of our corpus can make up for its noise and leads to state-of-the-art representations even with such a simple learning scheme. Our visual representation achieves strong performance when transferred to classification tasks such as ImageNet and VTAB. The aligned visual and language representations enables zero-shot image classification and also set new state-of-the-art results on Flickr30K and MSCOCO image-text retrieval benchmarks, even when compared with more sophisticated cross-attention models. The representations also enable cross-modality search with complex text and text + image queries.* + +This model was contributed by [Alara Dirik](https://huggingface.co/adirik). +The original code is not released, this implementation is based on the Kakao Brain implementation based on the original paper. + +## Usage example + +ALIGN uses EfficientNet to get visual features and BERT to get the text features. Both the text and visual features are then projected to a latent space with identical dimension. The dot product between the projected image and text features is then used as a similarity score. + +[`AlignProcessor`] wraps [`EfficientNetImageProcessor`] and [`BertTokenizer`] into a single instance to both encode the text and preprocess the images. The following example shows how to get the image-text similarity scores using [`AlignProcessor`] and [`AlignModel`]. + +```python +import requests +import torch +from PIL import Image +from transformers import AlignProcessor, AlignModel + +processor = AlignProcessor.from_pretrained("kakaobrain/align-base") +model = AlignModel.from_pretrained("kakaobrain/align-base") + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image = Image.open(requests.get(url, stream=True).raw) +candidate_labels = ["an image of a cat", "an image of a dog"] + +inputs = processor(images=image ,text=candidate_labels, return_tensors="pt") + +with torch.no_grad(): + outputs = model(**inputs) + +# this is the image-text similarity score +logits_per_image = outputs.logits_per_image + +# we can take the softmax to get the label probabilities +probs = logits_per_image.softmax(dim=1) +print(probs) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ALIGN. + +- A blog post on [ALIGN and the COYO-700M dataset](https://huggingface.co/blog/vit-align). +- A zero-shot image classification [demo](https://huggingface.co/spaces/adirik/ALIGN-zero-shot-image-classification). +- [Model card](https://huggingface.co/kakaobrain/align-base) of `kakaobrain/align-base` model. + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## AlignConfig + +[[autodoc]] AlignConfig + - from_text_vision_configs + +## AlignTextConfig + +[[autodoc]] AlignTextConfig + +## AlignVisionConfig + +[[autodoc]] AlignVisionConfig + +## AlignProcessor + +[[autodoc]] AlignProcessor + +## AlignModel + +[[autodoc]] AlignModel + - forward + - get_text_features + - get_image_features + +## AlignTextModel + +[[autodoc]] AlignTextModel + - forward + +## AlignVisionModel + +[[autodoc]] AlignVisionModel + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/altclip.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/altclip.md new file mode 100644 index 0000000000000000000000000000000000000000..0dfbf797a033de541187619f2432e57c07264a2a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/altclip.md @@ -0,0 +1,116 @@ + + +# AltCLIP + +
+PyTorch +
+ +## Overview + +The AltCLIP model was proposed in [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679v2) by Zhongzhi Chen, Guang Liu, Bo-Wen Zhang, Fulong Ye, Qinghong Yang, Ledell Wu. AltCLIP +(Altering the Language Encoder in CLIP) is a neural network trained on a variety of image-text and text-text pairs. By switching CLIP's +text encoder with a pretrained multilingual text encoder XLM-R, we could obtain very close performances with CLIP on almost all tasks, and extended original CLIP's capabilities such as multilingual understanding. + +The abstract from the paper is the following: + +*In this work, we present a conceptually simple and effective method to train a strong bilingual multimodal representation model. +Starting from the pretrained multimodal representation model CLIP released by OpenAI, we switched its text encoder with a pretrained +multilingual text encoder XLM-R, and aligned both languages and image representations by a two-stage training schema consisting of +teacher learning and contrastive learning. We validate our method through evaluations of a wide range of tasks. We set new state-of-the-art +performances on a bunch of tasks including ImageNet-CN, Flicker30k- CN, and COCO-CN. Further, we obtain very close performances with +CLIP on almost all tasks, suggesting that one can simply alter the text encoder in CLIP for extended capabilities such as multilingual understanding.* + +This model was contributed by [jongjyh](https://huggingface.co/jongjyh). + +## Usage tips and example + +The usage of AltCLIP is very similar to the CLIP. the difference between CLIP is the text encoder. Note that we use bidirectional attention instead of casual attention +and we take the [CLS] token in XLM-R to represent text embedding. + +AltCLIP is a multi-modal vision and language model. It can be used for image-text similarity and for zero-shot image +classification. AltCLIP uses a ViT like transformer to get visual features and a bidirectional language model to get the text +features. Both the text and visual features are then projected to a latent space with identical dimension. The dot +product between the projected image and text features is then used as a similar score. + +To feed images to the Transformer encoder, each image is split into a sequence of fixed-size non-overlapping patches, +which are then linearly embedded. A [CLS] token is added to serve as representation of an entire image. The authors +also add absolute position embeddings, and feed the resulting sequence of vectors to a standard Transformer encoder. +The [`CLIPImageProcessor`] can be used to resize (or rescale) and normalize images for the model. + +The [`AltCLIPProcessor`] wraps a [`CLIPImageProcessor`] and a [`XLMRobertaTokenizer`] into a single instance to both +encode the text and prepare the images. The following example shows how to get the image-text similarity scores using +[`AltCLIPProcessor`] and [`AltCLIPModel`]. + +```python +>>> from PIL import Image +>>> import requests + +>>> from transformers import AltCLIPModel, AltCLIPProcessor + +>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP") +>>> processor = AltCLIPProcessor.from_pretrained("BAAI/AltCLIP") + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) + +>>> outputs = model(**inputs) +>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score +>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities +``` + + + +This model is based on `CLIPModel`, use it like you would use the original [CLIP](clip). + + + +## AltCLIPConfig + +[[autodoc]] AltCLIPConfig + - from_text_vision_configs + +## AltCLIPTextConfig + +[[autodoc]] AltCLIPTextConfig + +## AltCLIPVisionConfig + +[[autodoc]] AltCLIPVisionConfig + +## AltCLIPProcessor + +[[autodoc]] AltCLIPProcessor + +## AltCLIPModel + +[[autodoc]] AltCLIPModel + - forward + - get_text_features + - get_image_features + +## AltCLIPTextModel + +[[autodoc]] AltCLIPTextModel + - forward + +## AltCLIPVisionModel + +[[autodoc]] AltCLIPVisionModel + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aria.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aria.md new file mode 100644 index 0000000000000000000000000000000000000000..7b58f59cab7ee9e33cdf4c592920f3aa2dd99e9e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aria.md @@ -0,0 +1,112 @@ + + +# Aria + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Aria model was proposed in [Aria: An Open Multimodal Native Mixture-of-Experts Model](https://huggingface.co/papers/2410.05993) by Li et al. from the Rhymes.AI team. + +Aria is an open multimodal-native model with best-in-class performance across a wide range of multimodal, language, and coding tasks. It has a Mixture-of-Experts architecture, with respectively 3.9B and 3.5B activated parameters per visual token and text token. + +The abstract from the paper is the following: + +*Information comes in diverse modalities. Multimodal native AI models are essential to integrate real-world information and deliver comprehensive understanding. While proprietary multimodal native models exist, their lack of openness imposes obstacles for adoptions, let alone adaptations. To fill this gap, we introduce Aria, an open multimodal native model with best-in-class performance across a wide range of multimodal, language, and coding tasks. Aria is a mixture-of-expert model with 3.9B and 3.5B activated parameters per visual token and text token, respectively. It outperforms Pixtral-12B and Llama3.2-11B, and is competitive against the best proprietary models on various multimodal tasks. We pre-train Aria from scratch following a 4-stage pipeline, which progressively equips the model with strong capabilities in language understanding, multimodal understanding, long context window, and instruction following. We open-source the model weights along with a codebase that facilitates easy adoptions and adaptations of Aria in real-world applications.* + +This model was contributed by [m-ric](https://huggingface.co/m-ric). +The original code can be found [here](https://github.com/rhymes-ai/Aria). + +## Usage tips + +Here's how to use the model for vision tasks: +```python +import requests +import torch +from PIL import Image + +from transformers import AriaProcessor, AriaForConditionalGeneration + +model_id_or_path = "rhymes-ai/Aria" + +model = AriaForConditionalGeneration.from_pretrained( + model_id_or_path, device_map="auto" +) + +processor = AriaProcessor.from_pretrained(model_id_or_path) + +image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw) + +messages = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"text": "what is the image?", "type": "text"}, + ], + } +] + +text = processor.apply_chat_template(messages, add_generation_prompt=True) +inputs = processor(text=text, images=image, return_tensors="pt") +inputs.to(model.device) + +output = model.generate( + **inputs, + max_new_tokens=15, + stop_strings=["<|im_end|>"], + tokenizer=processor.tokenizer, + do_sample=True, + temperature=0.9, +) +output_ids = output[0][inputs["input_ids"].shape[1]:] +response = processor.decode(output_ids, skip_special_tokens=True) +``` + + +## AriaImageProcessor + +[[autodoc]] AriaImageProcessor + +## AriaProcessor + +[[autodoc]] AriaProcessor + +## AriaTextConfig + +[[autodoc]] AriaTextConfig + +## AriaConfig + +[[autodoc]] AriaConfig + +## AriaTextModel + +[[autodoc]] AriaTextModel + +## AriaTextForCausalLM + +[[autodoc]] AriaTextForCausalLM + +## AriaForConditionalGeneration + +[[autodoc]] AriaForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/audio-spectrogram-transformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/audio-spectrogram-transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..4cc07aea758c7568a5b00eec1c6974f232c24e4e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/audio-spectrogram-transformer.md @@ -0,0 +1,108 @@ + + +# Audio Spectrogram Transformer + +
+PyTorch +SDPA +
+ +## Overview + +The Audio Spectrogram Transformer model was proposed in [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778) by Yuan Gong, Yu-An Chung, James Glass. +The Audio Spectrogram Transformer applies a [Vision Transformer](vit) to audio, by turning audio into an image (spectrogram). The model obtains state-of-the-art results +for audio classification. + +The abstract from the paper is the following: + +*In the past decade, convolutional neural networks (CNNs) have been widely adopted as the main building block for end-to-end audio classification models, which aim to learn a direct mapping from audio spectrograms to corresponding labels. To better capture long-range global context, a recent trend is to add a self-attention mechanism on top of the CNN, forming a CNN-attention hybrid model. However, it is unclear whether the reliance on a CNN is necessary, and if neural networks purely based on attention are sufficient to obtain good performance in audio classification. In this paper, we answer the question by introducing the Audio Spectrogram Transformer (AST), the first convolution-free, purely attention-based model for audio classification. We evaluate AST on various audio classification benchmarks, where it achieves new state-of-the-art results of 0.485 mAP on AudioSet, 95.6% accuracy on ESC-50, and 98.1% accuracy on Speech Commands V2.* + + + + Audio Spectrogram Transformer architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/YuanGongND/ast). + +## Usage tips + +- When fine-tuning the Audio Spectrogram Transformer (AST) on your own dataset, it's recommended to take care of the input normalization (to make +sure the input has mean of 0 and std of 0.5). [`ASTFeatureExtractor`] takes care of this. Note that it uses the AudioSet +mean and std by default. You can check [`ast/src/get_norm_stats.py`](https://github.com/YuanGongND/ast/blob/master/src/get_norm_stats.py) to see how +the authors compute the stats for a downstream dataset. +- Note that the AST needs a low learning rate (the authors use a 10 times smaller learning rate compared to their CNN model proposed in the +[PSLA paper](https://arxiv.org/abs/2102.01243)) and converges quickly, so please search for a suitable learning rate and learning rate scheduler for your task. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import ASTForAudioClassification +model = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `MIT/ast-finetuned-audioset-10-10-0.4593` model, we saw the following speedups during inference. + +| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) | +|--------------|-------------------------------------------|-------------------------------------------|------------------------------| +| 1 | 27 | 6 | 4.5 | +| 2 | 12 | 6 | 2 | +| 4 | 21 | 8 | 2.62 | +| 8 | 40 | 14 | 2.86 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with the Audio Spectrogram Transformer. + + + +- A notebook illustrating inference with AST for audio classification can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/AST). +- [`ASTForAudioClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb). +- See also: [Audio classification](../tasks/audio_classification). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## ASTConfig + +[[autodoc]] ASTConfig + +## ASTFeatureExtractor + +[[autodoc]] ASTFeatureExtractor + - __call__ + +## ASTModel + +[[autodoc]] ASTModel + - forward + +## ASTForAudioClassification + +[[autodoc]] ASTForAudioClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/auto.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/auto.md new file mode 100644 index 0000000000000000000000000000000000000000..059312850876d2b5b7a53c5f43f42a91c9eb3594 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/auto.md @@ -0,0 +1,387 @@ + + +# Auto Classes + +In many cases, the architecture you want to use can be guessed from the name or the path of the pretrained model you +are supplying to the `from_pretrained()` method. AutoClasses are here to do this job for you so that you +automatically retrieve the relevant model given the name/path to the pretrained weights/config/vocabulary. + +Instantiating one of [`AutoConfig`], [`AutoModel`], and +[`AutoTokenizer`] will directly create a class of the relevant architecture. For instance + + +```python +model = AutoModel.from_pretrained("google-bert/bert-base-cased") +``` + +will create a model that is an instance of [`BertModel`]. + +There is one class of `AutoModel` for each task, and for each backend (PyTorch, TensorFlow, or Flax). + +## Extending the Auto Classes + +Each of the auto classes has a method to be extended with your custom classes. For instance, if you have defined a +custom class of model `NewModel`, make sure you have a `NewModelConfig` then you can add those to the auto +classes like this: + +```python +from transformers import AutoConfig, AutoModel + +AutoConfig.register("new-model", NewModelConfig) +AutoModel.register(NewModelConfig, NewModel) +``` + +You will then be able to use the auto classes like you would usually do! + + + +If your `NewModelConfig` is a subclass of [`~transformers.PretrainedConfig`], make sure its +`model_type` attribute is set to the same key you use when registering the config (here `"new-model"`). + +Likewise, if your `NewModel` is a subclass of [`PreTrainedModel`], make sure its +`config_class` attribute is set to the same class you use when registering the model (here +`NewModelConfig`). + + + +## AutoConfig + +[[autodoc]] AutoConfig + +## AutoTokenizer + +[[autodoc]] AutoTokenizer + +## AutoFeatureExtractor + +[[autodoc]] AutoFeatureExtractor + +## AutoImageProcessor + +[[autodoc]] AutoImageProcessor + +## AutoProcessor + +[[autodoc]] AutoProcessor + +## Generic model classes + +The following auto classes are available for instantiating a base model class without a specific head. + +### AutoModel + +[[autodoc]] AutoModel + +### TFAutoModel + +[[autodoc]] TFAutoModel + +### FlaxAutoModel + +[[autodoc]] FlaxAutoModel + +## Generic pretraining classes + +The following auto classes are available for instantiating a model with a pretraining head. + +### AutoModelForPreTraining + +[[autodoc]] AutoModelForPreTraining + +### TFAutoModelForPreTraining + +[[autodoc]] TFAutoModelForPreTraining + +### FlaxAutoModelForPreTraining + +[[autodoc]] FlaxAutoModelForPreTraining + +## Natural Language Processing + +The following auto classes are available for the following natural language processing tasks. + +### AutoModelForCausalLM + +[[autodoc]] AutoModelForCausalLM + +### TFAutoModelForCausalLM + +[[autodoc]] TFAutoModelForCausalLM + +### FlaxAutoModelForCausalLM + +[[autodoc]] FlaxAutoModelForCausalLM + +### AutoModelForMaskedLM + +[[autodoc]] AutoModelForMaskedLM + +### TFAutoModelForMaskedLM + +[[autodoc]] TFAutoModelForMaskedLM + +### FlaxAutoModelForMaskedLM + +[[autodoc]] FlaxAutoModelForMaskedLM + +### AutoModelForMaskGeneration + +[[autodoc]] AutoModelForMaskGeneration + +### TFAutoModelForMaskGeneration + +[[autodoc]] TFAutoModelForMaskGeneration + +### AutoModelForSeq2SeqLM + +[[autodoc]] AutoModelForSeq2SeqLM + +### TFAutoModelForSeq2SeqLM + +[[autodoc]] TFAutoModelForSeq2SeqLM + +### FlaxAutoModelForSeq2SeqLM + +[[autodoc]] FlaxAutoModelForSeq2SeqLM + +### AutoModelForSequenceClassification + +[[autodoc]] AutoModelForSequenceClassification + +### TFAutoModelForSequenceClassification + +[[autodoc]] TFAutoModelForSequenceClassification + +### FlaxAutoModelForSequenceClassification + +[[autodoc]] FlaxAutoModelForSequenceClassification + +### AutoModelForMultipleChoice + +[[autodoc]] AutoModelForMultipleChoice + +### TFAutoModelForMultipleChoice + +[[autodoc]] TFAutoModelForMultipleChoice + +### FlaxAutoModelForMultipleChoice + +[[autodoc]] FlaxAutoModelForMultipleChoice + +### AutoModelForNextSentencePrediction + +[[autodoc]] AutoModelForNextSentencePrediction + +### TFAutoModelForNextSentencePrediction + +[[autodoc]] TFAutoModelForNextSentencePrediction + +### FlaxAutoModelForNextSentencePrediction + +[[autodoc]] FlaxAutoModelForNextSentencePrediction + +### AutoModelForTokenClassification + +[[autodoc]] AutoModelForTokenClassification + +### TFAutoModelForTokenClassification + +[[autodoc]] TFAutoModelForTokenClassification + +### FlaxAutoModelForTokenClassification + +[[autodoc]] FlaxAutoModelForTokenClassification + +### AutoModelForQuestionAnswering + +[[autodoc]] AutoModelForQuestionAnswering + +### TFAutoModelForQuestionAnswering + +[[autodoc]] TFAutoModelForQuestionAnswering + +### FlaxAutoModelForQuestionAnswering + +[[autodoc]] FlaxAutoModelForQuestionAnswering + +### AutoModelForTextEncoding + +[[autodoc]] AutoModelForTextEncoding + +### TFAutoModelForTextEncoding + +[[autodoc]] TFAutoModelForTextEncoding + +## Computer vision + +The following auto classes are available for the following computer vision tasks. + +### AutoModelForDepthEstimation + +[[autodoc]] AutoModelForDepthEstimation + +### AutoModelForImageClassification + +[[autodoc]] AutoModelForImageClassification + +### TFAutoModelForImageClassification + +[[autodoc]] TFAutoModelForImageClassification + +### FlaxAutoModelForImageClassification + +[[autodoc]] FlaxAutoModelForImageClassification + +### AutoModelForVideoClassification + +[[autodoc]] AutoModelForVideoClassification + +### AutoModelForKeypointDetection + +[[autodoc]] AutoModelForKeypointDetection + +### AutoModelForMaskedImageModeling + +[[autodoc]] AutoModelForMaskedImageModeling + +### TFAutoModelForMaskedImageModeling + +[[autodoc]] TFAutoModelForMaskedImageModeling + +### AutoModelForObjectDetection + +[[autodoc]] AutoModelForObjectDetection + +### AutoModelForImageSegmentation + +[[autodoc]] AutoModelForImageSegmentation + +### AutoModelForImageToImage + +[[autodoc]] AutoModelForImageToImage + +### AutoModelForSemanticSegmentation + +[[autodoc]] AutoModelForSemanticSegmentation + +### TFAutoModelForSemanticSegmentation + +[[autodoc]] TFAutoModelForSemanticSegmentation + +### AutoModelForInstanceSegmentation + +[[autodoc]] AutoModelForInstanceSegmentation + +### AutoModelForUniversalSegmentation + +[[autodoc]] AutoModelForUniversalSegmentation + +### AutoModelForZeroShotImageClassification + +[[autodoc]] AutoModelForZeroShotImageClassification + +### TFAutoModelForZeroShotImageClassification + +[[autodoc]] TFAutoModelForZeroShotImageClassification + +### AutoModelForZeroShotObjectDetection + +[[autodoc]] AutoModelForZeroShotObjectDetection + +## Audio + +The following auto classes are available for the following audio tasks. + +### AutoModelForAudioClassification + +[[autodoc]] AutoModelForAudioClassification + +### AutoModelForAudioFrameClassification + +[[autodoc]] TFAutoModelForAudioClassification + +### TFAutoModelForAudioFrameClassification + +[[autodoc]] AutoModelForAudioFrameClassification + +### AutoModelForCTC + +[[autodoc]] AutoModelForCTC + +### AutoModelForSpeechSeq2Seq + +[[autodoc]] AutoModelForSpeechSeq2Seq + +### TFAutoModelForSpeechSeq2Seq + +[[autodoc]] TFAutoModelForSpeechSeq2Seq + +### FlaxAutoModelForSpeechSeq2Seq + +[[autodoc]] FlaxAutoModelForSpeechSeq2Seq + +### AutoModelForAudioXVector + +[[autodoc]] AutoModelForAudioXVector + +### AutoModelForTextToSpectrogram + +[[autodoc]] AutoModelForTextToSpectrogram + +### AutoModelForTextToWaveform + +[[autodoc]] AutoModelForTextToWaveform + +## Multimodal + +The following auto classes are available for the following multimodal tasks. + +### AutoModelForTableQuestionAnswering + +[[autodoc]] AutoModelForTableQuestionAnswering + +### TFAutoModelForTableQuestionAnswering + +[[autodoc]] TFAutoModelForTableQuestionAnswering + +### AutoModelForDocumentQuestionAnswering + +[[autodoc]] AutoModelForDocumentQuestionAnswering + +### TFAutoModelForDocumentQuestionAnswering + +[[autodoc]] TFAutoModelForDocumentQuestionAnswering + +### AutoModelForVisualQuestionAnswering + +[[autodoc]] AutoModelForVisualQuestionAnswering + +### AutoModelForVision2Seq + +[[autodoc]] AutoModelForVision2Seq + +### TFAutoModelForVision2Seq + +[[autodoc]] TFAutoModelForVision2Seq + +### FlaxAutoModelForVision2Seq + +[[autodoc]] FlaxAutoModelForVision2Seq + +### AutoModelForImageTextToText + +[[autodoc]] AutoModelForImageTextToText diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/autoformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/autoformer.md new file mode 100644 index 0000000000000000000000000000000000000000..2c5e27153e03188ca08bcecc83d419d9f8481ecb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/autoformer.md @@ -0,0 +1,54 @@ + + +# Autoformer + +
+PyTorch +
+ +## Overview + +The Autoformer model was proposed in [Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://arxiv.org/abs/2106.13008) by Haixu Wu, Jiehui Xu, Jianmin Wang, Mingsheng Long. + +This model augments the Transformer as a deep decomposition architecture, which can progressively decompose the trend and seasonal components during the forecasting process. + +The abstract from the paper is the following: + +*Extending the forecasting time is a critical demand for real applications, such as extreme weather early warning and long-term energy consumption planning. This paper studies the long-term forecasting problem of time series. Prior Transformer-based models adopt various self-attention mechanisms to discover the long-range dependencies. However, intricate temporal patterns of the long-term future prohibit the model from finding reliable dependencies. Also, Transformers have to adopt the sparse versions of point-wise self-attentions for long series efficiency, resulting in the information utilization bottleneck. Going beyond Transformers, we design Autoformer as a novel decomposition architecture with an Auto-Correlation mechanism. We break with the pre-processing convention of series decomposition and renovate it as a basic inner block of deep models. This design empowers Autoformer with progressive decomposition capacities for complex time series. Further, inspired by the stochastic process theory, we design the Auto-Correlation mechanism based on the series periodicity, which conducts the dependencies discovery and representation aggregation at the sub-series level. Auto-Correlation outperforms self-attention in both efficiency and accuracy. In long-term forecasting, Autoformer yields state-of-the-art accuracy, with a 38% relative improvement on six benchmarks, covering five practical applications: energy, traffic, economics, weather and disease.* + +This model was contributed by [elisim](https://huggingface.co/elisim) and [kashif](https://huggingface.co/kashif). +The original code can be found [here](https://github.com/thuml/Autoformer). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- Check out the Autoformer blog-post in HuggingFace blog: [Yes, Transformers are Effective for Time Series Forecasting (+ Autoformer)](https://huggingface.co/blog/autoformer) + +## AutoformerConfig + +[[autodoc]] AutoformerConfig + +## AutoformerModel + +[[autodoc]] AutoformerModel + - forward + +## AutoformerForPrediction + +[[autodoc]] AutoformerForPrediction + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aya_vision.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aya_vision.md new file mode 100644 index 0000000000000000000000000000000000000000..17daf4949206578f9805ef7b1e1fa2494cc6a48f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/aya_vision.md @@ -0,0 +1,243 @@ + + +# AyaVision + +## Overview + +The Aya Vision 8B and 32B models is a state-of-the-art multilingual multimodal models developed by Cohere For AI. They build on the Aya Expanse recipe to handle both visual and textual information without compromising on the strong multilingual textual performance of the original model. + +Aya Vision 8B combines the `Siglip2-so400-384-14` vision encoder with the Cohere CommandR-7B language model further post-trained with the Aya Expanse recipe, creating a powerful vision-language model capable of understanding images and generating text across 23 languages. Whereas, Aya Vision 32B uses Aya Expanse 32B as the language model. + +Key features of Aya Vision include: +- Multimodal capabilities in 23 languages +- Strong text-only multilingual capabilities inherited from CommandR-7B post-trained with the Aya Expanse recipe and Aya Expanse 32B +- High-quality visual understanding using the Siglip2-so400-384-14 vision encoder +- Seamless integration of visual and textual information in 23 languages. + + + +Tips: + +- Aya Vision is a multimodal model that takes images and text as input and produces text as output. +- Images are represented using the `` tag in the templated input. +- For best results, use the `apply_chat_template` method of the processor to format your inputs correctly. +- The model can process multiple images in a single conversation. +- Aya Vision can understand and generate text in 23 languages, making it suitable for multilingual multimodal applications. + +This model was contributed by [saurabhdash](https://huggingface.co/saurabhdash) and [yonigozlan](https://huggingface.co/yonigozlan). + + +## Usage + +Here's how to use Aya Vision for inference: + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +import torch + +model_id = "CohereForAI/aya-vision-8b" +torch_device = "cuda:0" + +# Use fast image processor +processor = AutoProcessor.from_pretrained(model_id, use_fast=True) +model = AutoModelForImageTextToText.from_pretrained( + model_id, device_map=torch_device, torch_dtype=torch.float16 +) + +# Format message with the aya-vision chat template +messages = [ + {"role": "user", + "content": [ + {"type": "image", "url": "https://pbs.twimg.com/media/Fx7YvfQWYAIp6rZ?format=jpg&name=medium"}, + {"type": "text", "text": "चित्र में लिखा पाठ क्या कहता है?"}, + ]}, + ] + +# Process image on CUDA +inputs = processor.apply_chat_template( + messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", device=torch_device +).to(model.device) + +gen_tokens = model.generate( + **inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, +) + +gen_text = print(processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)) +``` +### Pipeline + +```python +from transformers import pipeline + +pipe = pipeline(model="CohereForAI/aya-vision-8b", task="image-text-to-text", device_map="auto") + +# Format message with the aya-vision chat template +messages = [ + {"role": "user", + "content": [ + {"type": "image", "url": "https://media.istockphoto.com/id/458012057/photo/istanbul-turkey.jpg?s=612x612&w=0&k=20&c=qogAOVvkpfUyqLUMr_XJQyq-HkACXyYUSZbKhBlPrxo="}, + {"type": "text", "text": "Bu resimde hangi anıt gösterilmektedir?"}, + ]}, + ] +outputs = pipe(text=messages, max_new_tokens=300, return_full_text=False) + +print(outputs) +``` + +### Multiple Images and Batched Inputs + +Aya Vision can process multiple images in a single conversation. Here's how to use it with multiple images: + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +import torch + +model_id = "CohereForAI/aya-vision-8b" + +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModelForImageTextToText.from_pretrained( + model_id, device_map="cuda:0", torch_dtype=torch.float16 +) + +# Example with multiple images in a single message +messages = [ + { + "role": "user", + "content": [ + { + "type": "image", + "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg", + }, + { + "type": "image", + "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg", + }, + { + "type": "text", + "text": "These images depict two different landmarks. Can you identify them?", + }, + ], + }, +] + +inputs = processor.apply_chat_template( + messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" +).to(model.device) + +gen_tokens = model.generate( + **inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, +) + +gen_text = processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True) +print(gen_text) +``` + +For processing batched inputs (multiple conversations at once): + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +import torch + +model_id = "CohereForAI/aya-vision-8b" + +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModelForImageTextToText.from_pretrained( + model_id, device_map="cuda:0", torch_dtype=torch.float16 +) + +# Prepare two different conversations +batch_messages = [ + # First conversation with a single image + [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, + {"type": "text", "text": "Write a haiku for this image"}, + ], + }, + ], + # Second conversation with multiple images + [ + { + "role": "user", + "content": [ + { + "type": "image", + "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg", + }, + { + "type": "image", + "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg", + }, + { + "type": "text", + "text": "These images depict two different landmarks. Can you identify them?", + }, + ], + }, + ], +] + +# Process each conversation separately and combine into a batch +batch_inputs = processor.apply_chat_template( + batch_messages, + padding=True, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt" +).to(model.device) + +# Generate responses for the batch +batch_outputs = model.generate( + **batch_inputs, + max_new_tokens=300, + do_sample=True, + temperature=0.3, +) + +# Decode the generated responses +for i, output in enumerate(batch_outputs): + response = processor.tokenizer.decode( + output[batch_inputs.input_ids.shape[1]:], + skip_special_tokens=True + ) + print(f"Response {i+1}:\n{response}\n") +``` + +## AyaVisionProcessor + +[[autodoc]] AyaVisionProcessor + +## AyaVisionConfig + +[[autodoc]] AyaVisionConfig + +## AyaVisionForConditionalGeneration + +[[autodoc]] AyaVisionForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bamba.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bamba.md new file mode 100644 index 0000000000000000000000000000000000000000..c6e1bcec56a2745e6ed1db7750f6479cc3ba0bb1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bamba.md @@ -0,0 +1,69 @@ + + +# Bamba + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +Bamba-9B is a decoder-only language model based on the [Mamba-2](https://github.com/state-spaces/mamba) architecture and is designed to handle a wide range of text generation tasks. It is trained from scratch using a two-stage training approach. In the first stage, the model is trained on 2 trillion tokens from the Dolma v1.7 dataset. In the second stage, it undergoes additional training on 200 billion tokens, leveraging a carefully curated blend of high-quality data to further refine its performance and enhance output quality. + +Checkout all Bamba-9B model checkpoints [here](https://github.com/foundation-model-stack/bamba). + +## BambaConfig + +| Model | Params | # Layers | Hidden Dim. | Attention Heads | GQA | KV Heads | Context Length | Tied Embeddings | +|-------------------|--------------|----------|-------------|-----------------|-----|----------|----------------|------------------| +| Bamba | 9B (9.78B) | 32 | 4096 | 32 | Yes | 8 | 4096 | True | + +[[autodoc]] BambaConfig + + + +## BambaForCausalLM + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("ibm-fms/Bamba-9B") +tokenizer = AutoTokenizer.from_pretrained("ibm-fms/Bamba-9B") + +message = ["Mamba is a snake with following properties "] +inputs = tokenizer(message, return_tensors='pt', return_token_type_ids=False) +response = model.generate(**inputs, max_new_tokens=64) +print(tokenizer.batch_decode(response, skip_special_tokens=True)[0]) +``` + +[[autodoc]] BambaForCausalLM + - forward + +This HF implementation is contributed by [ani300](https://github.com/ani300) and [fabianlim](https://github.com/fabianlim). diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bark.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bark.md new file mode 100644 index 0000000000000000000000000000000000000000..912f552fa7c0c503534ac6517053658de2a717c7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bark.md @@ -0,0 +1,237 @@ + + +# Bark + +
+PyTorch +FlashAttention +
+ +## Overview + +Bark is a transformer-based text-to-speech model proposed by Suno AI in [suno-ai/bark](https://github.com/suno-ai/bark). + +Bark is made of 4 main models: + +- [`BarkSemanticModel`] (also referred to as the 'text' model): a causal auto-regressive transformer model that takes as input tokenized text, and predicts semantic text tokens that capture the meaning of the text. +- [`BarkCoarseModel`] (also referred to as the 'coarse acoustics' model): a causal autoregressive transformer, that takes as input the results of the [`BarkSemanticModel`] model. It aims at predicting the first two audio codebooks necessary for EnCodec. +- [`BarkFineModel`] (the 'fine acoustics' model), this time a non-causal autoencoder transformer, which iteratively predicts the last codebooks based on the sum of the previous codebooks embeddings. +- having predicted all the codebook channels from the [`EncodecModel`], Bark uses it to decode the output audio array. + +It should be noted that each of the first three modules can support conditional speaker embeddings to condition the output sound according to specific predefined voice. + +This model was contributed by [Yoach Lacombe (ylacombe)](https://huggingface.co/ylacombe) and [Sanchit Gandhi (sanchit-gandhi)](https://github.com/sanchit-gandhi). +The original code can be found [here](https://github.com/suno-ai/bark). + +### Optimizing Bark + +Bark can be optimized with just a few extra lines of code, which **significantly reduces its memory footprint** and **accelerates inference**. + +#### Using half-precision + +You can speed up inference and reduce memory footprint by 50% simply by loading the model in half-precision. + +```python +from transformers import BarkModel +import torch + +device = "cuda" if torch.cuda.is_available() else "cpu" +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16).to(device) +``` + +#### Using CPU offload + +As mentioned above, Bark is made up of 4 sub-models, which are called up sequentially during audio generation. In other words, while one sub-model is in use, the other sub-models are idle. + +If you're using a CUDA device, a simple solution to benefit from an 80% reduction in memory footprint is to offload the submodels from GPU to CPU when they're idle. This operation is called *CPU offloading*. You can use it with one line of code as follows: + +```python +model.enable_cpu_offload() +``` + +Note that 🤗 Accelerate must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/accelerate/basic_tutorials/install) + +#### Using Better Transformer + +Better Transformer is an 🤗 Optimum feature that performs kernel fusion under the hood. You can gain 20% to 30% in speed with zero performance degradation. It only requires one line of code to export the model to 🤗 Better Transformer: + +```python +model = model.to_bettertransformer() +``` + +Note that 🤗 Optimum must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/optimum/installation) + +#### Using Flash Attention 2 + +Flash Attention 2 is an even faster, optimized version of the previous optimization. + +##### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + + +##### Usage + +To load a model using Flash Attention 2, we can pass the `attn_implementation="flash_attention_2"` flag to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference: + +```python +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) +``` + +##### Performance comparison + + +The following diagram shows the latency for the native attention implementation (no optimisation) against Better Transformer and Flash Attention 2. In all cases, we generate 400 semantic tokens on a 40GB A100 GPU with PyTorch 2.1. Flash Attention 2 is also consistently faster than Better Transformer, and its performance improves even more as batch sizes increase: + +
+ +
+ +To put this into perspective, on an NVIDIA A100 and when generating 400 semantic tokens with a batch size of 16, you can get 17 times the [throughput](https://huggingface.co/blog/optimizing-bark#throughput) and still be 2 seconds faster than generating sentences one by one with the native model implementation. In other words, all the samples will be generated 17 times faster. + +At batch size 8, on an NVIDIA A100, Flash Attention 2 is also 10% faster than Better Transformer, and at batch size 16, 25%. + + +#### Combining optimization techniques + +You can combine optimization techniques, and use CPU offload, half-precision and Flash Attention 2 (or 🤗 Better Transformer) all at once. + +```python +from transformers import BarkModel +import torch + +device = "cuda" if torch.cuda.is_available() else "cpu" + +# load in fp16 and use Flash Attention 2 +model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) + +# enable CPU offload +model.enable_cpu_offload() +``` + +Find out more on inference optimization techniques [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one). + +### Usage tips + +Suno offers a library of voice presets in a number of languages [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c). +These presets are also uploaded in the hub [here](https://huggingface.co/suno/bark-small/tree/main/speaker_embeddings) or [here](https://huggingface.co/suno/bark/tree/main/speaker_embeddings). + +```python +>>> from transformers import AutoProcessor, BarkModel + +>>> processor = AutoProcessor.from_pretrained("suno/bark") +>>> model = BarkModel.from_pretrained("suno/bark") + +>>> voice_preset = "v2/en_speaker_6" + +>>> inputs = processor("Hello, my dog is cute", voice_preset=voice_preset) + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +Bark can generate highly realistic, **multilingual** speech as well as other audio - including music, background noise and simple sound effects. + +```python +>>> # Multilingual speech - simplified Chinese +>>> inputs = processor("惊人的!我会说中文") + +>>> # Multilingual speech - French - let's use a voice_preset as well +>>> inputs = processor("Incroyable! Je peux générer du son.", voice_preset="fr_speaker_5") + +>>> # Bark can also generate music. You can help it out by adding music notes around your lyrics. +>>> inputs = processor("♪ Hello, my dog is cute ♪") + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +The model can also produce **nonverbal communications** like laughing, sighing and crying. + + +```python +>>> # Adding non-speech cues to the input text +>>> inputs = processor("Hello uh ... [clears throat], my dog is cute [laughter]") + +>>> audio_array = model.generate(**inputs) +>>> audio_array = audio_array.cpu().numpy().squeeze() +``` + +To save the audio, simply take the sample rate from the model config and some scipy utility: + +```python +>>> from scipy.io.wavfile import write as write_wav + +>>> # save audio to disk, but first take the sample rate from the model config +>>> sample_rate = model.generation_config.sample_rate +>>> write_wav("bark_generation.wav", sample_rate, audio_array) +``` + +## BarkConfig + +[[autodoc]] BarkConfig + - all + +## BarkProcessor + +[[autodoc]] BarkProcessor + - all + - __call__ + +## BarkModel + +[[autodoc]] BarkModel + - generate + - enable_cpu_offload + +## BarkSemanticModel + +[[autodoc]] BarkSemanticModel + - forward + +## BarkCoarseModel + +[[autodoc]] BarkCoarseModel + - forward + +## BarkFineModel + +[[autodoc]] BarkFineModel + - forward + +## BarkCausalModel + +[[autodoc]] BarkCausalModel + - forward + +## BarkCoarseConfig + +[[autodoc]] BarkCoarseConfig + - all + +## BarkFineConfig + +[[autodoc]] BarkFineConfig + - all + +## BarkSemanticConfig + +[[autodoc]] BarkSemanticConfig + - all + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bart.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bart.md new file mode 100644 index 0000000000000000000000000000000000000000..aaccd78047db100da208b1cab8757562bfd49315 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bart.md @@ -0,0 +1,228 @@ + + +# BART + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +## Overview + +The Bart model was proposed in [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, +Translation, and Comprehension](https://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan +Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer on 29 Oct, 2019. + +According to the abstract, + +- Bart uses a standard seq2seq/machine translation architecture with a bidirectional encoder (like BERT) and a + left-to-right decoder (like GPT). +- The pretraining task involves randomly shuffling the order of the original sentences and a novel in-filling scheme, + where spans of text are replaced with a single mask token. +- BART is particularly effective when fine tuned for text generation but also works well for comprehension tasks. It + matches the performance of RoBERTa with comparable training resources on GLUE and SQuAD, achieves new + state-of-the-art results on a range of abstractive dialogue, question answering, and summarization tasks, with gains + of up to 6 ROUGE. + +This model was contributed by [sshleifer](https://huggingface.co/sshleifer). The authors' code can be found [here](https://github.com/pytorch/fairseq/tree/master/examples/bart). + +## Usage tips: + +- BART is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. +- Sequence-to-sequence model with an encoder and a decoder. Encoder is fed a corrupted version of the tokens, decoder is fed the original tokens (but has a mask to hide the future words like a regular transformers decoder). A composition of the following transformations are applied on the pretraining tasks for the encoder: + + * mask random tokens (like in BERT) + * delete random tokens + * mask a span of k tokens with a single mask token (a span of 0 tokens is an insertion of a mask token) + * permute sentences + * rotate the document to make it start at a specific token + +## Implementation Notes + +- Bart doesn't use `token_type_ids` for sequence classification. Use [`BartTokenizer`] or + [`~BartTokenizer.encode`] to get the proper splitting. +- The forward pass of [`BartModel`] will create the `decoder_input_ids` if they are not passed. + This is different than some other modeling APIs. A typical use case of this feature is mask filling. +- Model predictions are intended to be identical to the original implementation when + `forced_bos_token_id=0`. This only works, however, if the string you pass to + [`fairseq.encode`] starts with a space. +- [`~generation.GenerationMixin.generate`] should be used for conditional generation tasks like + summarization, see the example in that docstrings. +- Models that load the *facebook/bart-large-cnn* weights will not have a `mask_token_id`, or be able to perform + mask-filling tasks. + +## Mask Filling + +The `facebook/bart-base` and `facebook/bart-large` checkpoints can be used to fill multi-token masks. + +```python +from transformers import BartForConditionalGeneration, BartTokenizer + +model = BartForConditionalGeneration.from_pretrained("facebook/bart-large", forced_bos_token_id=0) +tok = BartTokenizer.from_pretrained("facebook/bart-large") +example_english_phrase = "UN Chief Says There Is No in Syria" +batch = tok(example_english_phrase, return_tensors="pt") +generated_ids = model.generate(batch["input_ids"]) +assert tok.batch_decode(generated_ids, skip_special_tokens=True) == [ + "UN Chief Says There Is No Plan to Stop Chemical Weapons in Syria" +] +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BART. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A blog post on [Distributed Training: Train BART/T5 for Summarization using 🤗 Transformers and Amazon SageMaker](https://huggingface.co/blog/sagemaker-distributed-training-seq2seq). +- A notebook on how to [finetune BART for summarization with fastai using blurr](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb). 🌎 +- A notebook on how to [finetune BART for summarization in two languages with Trainer class](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb). 🌎 +- [`BartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb). +- [`TFBartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb). +- [`FlaxBartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization). +- An example of how to train [`BartForConditionalGeneration`] with a Hugging Face `datasets` object can be found in this [forum discussion](https://discuss.huggingface.co/t/train-bart-for-conditional-generation-e-g-summarization/1904) +- [Summarization](https://huggingface.co/course/chapter7/5?fw=pt#summarization) chapter of the 🤗 Hugging Face course. +- [Summarization task guide](../tasks/summarization) + + + +- [`BartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFBartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxBartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Masked language modeling task guide](../tasks/masked_language_modeling) + + + +- A notebook on how to [finetune mBART using Seq2SeqTrainer for Hindi to English translation](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb). 🌎 +- [`BartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/translation) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb). +- [`TFBartForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/translation) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb). +- [Translation task guide](../tasks/translation) + +See also: +- [Text classification task guide](../tasks/sequence_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Distilled checkpoints](https://huggingface.co/models?search=distilbart) are described in this [paper](https://arxiv.org/abs/2010.13002). + +## BartConfig + +[[autodoc]] BartConfig + - all + +## BartTokenizer + +[[autodoc]] BartTokenizer + - all + +## BartTokenizerFast + +[[autodoc]] BartTokenizerFast + - all + + + + + +## BartModel + +[[autodoc]] BartModel + - forward + +## BartForConditionalGeneration + +[[autodoc]] BartForConditionalGeneration + - forward + +## BartForSequenceClassification + +[[autodoc]] BartForSequenceClassification + - forward + +## BartForQuestionAnswering + +[[autodoc]] BartForQuestionAnswering + - forward + +## BartForCausalLM + +[[autodoc]] BartForCausalLM + - forward + + + + +## TFBartModel + +[[autodoc]] TFBartModel + - call + +## TFBartForConditionalGeneration + +[[autodoc]] TFBartForConditionalGeneration + - call + +## TFBartForSequenceClassification + +[[autodoc]] TFBartForSequenceClassification + - call + + + + +## FlaxBartModel + +[[autodoc]] FlaxBartModel + - __call__ + - encode + - decode + +## FlaxBartForConditionalGeneration + +[[autodoc]] FlaxBartForConditionalGeneration + - __call__ + - encode + - decode + +## FlaxBartForSequenceClassification + +[[autodoc]] FlaxBartForSequenceClassification + - __call__ + - encode + - decode + +## FlaxBartForQuestionAnswering + +[[autodoc]] FlaxBartForQuestionAnswering + - __call__ + - encode + - decode + +## FlaxBartForCausalLM + +[[autodoc]] FlaxBartForCausalLM + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/barthez.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/barthez.md new file mode 100644 index 0000000000000000000000000000000000000000..131b1dd8e185437905832c10120edf13f1e03b7a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/barthez.md @@ -0,0 +1,67 @@ + + +# BARThez + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The BARThez model was proposed in [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis on 23 Oct, +2020. + +The abstract of the paper: + + +*Inductive transfer learning, enabled by self-supervised learning, have taken the entire Natural Language Processing +(NLP) field by storm, with models such as BERT and BART setting new state of the art on countless natural language +understanding tasks. While there are some notable exceptions, most of the available models and research have been +conducted for the English language. In this work, we introduce BARThez, the first BART model for the French language +(to the best of our knowledge). BARThez was pretrained on a very large monolingual French corpus from past research +that we adapted to suit BART's perturbation schemes. Unlike already existing BERT-based French language models such as +CamemBERT and FlauBERT, BARThez is particularly well-suited for generative tasks, since not only its encoder but also +its decoder is pretrained. In addition to discriminative tasks from the FLUE benchmark, we evaluate BARThez on a novel +summarization dataset, OrangeSum, that we release with this paper. We also continue the pretraining of an already +pretrained multilingual BART on BARThez's corpus, and we show that the resulting model, which we call mBARTHez, +provides a significant boost over vanilla BARThez, and is on par with or outperforms CamemBERT and FlauBERT.* + +This model was contributed by [moussakam](https://huggingface.co/moussakam). The Authors' code can be found [here](https://github.com/moussaKam/BARThez). + + + +BARThez implementation is the same as BART, except for tokenization. Refer to [BART documentation](bart) for information on +configuration classes and their parameters. BARThez-specific tokenizers are documented below. + + + +## Resources + +- BARThez can be fine-tuned on sequence-to-sequence tasks in a similar way as BART, check: + [examples/pytorch/summarization/](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization/README.md). + + +## BarthezTokenizer + +[[autodoc]] BarthezTokenizer + +## BarthezTokenizerFast + +[[autodoc]] BarthezTokenizerFast diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bartpho.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bartpho.md new file mode 100644 index 0000000000000000000000000000000000000000..b3749516323d5fb6481cf60317bf9c0328f1b650 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bartpho.md @@ -0,0 +1,93 @@ + + +# BARTpho + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The BARTpho model was proposed in [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen. + +The abstract from the paper is the following: + +*We present BARTpho with two versions -- BARTpho_word and BARTpho_syllable -- the first public large-scale monolingual +sequence-to-sequence models pre-trained for Vietnamese. Our BARTpho uses the "large" architecture and pre-training +scheme of the sequence-to-sequence denoising model BART, thus especially suitable for generative NLP tasks. Experiments +on a downstream task of Vietnamese text summarization show that in both automatic and human evaluations, our BARTpho +outperforms the strong baseline mBART and improves the state-of-the-art. We release BARTpho to facilitate future +research and applications of generative Vietnamese NLP tasks.* + +This model was contributed by [dqnguyen](https://huggingface.co/dqnguyen). The original code can be found [here](https://github.com/VinAIResearch/BARTpho). + +## Usage example + +```python +>>> import torch +>>> from transformers import AutoModel, AutoTokenizer + +>>> bartpho = AutoModel.from_pretrained("vinai/bartpho-syllable") + +>>> tokenizer = AutoTokenizer.from_pretrained("vinai/bartpho-syllable") + +>>> line = "Chúng tôi là những nghiên cứu viên." + +>>> input_ids = tokenizer(line, return_tensors="pt") + +>>> with torch.no_grad(): +... features = bartpho(**input_ids) # Models outputs are now tuples + +>>> # With TensorFlow 2.0+: +>>> from transformers import TFAutoModel + +>>> bartpho = TFAutoModel.from_pretrained("vinai/bartpho-syllable") +>>> input_ids = tokenizer(line, return_tensors="tf") +>>> features = bartpho(**input_ids) +``` + +## Usage tips + +- Following mBART, BARTpho uses the "large" architecture of BART with an additional layer-normalization layer on top of + both the encoder and decoder. Thus, usage examples in the [documentation of BART](bart), when adapting to use + with BARTpho, should be adjusted by replacing the BART-specialized classes with the mBART-specialized counterparts. + For example: + +```python +>>> from transformers import MBartForConditionalGeneration + +>>> bartpho = MBartForConditionalGeneration.from_pretrained("vinai/bartpho-syllable") +>>> TXT = "Chúng tôi là nghiên cứu viên." +>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"] +>>> logits = bartpho(input_ids).logits +>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item() +>>> probs = logits[0, masked_index].softmax(dim=0) +>>> values, predictions = probs.topk(5) +>>> print(tokenizer.decode(predictions).split()) +``` + +- This implementation is only for tokenization: "monolingual_vocab_file" consists of Vietnamese-specialized types + extracted from the pre-trained SentencePiece model "vocab_file" that is available from the multilingual XLM-RoBERTa. + Other languages, if employing this pre-trained multilingual SentencePiece model "vocab_file" for subword + segmentation, can reuse BartphoTokenizer with their own language-specialized "monolingual_vocab_file". + +## BartphoTokenizer + +[[autodoc]] BartphoTokenizer diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/beit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/beit.md new file mode 100644 index 0000000000000000000000000000000000000000..24dfabf682b6bf652dc9055e5fba2e503b67f891 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/beit.md @@ -0,0 +1,196 @@ + + +# BEiT + +
+PyTorch +Flax +SDPA +
+ +## Overview + +The BEiT model was proposed in [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by +Hangbo Bao, Li Dong and Furu Wei. Inspired by BERT, BEiT is the first paper that makes self-supervised pre-training of +Vision Transformers (ViTs) outperform supervised pre-training. Rather than pre-training the model to predict the class +of an image (as done in the [original ViT paper](https://arxiv.org/abs/2010.11929)), BEiT models are pre-trained to +predict visual tokens from the codebook of OpenAI's [DALL-E model](https://arxiv.org/abs/2102.12092) given masked +patches. + +The abstract from the paper is the following: + +*We introduce a self-supervised vision representation model BEiT, which stands for Bidirectional Encoder representation +from Image Transformers. Following BERT developed in the natural language processing area, we propose a masked image +modeling task to pretrain vision Transformers. Specifically, each image has two views in our pre-training, i.e, image +patches (such as 16x16 pixels), and visual tokens (i.e., discrete tokens). We first "tokenize" the original image into +visual tokens. Then we randomly mask some image patches and fed them into the backbone Transformer. The pre-training +objective is to recover the original visual tokens based on the corrupted image patches. After pre-training BEiT, we +directly fine-tune the model parameters on downstream tasks by appending task layers upon the pretrained encoder. +Experimental results on image classification and semantic segmentation show that our model achieves competitive results +with previous pre-training methods. For example, base-size BEiT achieves 83.2% top-1 accuracy on ImageNet-1K, +significantly outperforming from-scratch DeiT training (81.8%) with the same setup. Moreover, large-size BEiT obtains +86.3% only using ImageNet-1K, even outperforming ViT-L with supervised pre-training on ImageNet-22K (85.2%).* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The JAX/FLAX version of this model was +contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/beit). + +## Usage tips + +- BEiT models are regular Vision Transformers, but pre-trained in a self-supervised way rather than supervised. They + outperform both the [original model (ViT)](vit) as well as [Data-efficient Image Transformers (DeiT)](deit) when fine-tuned on ImageNet-1K and CIFAR-100. You can check out demo notebooks regarding inference as well as + fine-tuning on custom data [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer) (you can just replace + [`ViTFeatureExtractor`] by [`BeitImageProcessor`] and + [`ViTForImageClassification`] by [`BeitForImageClassification`]). +- There's also a demo notebook available which showcases how to combine DALL-E's image tokenizer with BEiT for + performing masked image modeling. You can find it [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BEiT). +- As the BEiT models expect each image to be of the same size (resolution), one can use + [`BeitImageProcessor`] to resize (or rescale) and normalize images for the model. +- Both the patch resolution and image resolution used during pre-training or fine-tuning are reflected in the name of + each checkpoint. For example, `microsoft/beit-base-patch16-224` refers to a base-sized architecture with patch + resolution of 16x16 and fine-tuning resolution of 224x224. All checkpoints can be found on the [hub](https://huggingface.co/models?search=microsoft/beit). +- The available checkpoints are either (1) pre-trained on [ImageNet-22k](http://www.image-net.org/) (a collection of + 14 million images and 22k classes) only, (2) also fine-tuned on ImageNet-22k or (3) also fine-tuned on [ImageNet-1k](http://www.image-net.org/challenges/LSVRC/2012/) (also referred to as ILSVRC 2012, a collection of 1.3 million + images and 1,000 classes). +- BEiT uses relative position embeddings, inspired by the T5 model. During pre-training, the authors shared the + relative position bias among the several self-attention layers. During fine-tuning, each layer's relative position + bias is initialized with the shared relative position bias obtained after pre-training. Note that, if one wants to + pre-train a model from scratch, one needs to either set the `use_relative_position_bias` or the + `use_relative_position_bias` attribute of [`BeitConfig`] to `True` in order to add + position embeddings. + + + + BEiT pre-training. Taken from the original paper. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import BeitForImageClassification +model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.5.1, OS Ubuntu 20.04) with `float16` and +`microsoft/beit-base-patch16-224` model, we saw the following improvements during training and inference: + +#### Training + +| num_training_steps | batch_size | image_size | is_cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | SDPA peak mem (MB) | Mem saving (%) | +|--------------------|------------|--------------|---------|----------------------------|---------------------------|-------------|----------------------|--------------------|----------------| +| 50 | 2 | (1048, 640) | True | 0.984 | 0.746 | 31.975 | 6738.915 | 4319.886 | 55.998 | + +#### Inference + +| Image batch size | Eager (s/iter) | Eager CI, % | Eager memory (MB) | SDPA (s/iter) | SDPA CI, % | SDPA memory (MB) | SDPA speedup | SDPA memory saved (%) | +|-------------------:|-----------------:|:--------------|--------------------:|----------------:|:-------------|-------------------:|---------------:|----------------------:| +| 1 | 0.012 | ±0.3% | 3.76657e+08 | 0.011 | ±0.5% | 3.75739e+08 | 1.05 | 0.244 | +| 4 | 0.013 | ±0.1% | 4.03147e+08 | 0.011 | ±0.2% | 3.90554e+08 | 1.178 | 3.225 | +| 16 | 0.045 | ±0.1% | 4.96697e+08 | 0.035 | ±0.1% | 4.51232e+08 | 1.304 | 10.076 | +| 32 | 0.088 | ±0.1% | 6.24417e+08 | 0.066 | ±0.1% | 5.33488e+08 | 1.325 | 17.044 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BEiT. + + + +- [`BeitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +**Semantic segmentation** +- [Semantic segmentation task guide](../tasks/semantic_segmentation) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## BEiT specific outputs + +[[autodoc]] models.beit.modeling_beit.BeitModelOutputWithPooling + +[[autodoc]] models.beit.modeling_flax_beit.FlaxBeitModelOutputWithPooling + +## BeitConfig + +[[autodoc]] BeitConfig + +## BeitFeatureExtractor + +[[autodoc]] BeitFeatureExtractor + - __call__ + - post_process_semantic_segmentation + +## BeitImageProcessor + +[[autodoc]] BeitImageProcessor + - preprocess + - post_process_semantic_segmentation + + + + +## BeitModel + +[[autodoc]] BeitModel + - forward + +## BeitForMaskedImageModeling + +[[autodoc]] BeitForMaskedImageModeling + - forward + +## BeitForImageClassification + +[[autodoc]] BeitForImageClassification + - forward + +## BeitForSemanticSegmentation + +[[autodoc]] BeitForSemanticSegmentation + - forward + + + + +## FlaxBeitModel + +[[autodoc]] FlaxBeitModel + - __call__ + +## FlaxBeitForMaskedImageModeling + +[[autodoc]] FlaxBeitForMaskedImageModeling + - __call__ + +## FlaxBeitForImageClassification + +[[autodoc]] FlaxBeitForImageClassification + - __call__ + + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-generation.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-generation.md new file mode 100644 index 0000000000000000000000000000000000000000..0c42adbeb56473069df6b0bfd40a4c1bf84b6d82 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-generation.md @@ -0,0 +1,111 @@ + + +# BertGeneration + +
+PyTorch +
+ +## Overview + +The BertGeneration model is a BERT model that can be leveraged for sequence-to-sequence tasks using +[`EncoderDecoderModel`] as proposed in [Leveraging Pre-trained Checkpoints for Sequence Generation +Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. + +The abstract from the paper is the following: + +*Unsupervised pretraining of large neural models has recently revolutionized Natural Language Processing. By +warm-starting from the publicly released checkpoints, NLP practitioners have pushed the state-of-the-art on multiple +benchmarks while saving significant amounts of compute time. So far the focus has been mainly on the Natural Language +Understanding tasks. In this paper, we demonstrate the efficacy of pre-trained checkpoints for Sequence Generation. We +developed a Transformer-based sequence-to-sequence model that is compatible with publicly available pre-trained BERT, +GPT-2 and RoBERTa checkpoints and conducted an extensive empirical study on the utility of initializing our model, both +encoder and decoder, with these checkpoints. Our models result in new state-of-the-art results on Machine Translation, +Text Summarization, Sentence Splitting, and Sentence Fusion.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The original code can be +found [here](https://tfhub.dev/s?module-type=text-generation&subtype=module,placeholder). + +## Usage examples and tips + +The model can be used in combination with the [`EncoderDecoderModel`] to leverage two pretrained BERT checkpoints for +subsequent fine-tuning: + +```python +>>> # leverage checkpoints for Bert2Bert model... +>>> # use BERT's cls token as BOS token and sep token as EOS token +>>> encoder = BertGenerationEncoder.from_pretrained("google-bert/bert-large-uncased", bos_token_id=101, eos_token_id=102) +>>> # add cross attention layers and use BERT's cls token as BOS token and sep token as EOS token +>>> decoder = BertGenerationDecoder.from_pretrained( +... "google-bert/bert-large-uncased", add_cross_attention=True, is_decoder=True, bos_token_id=101, eos_token_id=102 +... ) +>>> bert2bert = EncoderDecoderModel(encoder=encoder, decoder=decoder) + +>>> # create tokenizer... +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-large-uncased") + +>>> input_ids = tokenizer( +... "This is a long article to summarize", add_special_tokens=False, return_tensors="pt" +... ).input_ids +>>> labels = tokenizer("This is a short summary", return_tensors="pt").input_ids + +>>> # train... +>>> loss = bert2bert(input_ids=input_ids, decoder_input_ids=labels, labels=labels).loss +>>> loss.backward() +``` + +Pretrained [`EncoderDecoderModel`] are also directly available in the model hub, e.g.: + +```python +>>> # instantiate sentence fusion model +>>> sentence_fuser = EncoderDecoderModel.from_pretrained("google/roberta2roberta_L-24_discofuse") +>>> tokenizer = AutoTokenizer.from_pretrained("google/roberta2roberta_L-24_discofuse") + +>>> input_ids = tokenizer( +... "This is the first sentence. This is the second sentence.", add_special_tokens=False, return_tensors="pt" +... ).input_ids + +>>> outputs = sentence_fuser.generate(input_ids) + +>>> print(tokenizer.decode(outputs[0])) +``` + +Tips: + +- [`BertGenerationEncoder`] and [`BertGenerationDecoder`] should be used in + combination with [`EncoderDecoder`]. +- For summarization, sentence splitting, sentence fusion and translation, no special tokens are required for the input. + Therefore, no EOS token should be added to the end of the input. + +## BertGenerationConfig + +[[autodoc]] BertGenerationConfig + +## BertGenerationTokenizer + +[[autodoc]] BertGenerationTokenizer + - save_vocabulary + +## BertGenerationEncoder + +[[autodoc]] BertGenerationEncoder + - forward + +## BertGenerationDecoder + +[[autodoc]] BertGenerationDecoder + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-japanese.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-japanese.md new file mode 100644 index 0000000000000000000000000000000000000000..33a720318b63718ef65a316145a92750e69fb9c1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert-japanese.md @@ -0,0 +1,89 @@ + + +# BertJapanese + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The BERT models trained on Japanese text. + +There are models with two different tokenization methods: + +- Tokenize with MeCab and WordPiece. This requires some extra dependencies, [fugashi](https://github.com/polm/fugashi) which is a wrapper around [MeCab](https://taku910.github.io/mecab/). +- Tokenize into characters. + +To use *MecabTokenizer*, you should `pip install transformers["ja"]` (or `pip install -e .["ja"]` if you install +from source) to install dependencies. + +See [details on cl-tohoku repository](https://github.com/cl-tohoku/bert-japanese). + +Example of using a model with MeCab and WordPiece tokenization: + +```python +>>> import torch +>>> from transformers import AutoModel, AutoTokenizer + +>>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese") +>>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese") + +>>> ## Input Japanese Text +>>> line = "吾輩は猫である。" + +>>> inputs = tokenizer(line, return_tensors="pt") + +>>> print(tokenizer.decode(inputs["input_ids"][0])) +[CLS] 吾輩 は 猫 で ある 。 [SEP] + +>>> outputs = bertjapanese(**inputs) +``` + +Example of using a model with Character tokenization: + +```python +>>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese-char") +>>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-char") + +>>> ## Input Japanese Text +>>> line = "吾輩は猫である。" + +>>> inputs = tokenizer(line, return_tensors="pt") + +>>> print(tokenizer.decode(inputs["input_ids"][0])) +[CLS] 吾 輩 は 猫 で あ る 。 [SEP] + +>>> outputs = bertjapanese(**inputs) +``` + +This model was contributed by [cl-tohoku](https://huggingface.co/cl-tohoku). + + + +This implementation is the same as BERT, except for tokenization method. Refer to [BERT documentation](bert) for +API reference information. + + + + +## BertJapaneseTokenizer + +[[autodoc]] BertJapaneseTokenizer diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert.md new file mode 100644 index 0000000000000000000000000000000000000000..883fba9a076df98021240b6396e9e312228c59b1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bert.md @@ -0,0 +1,357 @@ + + +# BERT + +
+PyTorch +TensorFlow +Flax +SDPA +
+ +## Overview + +The BERT model was proposed in [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. It's a +bidirectional transformer pretrained using a combination of masked language modeling objective and next sentence +prediction on a large corpus comprising the Toronto Book Corpus and Wikipedia. + +The abstract from the paper is the following: + +*We introduce a new language representation model called BERT, which stands for Bidirectional Encoder Representations +from Transformers. Unlike recent language representation models, BERT is designed to pre-train deep bidirectional +representations from unlabeled text by jointly conditioning on both left and right context in all layers. As a result, +the pre-trained BERT model can be fine-tuned with just one additional output layer to create state-of-the-art models +for a wide range of tasks, such as question answering and language inference, without substantial task-specific +architecture modifications.* + +*BERT is conceptually simple and empirically powerful. It obtains new state-of-the-art results on eleven natural +language processing tasks, including pushing the GLUE score to 80.5% (7.7% point absolute improvement), MultiNLI +accuracy to 86.7% (4.6% absolute improvement), SQuAD v1.1 question answering Test F1 to 93.2 (1.5 point absolute +improvement) and SQuAD v2.0 Test F1 to 83.1 (5.1 point absolute improvement).* + +This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://github.com/google-research/bert). + +## Usage tips + +- BERT is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. +- BERT was trained with the masked language modeling (MLM) and next sentence prediction (NSP) objectives. It is + efficient at predicting masked tokens and at NLU in general, but is not optimal for text generation. +- Corrupts the inputs by using random masking, more precisely, during pretraining, a given percentage of tokens (usually 15%) is masked by: + + * a special mask token with probability 0.8 + * a random token different from the one masked with probability 0.1 + * the same token with probability 0.1 + +- The model must predict the original sentence, but has a second objective: inputs are two sentences A and B (with a separation token in between). With probability 50%, the sentences are consecutive in the corpus, in the remaining 50% they are not related. The model has to predict if the sentences are consecutive or not. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import BertModel + +model = BertModel.from_pretrained("bert-base-uncased", torch_dtype=torch.float16, attn_implementation="sdpa") +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (A100-80GB, CPUx12, RAM 96.6GB, PyTorch 2.2.0, OS Ubuntu 22.04) with `float16`, we saw the +following speedups during training and inference. + +#### Training + +|batch_size|seq_len|Time per batch (eager - s)|Time per batch (sdpa - s)|Speedup (%)|Eager peak mem (MB)|sdpa peak mem (MB)|Mem saving (%)| +|----------|-------|--------------------------|-------------------------|-----------|-------------------|------------------|--------------| +|4 |256 |0.023 |0.017 |35.472 |939.213 |764.834 |22.800 | +|4 |512 |0.023 |0.018 |23.687 |1970.447 |1227.162 |60.569 | +|8 |256 |0.023 |0.018 |23.491 |1594.295 |1226.114 |30.028 | +|8 |512 |0.035 |0.025 |43.058 |3629.401 |2134.262 |70.054 | +|16 |256 |0.030 |0.024 |25.583 |2874.426 |2134.262 |34.680 | +|16 |512 |0.064 |0.044 |46.223 |6964.659 |3961.013 |75.830 | + +#### Inference + +|batch_size|seq_len|Per token latency eager (ms)|Per token latency SDPA (ms)|Speedup (%)|Mem eager (MB)|Mem BT (MB)|Mem saved (%)| +|----------|-------|----------------------------|---------------------------|-----------|--------------|-----------|-------------| +|1 |128 |5.736 |4.987 |15.022 |282.661 |282.924 |-0.093 | +|1 |256 |5.689 |4.945 |15.055 |298.686 |298.948 |-0.088 | +|2 |128 |6.154 |4.982 |23.521 |314.523 |314.785 |-0.083 | +|2 |256 |6.201 |4.949 |25.303 |347.546 |347.033 |0.148 | +|4 |128 |6.049 |4.987 |21.305 |378.895 |379.301 |-0.107 | +|4 |256 |6.285 |5.364 |17.166 |443.209 |444.382 |-0.264 | + + + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BERT. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A blog post on [BERT Text Classification in a different language](https://www.philschmid.de/bert-text-classification-in-a-different-language). +- A notebook for [Finetuning BERT (and friends) for multi-label text classification](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/BERT/Fine_tuning_BERT_(and_friends)_for_multi_label_text_classification.ipynb). +- A notebook on how to [Finetune BERT for multi-label classification using PyTorch](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb). 🌎 +- A notebook on how to [warm-start an EncoderDecoder model with BERT for summarization](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb). +- [`BertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb). +- [`TFBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). +- [`FlaxBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb). +- [Text classification task guide](../tasks/sequence_classification) + + + +- A blog post on how to use [Hugging Face Transformers with Keras: Fine-tune a non-English BERT for Named Entity Recognition](https://www.philschmid.de/huggingface-transformers-keras-tf). +- A notebook for [Finetuning BERT for named-entity recognition](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/BERT/Custom_Named_Entity_Recognition_with_BERT_only_first_wordpiece.ipynb) using only the first wordpiece of each word in the word label during tokenization. To propagate the label of the word to all wordpieces, see this [version](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/BERT/Custom_Named_Entity_Recognition_with_BERT.ipynb) of the notebook instead. +- [`BertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb). +- [`TFBertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). +- [`FlaxBertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/token-classification). +- [Token classification](https://huggingface.co/course/chapter7/2?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Token classification task guide](../tasks/token_classification) + + + +- [`BertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFBertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxBertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Masked language modeling task guide](../tasks/masked_language_modeling) + + + +- [`BertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb). +- [`TFBertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). +- [`FlaxBertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/question-answering). +- [Question answering](https://huggingface.co/course/chapter7/7?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Question answering task guide](../tasks/question_answering) + +**Multiple choice** +- [`BertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb). +- [`TFBertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb). +- [Multiple choice task guide](../tasks/multiple_choice) + +⚡️ **Inference** +- A blog post on how to [Accelerate BERT inference with Hugging Face Transformers and AWS Inferentia](https://huggingface.co/blog/bert-inferentia-sagemaker). +- A blog post on how to [Accelerate BERT inference with DeepSpeed-Inference on GPUs](https://www.philschmid.de/bert-deepspeed-inference). + +⚙️ **Pretraining** +- A blog post on [Pre-Training BERT with Hugging Face Transformers and Habana Gaudi](https://www.philschmid.de/pre-training-bert-habana). + +🚀 **Deploy** +- A blog post on how to [Convert Transformers to ONNX with Hugging Face Optimum](https://www.philschmid.de/convert-transformers-to-onnx). +- A blog post on how to [Setup Deep Learning environment for Hugging Face Transformers with Habana Gaudi on AWS](https://www.philschmid.de/getting-started-habana-gaudi#conclusion). +- A blog post on [Autoscaling BERT with Hugging Face Transformers, Amazon SageMaker and Terraform module](https://www.philschmid.de/terraform-huggingface-amazon-sagemaker-advanced). +- A blog post on [Serverless BERT with HuggingFace, AWS Lambda, and Docker](https://www.philschmid.de/serverless-bert-with-huggingface-aws-lambda-docker). +- A blog post on [Hugging Face Transformers BERT fine-tuning using Amazon SageMaker and Training Compiler](https://www.philschmid.de/huggingface-amazon-sagemaker-training-compiler). +- A blog post on [Task-specific knowledge distillation for BERT using Transformers & Amazon SageMaker](https://www.philschmid.de/knowledge-distillation-bert-transformers). + +## BertConfig + +[[autodoc]] BertConfig + - all + +## BertTokenizer + +[[autodoc]] BertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + + + + +## BertTokenizerFast + +[[autodoc]] BertTokenizerFast + + + + +## TFBertTokenizer + +[[autodoc]] TFBertTokenizer + + + + +## Bert specific outputs + +[[autodoc]] models.bert.modeling_bert.BertForPreTrainingOutput + +[[autodoc]] models.bert.modeling_tf_bert.TFBertForPreTrainingOutput + +[[autodoc]] models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput + + + + + +## BertModel + +[[autodoc]] BertModel + - forward + +## BertForPreTraining + +[[autodoc]] BertForPreTraining + - forward + +## BertLMHeadModel + +[[autodoc]] BertLMHeadModel + - forward + +## BertForMaskedLM + +[[autodoc]] BertForMaskedLM + - forward + +## BertForNextSentencePrediction + +[[autodoc]] BertForNextSentencePrediction + - forward + +## BertForSequenceClassification + +[[autodoc]] BertForSequenceClassification + - forward + +## BertForMultipleChoice + +[[autodoc]] BertForMultipleChoice + - forward + +## BertForTokenClassification + +[[autodoc]] BertForTokenClassification + - forward + +## BertForQuestionAnswering + +[[autodoc]] BertForQuestionAnswering + - forward + + + + +## TFBertModel + +[[autodoc]] TFBertModel + - call + +## TFBertForPreTraining + +[[autodoc]] TFBertForPreTraining + - call + +## TFBertModelLMHeadModel + +[[autodoc]] TFBertLMHeadModel + - call + +## TFBertForMaskedLM + +[[autodoc]] TFBertForMaskedLM + - call + +## TFBertForNextSentencePrediction + +[[autodoc]] TFBertForNextSentencePrediction + - call + +## TFBertForSequenceClassification + +[[autodoc]] TFBertForSequenceClassification + - call + +## TFBertForMultipleChoice + +[[autodoc]] TFBertForMultipleChoice + - call + +## TFBertForTokenClassification + +[[autodoc]] TFBertForTokenClassification + - call + +## TFBertForQuestionAnswering + +[[autodoc]] TFBertForQuestionAnswering + - call + + + + +## FlaxBertModel + +[[autodoc]] FlaxBertModel + - __call__ + +## FlaxBertForPreTraining + +[[autodoc]] FlaxBertForPreTraining + - __call__ + +## FlaxBertForCausalLM + +[[autodoc]] FlaxBertForCausalLM + - __call__ + +## FlaxBertForMaskedLM + +[[autodoc]] FlaxBertForMaskedLM + - __call__ + +## FlaxBertForNextSentencePrediction + +[[autodoc]] FlaxBertForNextSentencePrediction + - __call__ + +## FlaxBertForSequenceClassification + +[[autodoc]] FlaxBertForSequenceClassification + - __call__ + +## FlaxBertForMultipleChoice + +[[autodoc]] FlaxBertForMultipleChoice + - __call__ + +## FlaxBertForTokenClassification + +[[autodoc]] FlaxBertForTokenClassification + - __call__ + +## FlaxBertForQuestionAnswering + +[[autodoc]] FlaxBertForQuestionAnswering + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bertweet.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bertweet.md new file mode 100644 index 0000000000000000000000000000000000000000..be489643173f72a95d7885dd27b8e14e19965a6c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bertweet.md @@ -0,0 +1,76 @@ + + +# BERTweet + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The BERTweet model was proposed in [BERTweet: A pre-trained language model for English Tweets](https://www.aclweb.org/anthology/2020.emnlp-demos.2.pdf) by Dat Quoc Nguyen, Thanh Vu, Anh Tuan Nguyen. + +The abstract from the paper is the following: + +*We present BERTweet, the first public large-scale pre-trained language model for English Tweets. Our BERTweet, having +the same architecture as BERT-base (Devlin et al., 2019), is trained using the RoBERTa pre-training procedure (Liu et +al., 2019). Experiments show that BERTweet outperforms strong baselines RoBERTa-base and XLM-R-base (Conneau et al., +2020), producing better performance results than the previous state-of-the-art models on three Tweet NLP tasks: +Part-of-speech tagging, Named-entity recognition and text classification.* + +This model was contributed by [dqnguyen](https://huggingface.co/dqnguyen). The original code can be found [here](https://github.com/VinAIResearch/BERTweet). + +## Usage example + +```python +>>> import torch +>>> from transformers import AutoModel, AutoTokenizer + +>>> bertweet = AutoModel.from_pretrained("vinai/bertweet-base") + +>>> # For transformers v4.x+: +>>> tokenizer = AutoTokenizer.from_pretrained("vinai/bertweet-base", use_fast=False) + +>>> # For transformers v3.x: +>>> # tokenizer = AutoTokenizer.from_pretrained("vinai/bertweet-base") + +>>> # INPUT TWEET IS ALREADY NORMALIZED! +>>> line = "SC has first two presumptive cases of coronavirus , DHEC confirms HTTPURL via @USER :cry:" + +>>> input_ids = torch.tensor([tokenizer.encode(line)]) + +>>> with torch.no_grad(): +... features = bertweet(input_ids) # Models outputs are now tuples + +>>> # With TensorFlow 2.0+: +>>> # from transformers import TFAutoModel +>>> # bertweet = TFAutoModel.from_pretrained("vinai/bertweet-base") +``` + + + +This implementation is the same as BERT, except for tokenization method. Refer to [BERT documentation](bert) for +API reference information. + + + +## BertweetTokenizer + +[[autodoc]] BertweetTokenizer diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/big_bird.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/big_bird.md new file mode 100644 index 0000000000000000000000000000000000000000..32ca5a2062a2ee6aa5b95f384a8437809889fd44 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/big_bird.md @@ -0,0 +1,184 @@ + + +# BigBird + +
+PyTorch +Flax +
+ +## Overview + +The BigBird model was proposed in [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by +Zaheer, Manzil and Guruganesh, Guru and Dubey, Kumar Avinava and Ainslie, Joshua and Alberti, Chris and Ontanon, +Santiago and Pham, Philip and Ravula, Anirudh and Wang, Qifan and Yang, Li and others. BigBird, is a sparse-attention +based transformer which extends Transformer based models, such as BERT to much longer sequences. In addition to sparse +attention, BigBird also applies global attention as well as random attention to the input sequence. Theoretically, it +has been shown that applying sparse, global, and random attention approximates full attention, while being +computationally much more efficient for longer sequences. As a consequence of the capability to handle longer context, +BigBird has shown improved performance on various long document NLP tasks, such as question answering and +summarization, compared to BERT or RoBERTa. + +The abstract from the paper is the following: + +*Transformers-based models, such as BERT, have been one of the most successful deep learning models for NLP. +Unfortunately, one of their core limitations is the quadratic dependency (mainly in terms of memory) on the sequence +length due to their full attention mechanism. To remedy this, we propose, BigBird, a sparse attention mechanism that +reduces this quadratic dependency to linear. We show that BigBird is a universal approximator of sequence functions and +is Turing complete, thereby preserving these properties of the quadratic, full attention model. Along the way, our +theoretical analysis reveals some of the benefits of having O(1) global tokens (such as CLS), that attend to the entire +sequence as part of the sparse attention mechanism. The proposed sparse attention can handle sequences of length up to +8x of what was previously possible using similar hardware. As a consequence of the capability to handle longer context, +BigBird drastically improves performance on various NLP tasks such as question answering and summarization. We also +propose novel applications to genomics data.* + +This model was contributed by [vasudevgupta](https://huggingface.co/vasudevgupta). The original code can be found +[here](https://github.com/google-research/bigbird). + +## Usage tips + +- For an in-detail explanation on how BigBird's attention works, see [this blog post](https://huggingface.co/blog/big-bird). +- BigBird comes with 2 implementations: **original_full** & **block_sparse**. For the sequence length < 1024, using + **original_full** is advised as there is no benefit in using **block_sparse** attention. +- The code currently uses window size of 3 blocks and 2 global blocks. +- Sequence length must be divisible by block size. +- Current implementation supports only **ITC**. +- Current implementation doesn't support **num_random_blocks = 0** +- BigBird is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. + + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## BigBirdConfig + +[[autodoc]] BigBirdConfig + +## BigBirdTokenizer + +[[autodoc]] BigBirdTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## BigBirdTokenizerFast + +[[autodoc]] BigBirdTokenizerFast + +## BigBird specific outputs + +[[autodoc]] models.big_bird.modeling_big_bird.BigBirdForPreTrainingOutput + + + + +## BigBirdModel + +[[autodoc]] BigBirdModel + - forward + +## BigBirdForPreTraining + +[[autodoc]] BigBirdForPreTraining + - forward + +## BigBirdForCausalLM + +[[autodoc]] BigBirdForCausalLM + - forward + +## BigBirdForMaskedLM + +[[autodoc]] BigBirdForMaskedLM + - forward + +## BigBirdForSequenceClassification + +[[autodoc]] BigBirdForSequenceClassification + - forward + +## BigBirdForMultipleChoice + +[[autodoc]] BigBirdForMultipleChoice + - forward + +## BigBirdForTokenClassification + +[[autodoc]] BigBirdForTokenClassification + - forward + +## BigBirdForQuestionAnswering + +[[autodoc]] BigBirdForQuestionAnswering + - forward + + + + +## FlaxBigBirdModel + +[[autodoc]] FlaxBigBirdModel + - __call__ + +## FlaxBigBirdForPreTraining + +[[autodoc]] FlaxBigBirdForPreTraining + - __call__ + +## FlaxBigBirdForCausalLM + +[[autodoc]] FlaxBigBirdForCausalLM + - __call__ + +## FlaxBigBirdForMaskedLM + +[[autodoc]] FlaxBigBirdForMaskedLM + - __call__ + +## FlaxBigBirdForSequenceClassification + +[[autodoc]] FlaxBigBirdForSequenceClassification + - __call__ + +## FlaxBigBirdForMultipleChoice + +[[autodoc]] FlaxBigBirdForMultipleChoice + - __call__ + +## FlaxBigBirdForTokenClassification + +[[autodoc]] FlaxBigBirdForTokenClassification + - __call__ + +## FlaxBigBirdForQuestionAnswering + +[[autodoc]] FlaxBigBirdForQuestionAnswering + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bigbird_pegasus.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bigbird_pegasus.md new file mode 100644 index 0000000000000000000000000000000000000000..499d40b3149b4d8989a3da4ba0fc3bc35af041ce --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bigbird_pegasus.md @@ -0,0 +1,99 @@ + + +# BigBirdPegasus + +
+PyTorch +
+ +## Overview + +The BigBird model was proposed in [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) by +Zaheer, Manzil and Guruganesh, Guru and Dubey, Kumar Avinava and Ainslie, Joshua and Alberti, Chris and Ontanon, +Santiago and Pham, Philip and Ravula, Anirudh and Wang, Qifan and Yang, Li and others. BigBird, is a sparse-attention +based transformer which extends Transformer based models, such as BERT to much longer sequences. In addition to sparse +attention, BigBird also applies global attention as well as random attention to the input sequence. Theoretically, it +has been shown that applying sparse, global, and random attention approximates full attention, while being +computationally much more efficient for longer sequences. As a consequence of the capability to handle longer context, +BigBird has shown improved performance on various long document NLP tasks, such as question answering and +summarization, compared to BERT or RoBERTa. + +The abstract from the paper is the following: + +*Transformers-based models, such as BERT, have been one of the most successful deep learning models for NLP. +Unfortunately, one of their core limitations is the quadratic dependency (mainly in terms of memory) on the sequence +length due to their full attention mechanism. To remedy this, we propose, BigBird, a sparse attention mechanism that +reduces this quadratic dependency to linear. We show that BigBird is a universal approximator of sequence functions and +is Turing complete, thereby preserving these properties of the quadratic, full attention model. Along the way, our +theoretical analysis reveals some of the benefits of having O(1) global tokens (such as CLS), that attend to the entire +sequence as part of the sparse attention mechanism. The proposed sparse attention can handle sequences of length up to +8x of what was previously possible using similar hardware. As a consequence of the capability to handle longer context, +BigBird drastically improves performance on various NLP tasks such as question answering and summarization. We also +propose novel applications to genomics data.* + +The original code can be found [here](https://github.com/google-research/bigbird). + +## Usage tips + +- For an in-detail explanation on how BigBird's attention works, see [this blog post](https://huggingface.co/blog/big-bird). +- BigBird comes with 2 implementations: **original_full** & **block_sparse**. For the sequence length < 1024, using + **original_full** is advised as there is no benefit in using **block_sparse** attention. +- The code currently uses window size of 3 blocks and 2 global blocks. +- Sequence length must be divisible by block size. +- Current implementation supports only **ITC**. +- Current implementation doesn't support **num_random_blocks = 0**. +- BigBirdPegasus uses the [PegasusTokenizer](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pegasus/tokenization_pegasus.py). +- BigBird is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## BigBirdPegasusConfig + +[[autodoc]] BigBirdPegasusConfig + - all + +## BigBirdPegasusModel + +[[autodoc]] BigBirdPegasusModel + - forward + +## BigBirdPegasusForConditionalGeneration + +[[autodoc]] BigBirdPegasusForConditionalGeneration + - forward + +## BigBirdPegasusForSequenceClassification + +[[autodoc]] BigBirdPegasusForSequenceClassification + - forward + +## BigBirdPegasusForQuestionAnswering + +[[autodoc]] BigBirdPegasusForQuestionAnswering + - forward + +## BigBirdPegasusForCausalLM + +[[autodoc]] BigBirdPegasusForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/biogpt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/biogpt.md new file mode 100644 index 0000000000000000000000000000000000000000..ab8aea6c29e855ad07db816b8a27644bb2f9dc47 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/biogpt.md @@ -0,0 +1,121 @@ + + +# BioGPT + +
+PyTorch +SDPA +
+ +## Overview + +The BioGPT model was proposed in [BioGPT: generative pre-trained transformer for biomedical text generation and mining](https://academic.oup.com/bib/advance-article/doi/10.1093/bib/bbac409/6713511?guestAccessKey=a66d9b5d-4f83-4017-bb52-405815c907b9) by Renqian Luo, Liai Sun, Yingce Xia, Tao Qin, Sheng Zhang, Hoifung Poon and Tie-Yan Liu. BioGPT is a domain-specific generative pre-trained Transformer language model for biomedical text generation and mining. BioGPT follows the Transformer language model backbone, and is pre-trained on 15M PubMed abstracts from scratch. + +The abstract from the paper is the following: + +*Pre-trained language models have attracted increasing attention in the biomedical domain, inspired by their great success in the general natural language domain. Among the two main branches of pre-trained language models in the general language domain, i.e. BERT (and its variants) and GPT (and its variants), the first one has been extensively studied in the biomedical domain, such as BioBERT and PubMedBERT. While they have achieved great success on a variety of discriminative downstream biomedical tasks, the lack of generation ability constrains their application scope. In this paper, we propose BioGPT, a domain-specific generative Transformer language model pre-trained on large-scale biomedical literature. We evaluate BioGPT on six biomedical natural language processing tasks and demonstrate that our model outperforms previous models on most tasks. Especially, we get 44.98%, 38.42% and 40.76% F1 score on BC5CDR, KD-DTI and DDI end-to-end relation extraction tasks, respectively, and 78.2% accuracy on PubMedQA, creating a new record. Our case study on text generation further demonstrates the advantage of BioGPT on biomedical literature to generate fluent descriptions for biomedical terms.* + +This model was contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/microsoft/BioGPT). + +## Usage tips + +- BioGPT is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than the left. +- BioGPT was trained with a causal language modeling (CLM) objective and is therefore powerful at predicting the next token in a sequence. Leveraging this feature allows BioGPT to generate syntactically coherent text as it can be observed in the run_generation.py example script. +- The model can take the `past_key_values` (for PyTorch) as input, which is the previously computed key/value attention pairs. Using this (past_key_values or past) value prevents the model from re-computing pre-computed values in the context of text generation. For PyTorch, see past_key_values argument of the BioGptForCausalLM.forward() method for more information on its usage. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import BioGptForCausalLM +model = BioGptForCausalLM.from_pretrained("microsoft/biogpt", attn_implementation="sdpa", torch_dtype=torch.float16) +``` + +On a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.3.1, OS Ubuntu 20.04) with `float16` and `microsoft/biogpt` model with a CausalLM head, +we saw the following speedups during training. + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +| num_training_steps | batch_size | seq_len | is cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | sdpa peak mem (MB) | Mem saving (%) | +|--------------------|------------|---------|---------|----------------------------|---------------------------|-------------|---------------------|--------------------|----------------| +| 100 | 1 | 128 | False | 0.038 | 0.031 | 21.301 | 1601.862 | 1601.497 | 0.023 | +| 100 | 1 | 256 | False | 0.039 | 0.034 | 15.084 | 1624.944 | 1625.296 | -0.022 | +| 100 | 2 | 128 | False | 0.039 | 0.033 | 16.820 | 1624.567 | 1625.296 | -0.045 | +| 100 | 2 | 256 | False | 0.065 | 0.059 | 10.255 | 1672.164 | 1672.164 | 0.000 | +| 100 | 4 | 128 | False | 0.062 | 0.058 | 6.998 | 1671.435 | 1672.164 | -0.044 | +| 100 | 4 | 256 | False | 0.113 | 0.100 | 13.316 | 2350.179 | 1848.435 | 27.144 | +| 100 | 8 | 128 | False | 0.107 | 0.098 | 9.883 | 2098.521 | 1848.435 | 13.530 | +| 100 | 8 | 256 | False | 0.222 | 0.196 | 13.413 | 3989.980 | 2986.492 | 33.601 | + +On a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.3.1, OS Ubuntu 20.04) with `float16` and `microsoft/biogpt` model with a simple AutoModel head, +we saw the following speedups during inference. + +| num_batches | batch_size | seq_len | is cuda | is half | use mask | Per token latency eager (ms) | Per token latency SDPA (ms) | Speedup (%) | Mem eager (MB) | Mem BT (MB) | Mem saved (%) | +|-------------|------------|---------|---------|---------|----------|------------------------------|-----------------------------|-------------|----------------|--------------|---------------| +| 50 | 1 | 64 | True | True | True | 0.115 | 0.098 | 17.392 | 716.998 | 716.998 | 0.000 | +| 50 | 1 | 128 | True | True | True | 0.115 | 0.093 | 24.640 | 730.916 | 730.916 | 0.000 | +| 50 | 2 | 64 | True | True | True | 0.114 | 0.096 | 19.204 | 730.900 | 730.900 | 0.000 | +| 50 | 2 | 128 | True | True | True | 0.117 | 0.095 | 23.529 | 759.262 | 759.262 | 0.000 | +| 50 | 4 | 64 | True | True | True | 0.113 | 0.096 | 18.325 | 759.229 | 759.229 | 0.000 | +| 50 | 4 | 128 | True | True | True | 0.186 | 0.178 | 4.289 | 816.478 | 816.478 | 0.000 | + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) + +## BioGptConfig + +[[autodoc]] BioGptConfig + + +## BioGptTokenizer + +[[autodoc]] BioGptTokenizer + - save_vocabulary + + +## BioGptModel + +[[autodoc]] BioGptModel + - forward + + +## BioGptForCausalLM + +[[autodoc]] BioGptForCausalLM + - forward + + +## BioGptForTokenClassification + +[[autodoc]] BioGptForTokenClassification + - forward + + +## BioGptForSequenceClassification + +[[autodoc]] BioGptForSequenceClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bit.md new file mode 100644 index 0000000000000000000000000000000000000000..550c07662dd7a3d42437487e571cd83485078940 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bit.md @@ -0,0 +1,69 @@ + + +# Big Transfer (BiT) + +
+PyTorch +
+ +## Overview + +The BiT model was proposed in [Big Transfer (BiT): General Visual Representation Learning](https://arxiv.org/abs/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby. +BiT is a simple recipe for scaling up pre-training of [ResNet](resnet)-like architectures (specifically, ResNetv2). The method results in significant improvements for transfer learning. + +The abstract from the paper is the following: + +*Transfer of pre-trained representations improves sample efficiency and simplifies hyperparameter tuning when training deep neural networks for vision. We revisit the paradigm of pre-training on large supervised datasets and fine-tuning the model on a target task. We scale up pre-training, and propose a simple recipe that we call Big Transfer (BiT). By combining a few carefully selected components, and transferring using a simple heuristic, we achieve strong performance on over 20 datasets. BiT performs well across a surprisingly wide range of data regimes -- from 1 example per class to 1M total examples. BiT achieves 87.5% top-1 accuracy on ILSVRC-2012, 99.4% on CIFAR-10, and 76.3% on the 19 task Visual Task Adaptation Benchmark (VTAB). On small datasets, BiT attains 76.8% on ILSVRC-2012 with 10 examples per class, and 97.0% on CIFAR-10 with 10 examples per class. We conduct detailed analysis of the main components that lead to high transfer performance.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/google-research/big_transfer). + +## Usage tips + +- BiT models are equivalent to ResNetv2 in terms of architecture, except that: 1) all batch normalization layers are replaced by [group normalization](https://arxiv.org/abs/1803.08494), +2) [weight standardization](https://arxiv.org/abs/1903.10520) is used for convolutional layers. The authors show that the combination of both is useful for training with large batch sizes, and has a significant +impact on transfer learning. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BiT. + + + +- [`BitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## BitConfig + +[[autodoc]] BitConfig + +## BitImageProcessor + +[[autodoc]] BitImageProcessor + - preprocess + +## BitModel + +[[autodoc]] BitModel + - forward + +## BitForImageClassification + +[[autodoc]] BitForImageClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot-small.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot-small.md new file mode 100644 index 0000000000000000000000000000000000000000..647a865de339ad9a1cdde43641a6c9c962329915 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot-small.md @@ -0,0 +1,130 @@ + + +# Blenderbot Small + +
+PyTorch +TensorFlow +Flax +
+ +Note that [`BlenderbotSmallModel`] and +[`BlenderbotSmallForConditionalGeneration`] are only used in combination with the checkpoint +[facebook/blenderbot-90M](https://huggingface.co/facebook/blenderbot-90M). Larger Blenderbot checkpoints should +instead be used with [`BlenderbotModel`] and +[`BlenderbotForConditionalGeneration`] + +## Overview + +The Blender chatbot model was proposed in [Recipes for building an open-domain chatbot](https://arxiv.org/pdf/2004.13637.pdf) Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, +Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston on 30 Apr 2020. + +The abstract of the paper is the following: + +*Building open-domain chatbots is a challenging area for machine learning research. While prior work has shown that +scaling neural models in the number of parameters and the size of the data they are trained on gives improved results, +we show that other ingredients are important for a high-performing chatbot. Good conversation requires a number of +skills that an expert conversationalist blends in a seamless way: providing engaging talking points and listening to +their partners, and displaying knowledge, empathy and personality appropriately, while maintaining a consistent +persona. We show that large scale models can learn these skills when given appropriate training data and choice of +generation strategy. We build variants of these recipes with 90M, 2.7B and 9.4B parameter models, and make our models +and code publicly available. Human evaluations show our best models are superior to existing approaches in multi-turn +dialogue in terms of engagingness and humanness measurements. We then discuss the limitations of this work by analyzing +failure cases of our models.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The authors' code can be +found [here](https://github.com/facebookresearch/ParlAI). + +## Usage tips + +Blenderbot Small is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than +the left. + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## BlenderbotSmallConfig + +[[autodoc]] BlenderbotSmallConfig + +## BlenderbotSmallTokenizer + +[[autodoc]] BlenderbotSmallTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## BlenderbotSmallTokenizerFast + +[[autodoc]] BlenderbotSmallTokenizerFast + + + + +## BlenderbotSmallModel + +[[autodoc]] BlenderbotSmallModel + - forward + +## BlenderbotSmallForConditionalGeneration + +[[autodoc]] BlenderbotSmallForConditionalGeneration + - forward + +## BlenderbotSmallForCausalLM + +[[autodoc]] BlenderbotSmallForCausalLM + - forward + + + + +## TFBlenderbotSmallModel + +[[autodoc]] TFBlenderbotSmallModel + - call + +## TFBlenderbotSmallForConditionalGeneration + +[[autodoc]] TFBlenderbotSmallForConditionalGeneration + - call + + + + +## FlaxBlenderbotSmallModel + +[[autodoc]] FlaxBlenderbotSmallModel + - __call__ + - encode + - decode + +## FlaxBlenderbotForConditionalGeneration + +[[autodoc]] FlaxBlenderbotSmallForConditionalGeneration + - __call__ + - encode + - decode + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot.md new file mode 100644 index 0000000000000000000000000000000000000000..ec24d5ed7495191393cfca0afca97b26c5c26887 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blenderbot.md @@ -0,0 +1,151 @@ + + +# Blenderbot + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The Blender chatbot model was proposed in [Recipes for building an open-domain chatbot](https://arxiv.org/pdf/2004.13637.pdf) Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, +Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston on 30 Apr 2020. + +The abstract of the paper is the following: + +*Building open-domain chatbots is a challenging area for machine learning research. While prior work has shown that +scaling neural models in the number of parameters and the size of the data they are trained on gives improved results, +we show that other ingredients are important for a high-performing chatbot. Good conversation requires a number of +skills that an expert conversationalist blends in a seamless way: providing engaging talking points and listening to +their partners, and displaying knowledge, empathy and personality appropriately, while maintaining a consistent +persona. We show that large scale models can learn these skills when given appropriate training data and choice of +generation strategy. We build variants of these recipes with 90M, 2.7B and 9.4B parameter models, and make our models +and code publicly available. Human evaluations show our best models are superior to existing approaches in multi-turn +dialogue in terms of engagingness and humanness measurements. We then discuss the limitations of this work by analyzing +failure cases of our models.* + +This model was contributed by [sshleifer](https://huggingface.co/sshleifer). The authors' code can be found [here](https://github.com/facebookresearch/ParlAI) . + +## Usage tips and example + +Blenderbot is a model with absolute position embeddings so it's usually advised to pad the inputs on the right +rather than the left. + +An example: + +```python +>>> from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration + +>>> mname = "facebook/blenderbot-400M-distill" +>>> model = BlenderbotForConditionalGeneration.from_pretrained(mname) +>>> tokenizer = BlenderbotTokenizer.from_pretrained(mname) +>>> UTTERANCE = "My friends are cool but they eat too many carbs." +>>> inputs = tokenizer([UTTERANCE], return_tensors="pt") +>>> reply_ids = model.generate(**inputs) +>>> print(tokenizer.batch_decode(reply_ids)) +[" That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"] +``` + +## Implementation Notes + +- Blenderbot uses a standard [seq2seq model transformer](https://arxiv.org/pdf/1706.03762.pdf) based architecture. +- Available checkpoints can be found in the [model hub](https://huggingface.co/models?search=blenderbot). +- This is the *default* Blenderbot model class. However, some smaller checkpoints, such as + `facebook/blenderbot_small_90M`, have a different architecture and consequently should be used with + [BlenderbotSmall](blenderbot-small). + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## BlenderbotConfig + +[[autodoc]] BlenderbotConfig + +## BlenderbotTokenizer + +[[autodoc]] BlenderbotTokenizer + - build_inputs_with_special_tokens + +## BlenderbotTokenizerFast + +[[autodoc]] BlenderbotTokenizerFast + - build_inputs_with_special_tokens + + + + + +## BlenderbotModel + +See [`~transformers.BartModel`] for arguments to *forward* and *generate* + +[[autodoc]] BlenderbotModel + - forward + +## BlenderbotForConditionalGeneration + +See [`~transformers.BartForConditionalGeneration`] for arguments to *forward* and *generate* + +[[autodoc]] BlenderbotForConditionalGeneration + - forward + +## BlenderbotForCausalLM + +[[autodoc]] BlenderbotForCausalLM + - forward + + + + +## TFBlenderbotModel + +[[autodoc]] TFBlenderbotModel + - call + +## TFBlenderbotForConditionalGeneration + +[[autodoc]] TFBlenderbotForConditionalGeneration + - call + + + + +## FlaxBlenderbotModel + +[[autodoc]] FlaxBlenderbotModel + - __call__ + - encode + - decode + +## FlaxBlenderbotForConditionalGeneration + +[[autodoc]] FlaxBlenderbotForConditionalGeneration + - __call__ + - encode + - decode + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip-2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip-2.md new file mode 100644 index 0000000000000000000000000000000000000000..94331d9a5f6e7c069070ea8069e858d24fe6eb66 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip-2.md @@ -0,0 +1,111 @@ + + +# BLIP-2 + +
+PyTorch +
+ +## Overview + +The BLIP-2 model was proposed in [BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models](https://arxiv.org/abs/2301.12597) by +Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi. BLIP-2 leverages frozen pre-trained image encoders and large language models (LLMs) by training a lightweight, 12-layer Transformer +encoder in between them, achieving state-of-the-art performance on various vision-language tasks. Most notably, BLIP-2 improves upon [Flamingo](https://arxiv.org/abs/2204.14198), an 80 billion parameter model, by 8.7% +on zero-shot VQAv2 with 54x fewer trainable parameters. + +The abstract from the paper is the following: + +*The cost of vision-and-language pre-training has become increasingly prohibitive due to end-to-end training of large-scale models. This paper proposes BLIP-2, a generic and efficient pre-training strategy that bootstraps vision-language pre-training from off-the-shelf frozen pre-trained image encoders and frozen large language models. BLIP-2 bridges the modality gap with a lightweight Querying Transformer, which is pre-trained in two stages. The first stage bootstraps vision-language representation learning from a frozen image encoder. The second stage bootstraps vision-to-language generative learning from a frozen language model. BLIP-2 achieves state-of-the-art performance on various vision-language tasks, despite having significantly fewer trainable parameters than existing methods. For example, our model outperforms Flamingo80B by 8.7% on zero-shot VQAv2 with 54x fewer trainable parameters. We also demonstrate the model's emerging capabilities of zero-shot image-to-text generation that can follow natural language instructions.* + + + + BLIP-2 architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/salesforce/LAVIS/tree/5ee63d688ba4cebff63acee04adaef2dee9af207). + +## Usage tips + +- BLIP-2 can be used for conditional text generation given an image and an optional text prompt. At inference time, it's recommended to use the [`generate`] method. +- One can use [`Blip2Processor`] to prepare images for the model, and decode the predicted tokens ID's back to text. + +> [!NOTE] +> BLIP models after release v4.46 will raise warnings about adding `processor.num_query_tokens = {{num_query_tokens}}` and expand model embeddings layer to add special `` token. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. Adding these attributes means that BLIP will add the number of query tokens required per image and expand the text with as many `` placeholders as there will be query tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there wil be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.num_query_tokens` and model embeddings expansion can be done by following [this link](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BLIP-2. + +- Demo notebooks for BLIP-2 for image captioning, visual question answering (VQA) and chat-like conversations can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BLIP-2). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## Blip2Config + +[[autodoc]] Blip2Config + - from_vision_qformer_text_configs + +## Blip2VisionConfig + +[[autodoc]] Blip2VisionConfig + +## Blip2QFormerConfig + +[[autodoc]] Blip2QFormerConfig + +## Blip2Processor + +[[autodoc]] Blip2Processor + +## Blip2VisionModel + +[[autodoc]] Blip2VisionModel + - forward + +## Blip2QFormerModel + +[[autodoc]] Blip2QFormerModel + - forward + +## Blip2Model + +[[autodoc]] Blip2Model + - forward + - get_text_features + - get_image_features + - get_qformer_features + +## Blip2ForConditionalGeneration + +[[autodoc]] Blip2ForConditionalGeneration + - forward + - generate + +## Blip2ForImageTextRetrieval + +[[autodoc]] Blip2ForImageTextRetrieval + - forward + +## Blip2TextModelWithProjection + +[[autodoc]] Blip2TextModelWithProjection + +## Blip2VisionModelWithProjection + +[[autodoc]] Blip2VisionModelWithProjection diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip.md new file mode 100644 index 0000000000000000000000000000000000000000..1acf172f26b8cef3cbd2054c887a575d7fbce089 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/blip.md @@ -0,0 +1,146 @@ + + +# BLIP + +
+PyTorch +TensorFlow +
+ +## Overview + +The BLIP model was proposed in [BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://arxiv.org/abs/2201.12086) by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi. + +BLIP is a model that is able to perform various multi-modal tasks including: +- Visual Question Answering +- Image-Text retrieval (Image-text matching) +- Image Captioning + +The abstract from the paper is the following: + +*Vision-Language Pre-training (VLP) has advanced the performance for many vision-language tasks. +However, most existing pre-trained models only excel in either understanding-based tasks or generation-based tasks. Furthermore, performance improvement has been largely achieved by scaling up the dataset with noisy image-text pairs collected from the web, which is a suboptimal source of supervision. In this paper, we propose BLIP, a new VLP framework which transfers flexibly to both vision-language understanding and generation tasks. BLIP effectively utilizes the noisy web data by bootstrapping the captions, where a captioner generates synthetic captions and a filter removes the noisy ones. We achieve state-of-the-art results on a wide range of vision-language tasks, such as image-text retrieval (+2.7% in average recall@1), image captioning (+2.8% in CIDEr), and VQA (+1.6% in VQA score). BLIP also demonstrates strong generalization ability when directly transferred to videolanguage tasks in a zero-shot manner. Code, models, and datasets are released.* + +![BLIP.gif](https://cdn-uploads.huggingface.co/production/uploads/1670928184033-62441d1d9fdefb55a0b7d12c.gif) + +This model was contributed by [ybelkada](https://huggingface.co/ybelkada). +The original code can be found [here](https://github.com/salesforce/BLIP). + +## Resources + +- [Jupyter notebook](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) on how to fine-tune BLIP for image captioning on a custom dataset + +## BlipConfig + +[[autodoc]] BlipConfig + - from_text_vision_configs + +## BlipTextConfig + +[[autodoc]] BlipTextConfig + +## BlipVisionConfig + +[[autodoc]] BlipVisionConfig + +## BlipProcessor + +[[autodoc]] BlipProcessor + +## BlipImageProcessor + +[[autodoc]] BlipImageProcessor + - preprocess + +## BlipImageProcessorFast + +[[autodoc]] BlipImageProcessorFast + - preprocess + + + + +## BlipModel + +`BlipModel` is going to be deprecated in future versions, please use `BlipForConditionalGeneration`, `BlipForImageTextRetrieval` or `BlipForQuestionAnswering` depending on your usecase. + +[[autodoc]] BlipModel + - forward + - get_text_features + - get_image_features + +## BlipTextModel + +[[autodoc]] BlipTextModel + - forward + +## BlipVisionModel + +[[autodoc]] BlipVisionModel + - forward + +## BlipForConditionalGeneration + +[[autodoc]] BlipForConditionalGeneration + - forward + +## BlipForImageTextRetrieval + +[[autodoc]] BlipForImageTextRetrieval + - forward + +## BlipForQuestionAnswering + +[[autodoc]] BlipForQuestionAnswering + - forward + + + + +## TFBlipModel + +[[autodoc]] TFBlipModel + - call + - get_text_features + - get_image_features + +## TFBlipTextModel + +[[autodoc]] TFBlipTextModel + - call + +## TFBlipVisionModel + +[[autodoc]] TFBlipVisionModel + - call + +## TFBlipForConditionalGeneration + +[[autodoc]] TFBlipForConditionalGeneration + - call + +## TFBlipForImageTextRetrieval + +[[autodoc]] TFBlipForImageTextRetrieval + - call + +## TFBlipForQuestionAnswering + +[[autodoc]] TFBlipForQuestionAnswering + - call + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bloom.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bloom.md new file mode 100644 index 0000000000000000000000000000000000000000..9de98705957475c3fa0bd551aff0733c0a854626 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bloom.md @@ -0,0 +1,115 @@ + + +# BLOOM + +
+PyTorch +Flax +
+ +## Overview + +The BLOOM model has been proposed with its various versions through the [BigScience Workshop](https://bigscience.huggingface.co/). BigScience is inspired by other open science initiatives where researchers have pooled their time and resources to collectively achieve a higher impact. +The architecture of BLOOM is essentially similar to GPT3 (auto-regressive model for next token prediction), but has been trained on 46 different languages and 13 programming languages. +Several smaller versions of the models have been trained on the same dataset. BLOOM is available in the following versions: + +- [bloom-560m](https://huggingface.co/bigscience/bloom-560m) +- [bloom-1b1](https://huggingface.co/bigscience/bloom-1b1) +- [bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) +- [bloom-3b](https://huggingface.co/bigscience/bloom-3b) +- [bloom-7b1](https://huggingface.co/bigscience/bloom-7b1) +- [bloom](https://huggingface.co/bigscience/bloom) (176B parameters) + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BLOOM. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- [`BloomForCausalLM`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#gpt-2gpt-and-causal-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). + +See also: +- [Causal language modeling task guide](../tasks/language_modeling) +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) + + +⚡️ Inference +- A blog on [Optimization story: Bloom inference](https://huggingface.co/blog/bloom-inference-optimization). +- A blog on [Incredibly Fast BLOOM Inference with DeepSpeed and Accelerate](https://huggingface.co/blog/bloom-inference-pytorch-scripts). + +⚙️ Training +- A blog on [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed). + +## BloomConfig + +[[autodoc]] BloomConfig + - all + +## BloomTokenizerFast + +[[autodoc]] BloomTokenizerFast + - all + + + + + +## BloomModel + +[[autodoc]] BloomModel + - forward + +## BloomForCausalLM + +[[autodoc]] BloomForCausalLM + - forward + +## BloomForSequenceClassification + +[[autodoc]] BloomForSequenceClassification + - forward + +## BloomForTokenClassification + +[[autodoc]] BloomForTokenClassification + - forward + +## BloomForQuestionAnswering + +[[autodoc]] BloomForQuestionAnswering + - forward + + + + +## FlaxBloomModel + +[[autodoc]] FlaxBloomModel + - __call__ + +## FlaxBloomForCausalLM + +[[autodoc]] FlaxBloomForCausalLM + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bort.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bort.md new file mode 100644 index 0000000000000000000000000000000000000000..04cc2feb063b99b87d9a2bd7931d9f422d6bc4b2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bort.md @@ -0,0 +1,64 @@ + + +# BORT + +
+PyTorch +TensorFlow +Flax +
+ + + +This model is in maintenance mode only, we do not accept any new PRs changing its code. + +If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0. +You can do so by running the following command: `pip install -U transformers==4.30.0`. + + + +## Overview + +The BORT model was proposed in [Optimal Subarchitecture Extraction for BERT](https://arxiv.org/abs/2010.10499) by +Adrian de Wynter and Daniel J. Perry. It is an optimal subset of architectural parameters for the BERT, which the +authors refer to as "Bort". + +The abstract from the paper is the following: + +*We extract an optimal subset of architectural parameters for the BERT architecture from Devlin et al. (2018) by +applying recent breakthroughs in algorithms for neural architecture search. This optimal subset, which we refer to as +"Bort", is demonstrably smaller, having an effective (that is, not counting the embedding layer) size of 5.5% the +original BERT-large architecture, and 16% of the net size. Bort is also able to be pretrained in 288 GPU hours, which +is 1.2% of the time required to pretrain the highest-performing BERT parametric architectural variant, RoBERTa-large +(Liu et al., 2019), and about 33% of that of the world-record, in GPU hours, required to train BERT-large on the same +hardware. It is also 7.9x faster on a CPU, as well as being better performing than other compressed variants of the +architecture, and some of the non-compressed variants: it obtains performance improvements of between 0.3% and 31%, +absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks.* + +This model was contributed by [stefan-it](https://huggingface.co/stefan-it). The original code can be found [here](https://github.com/alexa/bort/). + +## Usage tips + +- BORT's model architecture is based on BERT, refer to [BERT's documentation page](bert) for the + model's API reference as well as usage examples. +- BORT uses the RoBERTa tokenizer instead of the BERT tokenizer, refer to [RoBERTa's documentation page](roberta) for the tokenizer's API reference as well as usage examples. +- BORT requires a specific fine-tuning algorithm, called [Agora](https://adewynter.github.io/notes/bort_algorithms_and_applications.html#fine-tuning-with-algebraic-topology) , + that is sadly not open-sourced yet. It would be very useful for the community, if someone tries to implement the + algorithm to make BORT fine-tuning work. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bridgetower.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bridgetower.md new file mode 100644 index 0000000000000000000000000000000000000000..2aee4cdebe5db9b0c183469159059cda16c113bf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bridgetower.md @@ -0,0 +1,174 @@ + + +# BridgeTower + +
+PyTorch +
+ +## Overview + +The BridgeTower model was proposed in [BridgeTower: Building Bridges Between Encoders in Vision-Language Representative Learning](https://arxiv.org/abs/2206.08657) by Xiao Xu, Chenfei Wu, Shachar Rosenman, Vasudev Lal, Wanxiang Che, Nan Duan. The goal of this model is to build a +bridge between each uni-modal encoder and the cross-modal encoder to enable comprehensive and detailed interaction at each layer of the cross-modal encoder thus achieving remarkable performance on various downstream tasks with almost negligible additional performance and computational costs. + +This paper has been accepted to the [AAAI'23](https://aaai.org/Conferences/AAAI-23/) conference. + +The abstract from the paper is the following: + +*Vision-Language (VL) models with the TWO-TOWER architecture have dominated visual-language representation learning in recent years. +Current VL models either use lightweight uni-modal encoders and learn to extract, align and fuse both modalities simultaneously in a deep cross-modal encoder, or feed the last-layer uni-modal representations from the deep pre-trained uni-modal encoders into the top cross-modal encoder. +Both approaches potentially restrict vision-language representation learning and limit model performance. In this paper, we propose BRIDGETOWER, which introduces multiple bridge layers that build a connection between the top layers of uni-modal encoders and each layer of the crossmodal encoder. +This enables effective bottom-up cross-modal alignment and fusion between visual and textual representations of different semantic levels of pre-trained uni-modal encoders in the cross-modal encoder. Pre-trained with only 4M images, BRIDGETOWER achieves state-of-the-art performance on various downstream vision-language tasks. +In particular, on the VQAv2 test-std set, BRIDGETOWER achieves an accuracy of 78.73%, outperforming the previous state-of-the-art model METER by 1.09% with the same pre-training data and almost negligible additional parameters and computational costs. +Notably, when further scaling the model, BRIDGETOWER achieves an accuracy of 81.15%, surpassing models that are pre-trained on orders-of-magnitude larger datasets.* + + + + BridgeTower architecture. Taken from the original paper. + +This model was contributed by [Anahita Bhiwandiwalla](https://huggingface.co/anahita-b), [Tiep Le](https://huggingface.co/Tile) and [Shaoyen Tseng](https://huggingface.co/shaoyent). The original code can be found [here](https://github.com/microsoft/BridgeTower). + +## Usage tips and examples + +BridgeTower consists of a visual encoder, a textual encoder and cross-modal encoder with multiple lightweight bridge layers. +The goal of this approach was to build a bridge between each uni-modal encoder and the cross-modal encoder to enable comprehensive and detailed interaction at each layer of the cross-modal encoder. +In principle, one can apply any visual, textual or cross-modal encoder in the proposed architecture. + +The [`BridgeTowerProcessor`] wraps [`RobertaTokenizer`] and [`BridgeTowerImageProcessor`] into a single instance to both +encode the text and prepare the images respectively. + +The following example shows how to run contrastive learning using [`BridgeTowerProcessor`] and [`BridgeTowerForContrastiveLearning`]. +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning +>>> import requests +>>> from PIL import Image + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") +>>> model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") + +>>> # forward pass +>>> scores = dict() +>>> for text in texts: +... # prepare inputs +... encoding = processor(image, text, return_tensors="pt") +... outputs = model(**encoding) +... scores[text] = outputs +``` + +The following example shows how to run image-text retrieval using [`BridgeTowerProcessor`] and [`BridgeTowerForImageAndTextRetrieval`]. +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForImageAndTextRetrieval +>>> import requests +>>> from PIL import Image + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") +>>> model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") + +>>> # forward pass +>>> scores = dict() +>>> for text in texts: +... # prepare inputs +... encoding = processor(image, text, return_tensors="pt") +... outputs = model(**encoding) +... scores[text] = outputs.logits[0, 1].item() +``` + +The following example shows how to run masked language modeling using [`BridgeTowerProcessor`] and [`BridgeTowerForMaskedLM`]. + +```python +>>> from transformers import BridgeTowerProcessor, BridgeTowerForMaskedLM +>>> from PIL import Image +>>> import requests + +>>> url = "http://images.cocodataset.org/val2017/000000360943.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB") +>>> text = "a looking out of the window" + +>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") +>>> model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") + +>>> # prepare inputs +>>> encoding = processor(image, text, return_tensors="pt") + +>>> # forward pass +>>> outputs = model(**encoding) + +>>> results = processor.decode(outputs.logits.argmax(dim=-1).squeeze(0).tolist()) + +>>> print(results) +.a cat looking out of the window. +``` + +Tips: + +- This implementation of BridgeTower uses [`RobertaTokenizer`] to generate text embeddings and OpenAI's CLIP/ViT model to compute visual embeddings. +- Checkpoints for pre-trained [bridgeTower-base](https://huggingface.co/BridgeTower/bridgetower-base) and [bridgetower masked language modeling and image text matching](https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm) are released. +- Please refer to [Table 5](https://arxiv.org/pdf/2206.08657.pdf) for BridgeTower's performance on Image Retrieval and other down stream tasks. +- The PyTorch version of this model is only available in torch 1.10 and higher. + + +## BridgeTowerConfig + +[[autodoc]] BridgeTowerConfig + +## BridgeTowerTextConfig + +[[autodoc]] BridgeTowerTextConfig + +## BridgeTowerVisionConfig + +[[autodoc]] BridgeTowerVisionConfig + +## BridgeTowerImageProcessor + +[[autodoc]] BridgeTowerImageProcessor + - preprocess + +## BridgeTowerProcessor + +[[autodoc]] BridgeTowerProcessor + - __call__ + +## BridgeTowerModel + +[[autodoc]] BridgeTowerModel + - forward + +## BridgeTowerForContrastiveLearning + +[[autodoc]] BridgeTowerForContrastiveLearning + - forward + +## BridgeTowerForMaskedLM + +[[autodoc]] BridgeTowerForMaskedLM + - forward + +## BridgeTowerForImageAndTextRetrieval + +[[autodoc]] BridgeTowerForImageAndTextRetrieval + - forward + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bros.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bros.md new file mode 100644 index 0000000000000000000000000000000000000000..baa658e598fbc6a5c1c83c41077a148ffdb0c1f7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/bros.md @@ -0,0 +1,118 @@ + + +# BROS + +
+PyTorch +
+ +## Overview + +The BROS model was proposed in [BROS: A Pre-trained Language Model Focusing on Text and Layout for Better Key Information Extraction from Documents](https://arxiv.org/abs/2108.04539) by Teakgyu Hong, Donghyun Kim, Mingi Ji, Wonseok Hwang, Daehyun Nam, Sungrae Park. + +BROS stands for *BERT Relying On Spatiality*. It is an encoder-only Transformer model that takes a sequence of tokens and their bounding boxes as inputs and outputs a sequence of hidden states. BROS encode relative spatial information instead of using absolute spatial information. + +It is pre-trained with two objectives: a token-masked language modeling objective (TMLM) used in BERT, and a novel area-masked language modeling objective (AMLM) +In TMLM, tokens are randomly masked, and the model predicts the masked tokens using spatial information and other unmasked tokens. +AMLM is a 2D version of TMLM. It randomly masks text tokens and predicts with the same information as TMLM, but it masks text blocks (areas). + +`BrosForTokenClassification` has a simple linear layer on top of BrosModel. It predicts the label of each token. +`BrosSpadeEEForTokenClassification` has an `initial_token_classifier` and `subsequent_token_classifier` on top of BrosModel. `initial_token_classifier` is used to predict the first token of each entity, and `subsequent_token_classifier` is used to predict the next token of within entity. `BrosSpadeELForTokenClassification` has an `entity_linker` on top of BrosModel. `entity_linker` is used to predict the relation between two entities. + +`BrosForTokenClassification` and `BrosSpadeEEForTokenClassification` essentially perform the same job. However, `BrosForTokenClassification` assumes input tokens are perfectly serialized (which is very challenging task since they exist in a 2D space), while `BrosSpadeEEForTokenClassification` allows for more flexibility in handling serialization errors as it predicts next connection tokens from one token. + +`BrosSpadeELForTokenClassification` perform the intra-entity linking task. It predicts relation from one token (of one entity) to another token (of another entity) if these two entities share some relation. + +BROS achieves comparable or better result on Key Information Extraction (KIE) benchmarks such as FUNSD, SROIE, CORD and SciTSR, without relying on explicit visual features. + +The abstract from the paper is the following: + +*Key information extraction (KIE) from document images requires understanding the contextual and spatial semantics of texts in two-dimensional (2D) space. Many recent studies try to solve the task by developing pre-trained language models focusing on combining visual features from document images with texts and their layout. On the other hand, this paper tackles the problem by going back to the basic: effective combination of text and layout. Specifically, we propose a pre-trained language model, named BROS (BERT Relying On Spatiality), that encodes relative positions of texts in 2D space and learns from unlabeled documents with area-masking strategy. With this optimized training scheme for understanding texts in 2D space, BROS shows comparable or better performance compared to previous methods on four KIE benchmarks (FUNSD, SROIE*, CORD, and SciTSR) without relying on visual features. This paper also reveals two real-world challenges in KIE tasks-(1) minimizing the error from incorrect text ordering and (2) efficient learning from fewer downstream examples-and demonstrates the superiority of BROS over previous methods.* + +This model was contributed by [jinho8345](https://huggingface.co/jinho8345). The original code can be found [here](https://github.com/clovaai/bros). + +## Usage tips and examples + +- [`~transformers.BrosModel.forward`] requires `input_ids` and `bbox` (bounding box). Each bounding box should be in (x0, y0, x1, y1) format (top-left corner, bottom-right corner). Obtaining of Bounding boxes depends on external OCR system. The `x` coordinate should be normalized by document image width, and the `y` coordinate should be normalized by document image height. + +```python +def expand_and_normalize_bbox(bboxes, doc_width, doc_height): + # here, bboxes are numpy array + + # Normalize bbox -> 0 ~ 1 + bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / width + bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / height +``` + +- [`~transformers.BrosForTokenClassification.forward`, `~transformers.BrosSpadeEEForTokenClassification.forward`, `~transformers.BrosSpadeEEForTokenClassification.forward`] require not only `input_ids` and `bbox` but also `box_first_token_mask` for loss calculation. It is a mask to filter out non-first tokens of each box. You can obtain this mask by saving start token indices of bounding boxes when creating `input_ids` from words. You can make `box_first_token_mask` with following code, + + +```python +def make_box_first_token_mask(bboxes, words, tokenizer, max_seq_length=512): + + box_first_token_mask = np.zeros(max_seq_length, dtype=np.bool_) + + # encode(tokenize) each word from words (List[str]) + input_ids_list: List[List[int]] = [tokenizer.encode(e, add_special_tokens=False) for e in words] + + # get the length of each box + tokens_length_list: List[int] = [len(l) for l in input_ids_list] + + box_end_token_indices = np.array(list(itertools.accumulate(tokens_length_list))) + box_start_token_indices = box_end_token_indices - np.array(tokens_length_list) + + # filter out the indices that are out of max_seq_length + box_end_token_indices = box_end_token_indices[box_end_token_indices < max_seq_length - 1] + if len(box_start_token_indices) > len(box_end_token_indices): + box_start_token_indices = box_start_token_indices[: len(box_end_token_indices)] + + # set box_start_token_indices to True + box_first_token_mask[box_start_token_indices] = True + + return box_first_token_mask + +``` + +## Resources + +- Demo scripts can be found [here](https://github.com/clovaai/bros). + +## BrosConfig + +[[autodoc]] BrosConfig + +## BrosProcessor + +[[autodoc]] BrosProcessor + - __call__ + +## BrosModel + +[[autodoc]] BrosModel + - forward + + +## BrosForTokenClassification + +[[autodoc]] BrosForTokenClassification + - forward + +## BrosSpadeEEForTokenClassification + +[[autodoc]] BrosSpadeEEForTokenClassification + - forward + +## BrosSpadeELForTokenClassification + +[[autodoc]] BrosSpadeELForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/byt5.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/byt5.md new file mode 100644 index 0000000000000000000000000000000000000000..7e95bae53e87fdcebebd6c0f4e512c22a36fff41 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/byt5.md @@ -0,0 +1,162 @@ + + +# ByT5 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The ByT5 model was presented in [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir +Kale, Adam Roberts, Colin Raffel. + +The abstract from the paper is the following: + +*Most widely-used pre-trained language models operate on sequences of tokens corresponding to word or subword units. +Encoding text as a sequence of tokens requires a tokenizer, which is typically created as an independent artifact from +the model. Token-free models that instead operate directly on raw text (bytes or characters) have many benefits: they +can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by +removing complex and error-prone text preprocessing pipelines. Since byte or character sequences are longer than token +sequences, past work on token-free models has often introduced new model architectures designed to amortize the cost of +operating directly on raw text. In this paper, we show that a standard Transformer architecture can be used with +minimal modifications to process byte sequences. We carefully characterize the trade-offs in terms of parameter count, +training FLOPs, and inference speed, and show that byte-level models are competitive with their token-level +counterparts. We also demonstrate that byte-level models are significantly more robust to noise and perform better on +tasks that are sensitive to spelling and pronunciation. As part of our contribution, we release a new set of +pre-trained byte-level Transformer models based on the T5 architecture, as well as all code and data used in our +experiments.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The original code can be +found [here](https://github.com/google-research/byt5). + + + +ByT5's architecture is based on the T5v1.1 model, refer to [T5v1.1's documentation page](t5v1.1) for the API reference. They +only differ in how inputs should be prepared for the model, see the code examples below. + + + +Since ByT5 was pre-trained unsupervisedly, there's no real advantage to using a task prefix during single-task +fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix. + + +## Usage example + +ByT5 works on raw UTF-8 bytes, so it can be used without a tokenizer: + +```python +>>> from transformers import T5ForConditionalGeneration +>>> import torch + +>>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") + +>>> num_special_tokens = 3 +>>> # Model has 3 special tokens which take up the input ids 0,1,2 of ByT5. +>>> # => Need to shift utf-8 character encodings by 3 before passing ids to model. + +>>> input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens + +>>> labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens + +>>> loss = model(input_ids, labels=labels).loss +>>> loss.item() +2.66 +``` + +For batched inference and training it is however recommended to make use of the tokenizer: + +```python +>>> from transformers import T5ForConditionalGeneration, AutoTokenizer + +>>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") +>>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-small") + +>>> model_inputs = tokenizer( +... ["Life is like a box of chocolates.", "Today is Monday."], padding="longest", return_tensors="pt" +... ) +>>> labels_dict = tokenizer( +... ["La vie est comme une boîte de chocolat.", "Aujourd'hui c'est lundi."], padding="longest", return_tensors="pt" +... ) +>>> labels = labels_dict.input_ids + +>>> loss = model(**model_inputs, labels=labels).loss +>>> loss.item() +17.9 +``` + +Similar to [T5](t5), ByT5 was trained on the span-mask denoising task. However, +since the model works directly on characters, the pretraining task is a bit +different. Let's corrupt some characters of the +input sentence `"The dog chases a ball in the park."` and ask ByT5 to predict them +for us. + +```python +>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM +>>> import torch + +>>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-base") +>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-base") + +>>> input_ids_prompt = "The dog chases a ball in the park." +>>> input_ids = tokenizer(input_ids_prompt).input_ids + +>>> # Note that we cannot add "{extra_id_...}" to the string directly +>>> # as the Byte tokenizer would incorrectly merge the tokens +>>> # For ByT5, we need to work directly on the character level +>>> # Contrary to T5, ByT5 does not use sentinel tokens for masking, but instead +>>> # uses final utf character ids. +>>> # UTF-8 is represented by 8 bits and ByT5 has 3 special tokens. +>>> # => There are 2**8+2 = 259 input ids and mask tokens count down from index 258. +>>> # => mask to "The dog [258]a ball [257]park." + +>>> input_ids = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]]) +>>> input_ids +tensor([[ 87, 107, 104, 35, 103, 114, 106, 35, 258, 35, 100, 35, 101, 100, 111, 111, 257, 35, 115, 100, 117, 110, 49, 1]]) + +>>> # ByT5 produces only one char at a time so we need to produce many more output characters here -> set `max_length=100`. +>>> output_ids = model.generate(input_ids, max_length=100)[0].tolist() +>>> output_ids +[0, 258, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 257, 35, 108, 113, 35, 119, 107, 104, 35, 103, 108, 118, 102, 114, 256, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49, 35, 87, 107, 104, 35, 103, 114, 106, 35, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 35, 100, 35, 101, 100, 111, 111, 35, 108, 113, 255, 35, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49] + +>>> # ^- Note how 258 descends to 257, 256, 255 + +>>> # Now we need to split on the sentinel tokens, let's write a short loop for this +>>> output_ids_list = [] +>>> start_token = 0 +>>> sentinel_token = 258 +>>> while sentinel_token in output_ids: +... split_idx = output_ids.index(sentinel_token) +... output_ids_list.append(output_ids[start_token:split_idx]) +... start_token = split_idx +... sentinel_token -= 1 + +>>> output_ids_list.append(output_ids[start_token:]) +>>> output_string = tokenizer.batch_decode(output_ids_list) +>>> output_string +['', 'is the one who does', ' in the disco', 'in the park. The dog is the one who does a ball in', ' in the park.'] +``` + + +## ByT5Tokenizer + +[[autodoc]] ByT5Tokenizer + +See [`ByT5Tokenizer`] for all details. diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/camembert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/camembert.md new file mode 100644 index 0000000000000000000000000000000000000000..9066ee360c6c97301ec164a7c4985abe327390df --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/camembert.md @@ -0,0 +1,141 @@ + + +# CamemBERT + +
+PyTorch +TensorFlow +SDPA +
+ +## Overview + +The CamemBERT model was proposed in [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by +[Louis Martin](https://huggingface.co/louismartin), [Benjamin Muller](https://huggingface.co/benjamin-mlr), [Pedro Javier Ortiz Suárez](https://huggingface.co/pjox), Yoann Dupont, Laurent Romary, Éric Villemonte de la +Clergerie, [Djamé Seddah](https://huggingface.co/Djame), and [Benoît Sagot](https://huggingface.co/sagot). It is based on Facebook's RoBERTa model released in 2019. It is a model +trained on 138GB of French text. + +The abstract from the paper is the following: + +*Pretrained language models are now ubiquitous in Natural Language Processing. Despite their success, most available +models have either been trained on English data or on the concatenation of data in multiple languages. This makes +practical use of such models --in all languages except English-- very limited. Aiming to address this issue for French, +we release CamemBERT, a French version of the Bi-directional Encoders for Transformers (BERT). We measure the +performance of CamemBERT compared to multilingual models in multiple downstream tasks, namely part-of-speech tagging, +dependency parsing, named-entity recognition, and natural language inference. CamemBERT improves the state of the art +for most of the tasks considered. We release the pretrained model for CamemBERT hoping to foster research and +downstream applications for French NLP.* + +This model was contributed by [the ALMAnaCH team (Inria)](https://huggingface.co/almanach). The original code can be found [here](https://camembert-model.fr/). + + + +This implementation is the same as RoBERTa. Refer to the [documentation of RoBERTa](roberta) for usage examples as well +as the information relative to the inputs and outputs. + + + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## CamembertConfig + +[[autodoc]] CamembertConfig + +## CamembertTokenizer + +[[autodoc]] CamembertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CamembertTokenizerFast + +[[autodoc]] CamembertTokenizerFast + + + + +## CamembertModel + +[[autodoc]] CamembertModel + +## CamembertForCausalLM + +[[autodoc]] CamembertForCausalLM + +## CamembertForMaskedLM + +[[autodoc]] CamembertForMaskedLM + +## CamembertForSequenceClassification + +[[autodoc]] CamembertForSequenceClassification + +## CamembertForMultipleChoice + +[[autodoc]] CamembertForMultipleChoice + +## CamembertForTokenClassification + +[[autodoc]] CamembertForTokenClassification + +## CamembertForQuestionAnswering + +[[autodoc]] CamembertForQuestionAnswering + + + + +## TFCamembertModel + +[[autodoc]] TFCamembertModel + +## TFCamembertForCausalLM + +[[autodoc]] TFCamembertForCausalLM + +## TFCamembertForMaskedLM + +[[autodoc]] TFCamembertForMaskedLM + +## TFCamembertForSequenceClassification + +[[autodoc]] TFCamembertForSequenceClassification + +## TFCamembertForMultipleChoice + +[[autodoc]] TFCamembertForMultipleChoice + +## TFCamembertForTokenClassification + +[[autodoc]] TFCamembertForTokenClassification + +## TFCamembertForQuestionAnswering + +[[autodoc]] TFCamembertForQuestionAnswering + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/canine.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/canine.md new file mode 100644 index 0000000000000000000000000000000000000000..cd1cce34c79c3fac14b5cc977dcf51b65ce99540 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/canine.md @@ -0,0 +1,149 @@ + + +# CANINE + +
+PyTorch +
+ +## Overview + +The CANINE model was proposed in [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language +Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting. It's +among the first papers that trains a Transformer without using an explicit tokenization step (such as Byte Pair +Encoding (BPE), WordPiece or SentencePiece). Instead, the model is trained directly at a Unicode character-level. +Training at a character-level inevitably comes with a longer sequence length, which CANINE solves with an efficient +downsampling strategy, before applying a deep Transformer encoder. + +The abstract from the paper is the following: + +*Pipelined NLP systems have largely been superseded by end-to-end neural modeling, yet nearly all commonly-used models +still require an explicit tokenization step. While recent tokenization approaches based on data-derived subword +lexicons are less brittle than manually engineered tokenizers, these techniques are not equally suited to all +languages, and the use of any fixed vocabulary may limit a model's ability to adapt. In this paper, we present CANINE, +a neural encoder that operates directly on character sequences, without explicit tokenization or vocabulary, and a +pre-training strategy that operates either directly on characters or optionally uses subwords as a soft inductive bias. +To use its finer-grained input effectively and efficiently, CANINE combines downsampling, which reduces the input +sequence length, with a deep transformer stack, which encodes context. CANINE outperforms a comparable mBERT model by +2.8 F1 on TyDi QA, a challenging multilingual benchmark, despite having 28% fewer model parameters.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/google-research/language/tree/master/language/canine). + +## Usage tips + +- CANINE uses no less than 3 Transformer encoders internally: 2 "shallow" encoders (which only consist of a single + layer) and 1 "deep" encoder (which is a regular BERT encoder). First, a "shallow" encoder is used to contextualize + the character embeddings, using local attention. Next, after downsampling, a "deep" encoder is applied. Finally, + after upsampling, a "shallow" encoder is used to create the final character embeddings. Details regarding up- and + downsampling can be found in the paper. +- CANINE uses a max sequence length of 2048 characters by default. One can use [`CanineTokenizer`] + to prepare text for the model. +- Classification can be done by placing a linear layer on top of the final hidden state of the special [CLS] token + (which has a predefined Unicode code point). For token classification tasks however, the downsampled sequence of + tokens needs to be upsampled again to match the length of the original character sequence (which is 2048). The + details for this can be found in the paper. + +Model checkpoints: + + - [google/canine-c](https://huggingface.co/google/canine-c): Pre-trained with autoregressive character loss, + 12-layer, 768-hidden, 12-heads, 121M parameters (size ~500 MB). + - [google/canine-s](https://huggingface.co/google/canine-s): Pre-trained with subword loss, 12-layer, + 768-hidden, 12-heads, 121M parameters (size ~500 MB). + + +## Usage example + +CANINE works on raw characters, so it can be used **without a tokenizer**: + +```python +>>> from transformers import CanineModel +>>> import torch + +>>> model = CanineModel.from_pretrained("google/canine-c") # model pre-trained with autoregressive character loss + +>>> text = "hello world" +>>> # use Python's built-in ord() function to turn each character into its unicode code point id +>>> input_ids = torch.tensor([[ord(char) for char in text]]) + +>>> outputs = model(input_ids) # forward pass +>>> pooled_output = outputs.pooler_output +>>> sequence_output = outputs.last_hidden_state +``` + +For batched inference and training, it is however recommended to make use of the tokenizer (to pad/truncate all +sequences to the same length): + +```python +>>> from transformers import CanineTokenizer, CanineModel + +>>> model = CanineModel.from_pretrained("google/canine-c") +>>> tokenizer = CanineTokenizer.from_pretrained("google/canine-c") + +>>> inputs = ["Life is like a box of chocolates.", "You never know what you gonna get."] +>>> encoding = tokenizer(inputs, padding="longest", truncation=True, return_tensors="pt") + +>>> outputs = model(**encoding) # forward pass +>>> pooled_output = outputs.pooler_output +>>> sequence_output = outputs.last_hidden_state +``` + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Multiple choice task guide](../tasks/multiple_choice) + +## CanineConfig + +[[autodoc]] CanineConfig + +## CanineTokenizer + +[[autodoc]] CanineTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + +## CANINE specific outputs + +[[autodoc]] models.canine.modeling_canine.CanineModelOutputWithPooling + +## CanineModel + +[[autodoc]] CanineModel + - forward + +## CanineForSequenceClassification + +[[autodoc]] CanineForSequenceClassification + - forward + +## CanineForMultipleChoice + +[[autodoc]] CanineForMultipleChoice + - forward + +## CanineForTokenClassification + +[[autodoc]] CanineForTokenClassification + - forward + +## CanineForQuestionAnswering + +[[autodoc]] CanineForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chameleon.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chameleon.md new file mode 100644 index 0000000000000000000000000000000000000000..3810b3590a00650e58ae58f6a5ab0547e3606791 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chameleon.md @@ -0,0 +1,208 @@ + + +# Chameleon + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Chameleon model was proposed in [Chameleon: Mixed-Modal Early-Fusion Foundation Models +](https://arxiv.org/abs/2405.09818v1) by META AI Chameleon Team. Chameleon is a Vision-Language Model that use vector quantization to tokenize images which enables the model to generate multimodal output. The model takes images and texts as input, including an interleaved format, and generates textual response. Image generation module is not released yet. + + +The abstract from the paper is the following: + +*We present Chameleon, a family of early-fusion token-based mixed-modal models capable of understanding and generating images and text in any arbitrary sequence. We outline a stable training +approach from inception, an alignment recipe, and an architectural parameterization tailored for the +early-fusion, token-based, mixed-modal setting. The models are evaluated on a comprehensive range +of tasks, including visual question answering, image captioning, text generation, image generation, and +long-form mixed modal generation. Chameleon demonstrates broad and general capabilities, including +state-of-the-art performance in image captioning tasks, outperforms Llama-2 in text-only tasks while +being competitive with models such as Mixtral 8x7B and Gemini-Pro, and performs non-trivial image +generation, all in a single model. It also matches or exceeds the performance of much larger models, +including Gemini Pro and GPT-4V, according to human judgments on a new long-form mixed-modal +generation evaluation, where either the prompt or outputs contain mixed sequences of both images and +text. Chameleon marks a significant step forward in unified modeling of full multimodal documents* + + + + + Chameleon incorporates a vector quantizer module to transform images into discrete tokens. That also enables image generation using an auto-regressive transformer. Taken from the original paper. + +This model was contributed by [joaogante](https://huggingface.co/joaogante) and [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/facebookresearch/chameleon). + + +## Usage tips + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to set `processor.tokenizer.padding_side = "left"` before generating. + +- Note that Chameleon was tuned for safety alignment. If the model is refusing to answer, consider asking a more concrete question, instead of an open question. + +- Chameleon generates in chat format which means that the generated text will always be the "assistant's turn". You can enable a text completion generation by passing `return_for_text_completion=True` when calling the processor. + +> [!NOTE] +> Chameleon implementation in Transformers uses a special image token to indicate where to merge image embeddings. For special image token we didn't add a new one but used one of the reserved tokens: ``. You have to add `` to your prompt in the place where the image should be embedded for correct generation. + +## Usage example + +### Single image inference + +Chameleon is a gated model so make sure to have access and login to Hugging Face Hub using a token. +Here's how to load the model and perform inference in half-precision (`torch.bfloat16`): + +```python +from transformers import ChameleonProcessor, ChameleonForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b") +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_dtype=torch.bfloat16, device_map="cuda") + +# prepare image and text prompt +url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +image = Image.open(requests.get(url, stream=True).raw) +prompt = "What do you see in this image?" + +inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=50) +print(processor.decode(output[0], skip_special_tokens=True)) +``` + +### Multi image inference + +Chameleon can perform inference with multiple images as input, where images either belong to the same prompt or different prompts (in batched inference). Here is how you can do it: + +```python +from transformers import ChameleonProcessor, ChameleonForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b") + +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_dtype=torch.bfloat16, device_map="cuda") + +# Get three different images +url = "https://www.ilankelman.org/stopsigns/australia.jpg" +image_stop = Image.open(requests.get(url, stream=True).raw) + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image_cats = Image.open(requests.get(url, stream=True).raw) + +url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg" +image_snowman = Image.open(requests.get(url, stream=True).raw) + +# Prepare a batched prompt, where the first one is a multi-image prompt and the second is not +prompts = [ + "What do these images have in common?", + "What is shown in this image?" +] + +# We can simply feed images in the order they have to be used in the text prompt +# Each "" token uses one image leaving the next for the subsequent "" tokens +inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, padding=True, return_tensors="pt").to(device="cuda", dtype=torch.bfloat16) + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=50) +processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) +``` + +## Model optimization + +### Quantization using Bitsandbytes + +The model can be loaded in 8 or 4 bits, greatly reducing the memory requirements while maintaining the performance of the original model. First make sure to install bitsandbytes, `pip install bitsandbytes` and to have access to a GPU/accelerator that is supported by the library. + + + +bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend). + +We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links. + + + +Simply change the snippet above with: + +```python +from transformers import ChameleonForConditionalGeneration, BitsAndBytesConfig + +# specify how to quantize the model +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.bfloat16, +) + +model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", quantization_config=quantization_config, device_map="cuda") +``` + +### Use Flash-Attention 2 and SDPA to further speed-up generation + +The models supports both, Flash-Attention 2 and PyTorch's [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html) which can be enables for optimization. SDPA is the default options when you load the model, If you want to switch for Flash Attention 2, first make sure to install flash-attn. Refer to the [original repository](https://github.com/Dao-AILab/flash-attention) regarding that package installation. Simply change the snippet above with: + +```python +from transformers import ChameleonForConditionalGeneration + +model_id = "facebook/chameleon-7b" +model = ChameleonForConditionalGeneration.from_pretrained( + model_id, + torch_dtype=torch.bfloat16, + low_cpu_mem_usage=True, + attn_implementation="flash_attention_2" +).to(0) +``` + +## ChameleonConfig + +[[autodoc]] ChameleonConfig + +## ChameleonVQVAEConfig + +[[autodoc]] ChameleonVQVAEConfig + +## ChameleonProcessor + +[[autodoc]] ChameleonProcessor + +## ChameleonImageProcessor + +[[autodoc]] ChameleonImageProcessor + - preprocess + +## ChameleonVQVAE + +[[autodoc]] ChameleonVQVAE + - forward + +## ChameleonModel + +[[autodoc]] ChameleonModel + - forward + +## ChameleonForConditionalGeneration + +[[autodoc]] ChameleonForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chinese_clip.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chinese_clip.md new file mode 100644 index 0000000000000000000000000000000000000000..c73fee0422f0fe3fb4569891a400067eba788ea0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/chinese_clip.md @@ -0,0 +1,116 @@ + + +# Chinese-CLIP + +
+PyTorch +
+ +## Overview + +The Chinese-CLIP model was proposed in [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou. +Chinese-CLIP is an implementation of CLIP (Radford et al., 2021) on a large-scale dataset of Chinese image-text pairs. It is capable of performing cross-modal retrieval and also playing as a vision backbone for vision tasks like zero-shot image classification, open-domain object detection, etc. The original Chinese-CLIP code is released [at this link](https://github.com/OFA-Sys/Chinese-CLIP). + +The abstract from the paper is the following: + +*The tremendous success of CLIP (Radford et al., 2021) has promoted the research and application of contrastive learning for vision-language pretraining. In this work, we construct a large-scale dataset of image-text pairs in Chinese, where most data are retrieved from publicly available datasets, and we pretrain Chinese CLIP models on the new dataset. We develop 5 Chinese CLIP models of multiple sizes, spanning from 77 to 958 million parameters. Furthermore, we propose a two-stage pretraining method, where the model is first trained with the image encoder frozen and then trained with all parameters being optimized, to achieve enhanced model performance. Our comprehensive experiments demonstrate that Chinese CLIP can achieve the state-of-the-art performance on MUGE, Flickr30K-CN, and COCO-CN in the setups of zero-shot learning and finetuning, and it is able to achieve competitive performance in zero-shot image classification based on the evaluation on the ELEVATER benchmark (Li et al., 2022). Our codes, pretrained models, and demos have been released.* + +The Chinese-CLIP model was contributed by [OFA-Sys](https://huggingface.co/OFA-Sys). + +## Usage example + +The code snippet below shows how to compute image & text features and similarities: + +```python +>>> from PIL import Image +>>> import requests +>>> from transformers import ChineseCLIPProcessor, ChineseCLIPModel + +>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") +>>> processor = ChineseCLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") + +>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg" +>>> image = Image.open(requests.get(url, stream=True).raw) +>>> # Squirtle, Bulbasaur, Charmander, Pikachu in English +>>> texts = ["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"] + +>>> # compute image feature +>>> inputs = processor(images=image, return_tensors="pt") +>>> image_features = model.get_image_features(**inputs) +>>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True) # normalize + +>>> # compute text features +>>> inputs = processor(text=texts, padding=True, return_tensors="pt") +>>> text_features = model.get_text_features(**inputs) +>>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True) # normalize + +>>> # compute image-text similarity scores +>>> inputs = processor(text=texts, images=image, return_tensors="pt", padding=True) +>>> outputs = model(**inputs) +>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score +>>> probs = logits_per_image.softmax(dim=1) # probs: [[1.2686e-03, 5.4499e-02, 6.7968e-04, 9.4355e-01]] +``` + +Currently, following scales of pretrained Chinese-CLIP models are available on 🤗 Hub: + +- [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) +- [OFA-Sys/chinese-clip-vit-large-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14) +- [OFA-Sys/chinese-clip-vit-large-patch14-336px](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14-336px) +- [OFA-Sys/chinese-clip-vit-huge-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-huge-patch14) + +## ChineseCLIPConfig + +[[autodoc]] ChineseCLIPConfig + - from_text_vision_configs + +## ChineseCLIPTextConfig + +[[autodoc]] ChineseCLIPTextConfig + +## ChineseCLIPVisionConfig + +[[autodoc]] ChineseCLIPVisionConfig + +## ChineseCLIPImageProcessor + +[[autodoc]] ChineseCLIPImageProcessor + - preprocess + +## ChineseCLIPFeatureExtractor + +[[autodoc]] ChineseCLIPFeatureExtractor + +## ChineseCLIPProcessor + +[[autodoc]] ChineseCLIPProcessor + +## ChineseCLIPModel + +[[autodoc]] ChineseCLIPModel + - forward + - get_text_features + - get_image_features + +## ChineseCLIPTextModel + +[[autodoc]] ChineseCLIPTextModel + - forward + +## ChineseCLIPVisionModel + +[[autodoc]] ChineseCLIPVisionModel + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clap.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clap.md new file mode 100644 index 0000000000000000000000000000000000000000..e060662c01a9edd0acfa176f0fdb306f92b612c6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clap.md @@ -0,0 +1,83 @@ + + +# CLAP + +
+PyTorch +
+ +## Overview + +The CLAP model was proposed in [Large Scale Contrastive Language-Audio pretraining with +feature fusion and keyword-to-caption augmentation](https://arxiv.org/pdf/2211.06687.pdf) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov. + +CLAP (Contrastive Language-Audio Pretraining) is a neural network trained on a variety of (audio, text) pairs. It can be instructed in to predict the most relevant text snippet, given an audio, without directly optimizing for the task. The CLAP model uses a SWINTransformer to get audio features from a log-Mel spectrogram input, and a RoBERTa model to get text features. Both the text and audio features are then projected to a latent space with identical dimension. The dot product between the projected audio and text features is then used as a similar score. + +The abstract from the paper is the following: + +*Contrastive learning has shown remarkable success in the field of multimodal representation learning. In this paper, we propose a pipeline of contrastive language-audio pretraining to develop an audio representation by combining audio data with natural language descriptions. To accomplish this target, we first release LAION-Audio-630K, a large collection of 633,526 audio-text pairs from different data sources. Second, we construct a contrastive language-audio pretraining model by considering different audio encoders and text encoders. We incorporate the feature fusion mechanism and keyword-to-caption augmentation into the model design to further enable the model to process audio inputs of variable lengths and enhance the performance. Third, we perform comprehensive experiments to evaluate our model across three tasks: text-to-audio retrieval, zero-shot audio classification, and supervised audio classification. The results demonstrate that our model achieves superior performance in text-to-audio retrieval task. In audio classification tasks, the model achieves state-of-the-art performance in the zeroshot setting and is able to obtain performance comparable to models' results in the non-zero-shot setting. LAION-Audio-6* + +This model was contributed by [Younes Belkada](https://huggingface.co/ybelkada) and [Arthur Zucker](https://huggingface.co/ArthurZ) . +The original code can be found [here](https://github.com/LAION-AI/Clap). + +## ClapConfig + +[[autodoc]] ClapConfig + - from_text_audio_configs + +## ClapTextConfig + +[[autodoc]] ClapTextConfig + +## ClapAudioConfig + +[[autodoc]] ClapAudioConfig + +## ClapFeatureExtractor + +[[autodoc]] ClapFeatureExtractor + +## ClapProcessor + +[[autodoc]] ClapProcessor + +## ClapModel + +[[autodoc]] ClapModel + - forward + - get_text_features + - get_audio_features + +## ClapTextModel + +[[autodoc]] ClapTextModel + - forward + +## ClapTextModelWithProjection + +[[autodoc]] ClapTextModelWithProjection + - forward + +## ClapAudioModel + +[[autodoc]] ClapAudioModel + - forward + +## ClapAudioModelWithProjection + +[[autodoc]] ClapAudioModelWithProjection + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clip.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clip.md new file mode 100644 index 0000000000000000000000000000000000000000..2e1c5168ce710e6feec04eecb7b25b6596020329 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clip.md @@ -0,0 +1,357 @@ + + +# CLIP + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +## Overview + +The CLIP model was proposed in [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, +Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever. CLIP +(Contrastive Language-Image Pre-Training) is a neural network trained on a variety of (image, text) pairs. It can be +instructed in natural language to predict the most relevant text snippet, given an image, without directly optimizing +for the task, similarly to the zero-shot capabilities of GPT-2 and 3. + +The abstract from the paper is the following: + +*State-of-the-art computer vision systems are trained to predict a fixed set of predetermined object categories. This +restricted form of supervision limits their generality and usability since additional labeled data is needed to specify +any other visual concept. Learning directly from raw text about images is a promising alternative which leverages a +much broader source of supervision. We demonstrate that the simple pre-training task of predicting which caption goes +with which image is an efficient and scalable way to learn SOTA image representations from scratch on a dataset of 400 +million (image, text) pairs collected from the internet. After pre-training, natural language is used to reference +learned visual concepts (or describe new ones) enabling zero-shot transfer of the model to downstream tasks. We study +the performance of this approach by benchmarking on over 30 different existing computer vision datasets, spanning tasks +such as OCR, action recognition in videos, geo-localization, and many types of fine-grained object classification. The +model transfers non-trivially to most tasks and is often competitive with a fully supervised baseline without the need +for any dataset specific training. For instance, we match the accuracy of the original ResNet-50 on ImageNet zero-shot +without needing to use any of the 1.28 million training examples it was trained on. We release our code and pre-trained +model weights at this https URL.* + +This model was contributed by [valhalla](https://huggingface.co/valhalla). The original code can be found [here](https://github.com/openai/CLIP). + +## Usage tips and example + +CLIP is a multi-modal vision and language model. It can be used for image-text similarity and for zero-shot image +classification. CLIP uses a ViT like transformer to get visual features and a causal language model to get the text +features. Both the text and visual features are then projected to a latent space with identical dimension. The dot +product between the projected image and text features is then used as a similar score. + +To feed images to the Transformer encoder, each image is split into a sequence of fixed-size non-overlapping patches, +which are then linearly embedded. A [CLS] token is added to serve as representation of an entire image. The authors +also add absolute position embeddings, and feed the resulting sequence of vectors to a standard Transformer encoder. +The [`CLIPImageProcessor`] can be used to resize (or rescale) and normalize images for the model. + +The [`CLIPTokenizer`] is used to encode the text. The [`CLIPProcessor`] wraps +[`CLIPImageProcessor`] and [`CLIPTokenizer`] into a single instance to both +encode the text and prepare the images. The following example shows how to get the image-text similarity scores using +[`CLIPProcessor`] and [`CLIPModel`]. + + +```python +>>> from PIL import Image +>>> import requests + +>>> from transformers import CLIPProcessor, CLIPModel + +>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") +>>> processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) + +>>> outputs = model(**inputs) +>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score +>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities +``` + + +### Combining CLIP and Flash Attention 2 + +First, make sure to install the latest version of Flash Attention 2. + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of flash-attn repository. Make also sure to load your model in half-precision (e.g. `torch.float16`) + + + +For small batch sizes, you might notice a slowdown in your model when using flash attention. Refer to the section [Expected speedups with Flash Attention and SDPA](#Expected-speedups-with-Flash-Attention-and-SDPA) below and select an appropriate attention implementation. + + + +To load and run a model using Flash Attention 2, refer to the snippet below: + +```python +>>> import torch +>>> import requests +>>> from PIL import Image + +>>> from transformers import CLIPProcessor, CLIPModel + +>>> device = "cuda" +>>> torch_dtype = torch.float16 + +>>> model = CLIPModel.from_pretrained( +... "openai/clip-vit-base-patch32", +... attn_implementation="flash_attention_2", +... device_map=device, +... torch_dtype=torch_dtype, +... ) +>>> processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) +>>> inputs.to(device) + +>>> with torch.no_grad(): +... with torch.autocast(device): +... outputs = model(**inputs) + +>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score +>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities +>>> print(probs) +tensor([[0.9946, 0.0052]], device='cuda:0', dtype=torch.float16) +``` + + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +```python +from transformers import CLIPModel + +model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32", torch_dtype=torch.float16, attn_implementation="sdpa") +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +### Expected speedups with Flash Attention and SDPA + +On a local benchmark (NVIDIA A10G, PyTorch 2.3.1+cu121) with `float16`, we saw the following speedups during inference for `"openai/clip-vit-large-patch14"` checkpoint ([code](https://gist.github.com/qubvel/ac691a54e54f9fae8144275f866a7ff8)): + +#### CLIPTextModel + +| Num text labels | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | +|------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| +| 4 | 0.009 | 0.012 | 0.737 | 0.007 | 1.269 | +| 16 | 0.009 | 0.014 | 0.659 | 0.008 | 1.187 | +| 32 | 0.018 | 0.021 | 0.862 | 0.016 | 1.142 | +| 64 | 0.034 | 0.034 | 1.001 | 0.03 | 1.163 | +| 128 | 0.063 | 0.058 | 1.09 | 0.054 | 1.174 | + +![clip_text_model_viz_3](https://github.com/user-attachments/assets/e9826b43-4e66-4f4c-952b-af4d90bd38eb) + +#### CLIPVisionModel + +| Image batch size | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | +|-------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| +| 1 | 0.016 | 0.013 | 1.247 | 0.012 | 1.318 | +| 4 | 0.025 | 0.021 | 1.198 | 0.021 | 1.202 | +| 16 | 0.093 | 0.075 | 1.234 | 0.075 | 1.24 | +| 32 | 0.181 | 0.147 | 1.237 | 0.146 | 1.241 | + +![clip_image_model_viz_3](https://github.com/user-attachments/assets/50a36206-e3b9-4adc-ac8e-926b8b071d63) + +#### CLIPModel + +| Image batch size | Num text labels | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | +|-------------------:|------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| +| 1 | 4 | 0.025 | 0.026 | 0.954 | 0.02 | 1.217 | +| 1 | 16 | 0.026 | 0.028 | 0.918 | 0.02 | 1.287 | +| 1 | 64 | 0.042 | 0.046 | 0.906 | 0.036 | 1.167 | +| 4 | 4 | 0.028 | 0.033 | 0.849 | 0.024 | 1.189 | +| 4 | 16 | 0.034 | 0.035 | 0.955 | 0.029 | 1.169 | +| 4 | 64 | 0.059 | 0.055 | 1.072 | 0.05 | 1.179 | +| 16 | 4 | 0.096 | 0.088 | 1.091 | 0.078 | 1.234 | +| 16 | 16 | 0.102 | 0.09 | 1.129 | 0.083 | 1.224 | +| 16 | 64 | 0.127 | 0.11 | 1.157 | 0.105 | 1.218 | +| 32 | 4 | 0.185 | 0.159 | 1.157 | 0.149 | 1.238 | +| 32 | 16 | 0.19 | 0.162 | 1.177 | 0.154 | 1.233 | +| 32 | 64 | 0.216 | 0.181 | 1.19 | 0.176 | 1.228 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with CLIP. + +- [Fine tuning CLIP with Remote Sensing (Satellite) images and captions](https://huggingface.co/blog/fine-tune-clip-rsicd), a blog post about how to fine-tune CLIP with [RSICD dataset](https://github.com/201528014227051/RSICD_optimal) and comparison of performance changes due to data augmentation. +- This [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/contrastive-image-text) shows how to train a CLIP-like vision-text dual encoder model using a pre-trained vision and text encoder using [COCO dataset](https://cocodataset.org/#home). + + + +- A [notebook](https://colab.research.google.com/drive/1tuoAC5F4sC7qid56Z0ap-stR3rwdk0ZV?usp=sharing) on how to use a pretrained CLIP for inference with beam search for image captioning. 🌎 + +**Image retrieval** + +- A [notebook](https://colab.research.google.com/drive/1bLVwVKpAndpEDHqjzxVPr_9nGrSbuOQd?usp=sharing) on image retrieval using pretrained CLIP and computing MRR(Mean Reciprocal Rank) score. 🌎 +- A [notebook](https://colab.research.google.com/github/deep-diver/image_search_with_natural_language/blob/main/notebooks/Image_Search_CLIP.ipynb) on image retrieval and showing the similarity score. 🌎 +- A [notebook](https://colab.research.google.com/drive/1xO-wC_m_GNzgjIBQ4a4znvQkvDoZJvH4?usp=sharing) on how to map images and texts to the same vector space using Multilingual CLIP. 🌎 +- A [notebook](https://colab.research.google.com/github/vivien000/clip-demo/blob/master/clip.ipynb#scrollTo=uzdFhRGqiWkR) on how to run CLIP on semantic image search using [Unsplash](https://unsplash.com) and [TMDB](https://www.themoviedb.org/) datasets. 🌎 + +**Explainability** + +- A [notebook](https://colab.research.google.com/github/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP_explainability.ipynb) on how to visualize similarity between input token and image segment. 🌎 + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. +The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## CLIPConfig + +[[autodoc]] CLIPConfig + - from_text_vision_configs + +## CLIPTextConfig + +[[autodoc]] CLIPTextConfig + +## CLIPVisionConfig + +[[autodoc]] CLIPVisionConfig + +## CLIPTokenizer + +[[autodoc]] CLIPTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CLIPTokenizerFast + +[[autodoc]] CLIPTokenizerFast + +## CLIPImageProcessor + +[[autodoc]] CLIPImageProcessor + - preprocess + +## CLIPImageProcessorFast + +[[autodoc]] CLIPImageProcessorFast + - preprocess + +## CLIPFeatureExtractor + +[[autodoc]] CLIPFeatureExtractor + +## CLIPProcessor + +[[autodoc]] CLIPProcessor + + + + +## CLIPModel + +[[autodoc]] CLIPModel + - forward + - get_text_features + - get_image_features + +## CLIPTextModel + +[[autodoc]] CLIPTextModel + - forward + +## CLIPTextModelWithProjection + +[[autodoc]] CLIPTextModelWithProjection + - forward + +## CLIPVisionModelWithProjection + +[[autodoc]] CLIPVisionModelWithProjection + - forward + +## CLIPVisionModel + +[[autodoc]] CLIPVisionModel + - forward + +## CLIPForImageClassification + +[[autodoc]] CLIPForImageClassification + - forward + + + + +## TFCLIPModel + +[[autodoc]] TFCLIPModel + - call + - get_text_features + - get_image_features + +## TFCLIPTextModel + +[[autodoc]] TFCLIPTextModel + - call + +## TFCLIPVisionModel + +[[autodoc]] TFCLIPVisionModel + - call + + + + +## FlaxCLIPModel + +[[autodoc]] FlaxCLIPModel + - __call__ + - get_text_features + - get_image_features + +## FlaxCLIPTextModel + +[[autodoc]] FlaxCLIPTextModel + - __call__ + +## FlaxCLIPTextModelWithProjection + +[[autodoc]] FlaxCLIPTextModelWithProjection + - __call__ + +## FlaxCLIPVisionModel + +[[autodoc]] FlaxCLIPVisionModel + - __call__ + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clipseg.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clipseg.md new file mode 100644 index 0000000000000000000000000000000000000000..f594dbc3e0f3a238eaa701d286f7a8e0246ed86d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clipseg.md @@ -0,0 +1,108 @@ + + +# CLIPSeg + +
+PyTorch +
+ +## Overview + +The CLIPSeg model was proposed in [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo Lüddecke +and Alexander Ecker. CLIPSeg adds a minimal decoder on top of a frozen [CLIP](clip) model for zero-shot and one-shot image segmentation. + +The abstract from the paper is the following: + +*Image segmentation is usually addressed by training a +model for a fixed set of object classes. Incorporating additional classes or more complex queries later is expensive +as it requires re-training the model on a dataset that encompasses these expressions. Here we propose a system +that can generate image segmentations based on arbitrary +prompts at test time. A prompt can be either a text or an +image. This approach enables us to create a unified model +(trained once) for three common segmentation tasks, which +come with distinct challenges: referring expression segmentation, zero-shot segmentation and one-shot segmentation. +We build upon the CLIP model as a backbone which we extend with a transformer-based decoder that enables dense +prediction. After training on an extended version of the +PhraseCut dataset, our system generates a binary segmentation map for an image based on a free-text prompt or on +an additional image expressing the query. We analyze different variants of the latter image-based prompts in detail. +This novel hybrid input allows for dynamic adaptation not +only to the three segmentation tasks mentioned above, but +to any binary segmentation task where a text or image query +can be formulated. Finally, we find our system to adapt well +to generalized queries involving affordances or properties* + + + + CLIPSeg overview. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/timojl/clipseg). + +## Usage tips + +- [`CLIPSegForImageSegmentation`] adds a decoder on top of [`CLIPSegModel`]. The latter is identical to [`CLIPModel`]. +- [`CLIPSegForImageSegmentation`] can generate image segmentations based on arbitrary prompts at test time. A prompt can be either a text +(provided to the model as `input_ids`) or an image (provided to the model as `conditional_pixel_values`). One can also provide custom +conditional embeddings (provided to the model as `conditional_embeddings`). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with CLIPSeg. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A notebook that illustrates [zero-shot image segmentation with CLIPSeg](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/CLIPSeg/Zero_shot_image_segmentation_with_CLIPSeg.ipynb). + +## CLIPSegConfig + +[[autodoc]] CLIPSegConfig + - from_text_vision_configs + +## CLIPSegTextConfig + +[[autodoc]] CLIPSegTextConfig + +## CLIPSegVisionConfig + +[[autodoc]] CLIPSegVisionConfig + +## CLIPSegProcessor + +[[autodoc]] CLIPSegProcessor + +## CLIPSegModel + +[[autodoc]] CLIPSegModel + - forward + - get_text_features + - get_image_features + +## CLIPSegTextModel + +[[autodoc]] CLIPSegTextModel + - forward + +## CLIPSegVisionModel + +[[autodoc]] CLIPSegVisionModel + - forward + +## CLIPSegForImageSegmentation + +[[autodoc]] CLIPSegForImageSegmentation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clvp.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clvp.md new file mode 100644 index 0000000000000000000000000000000000000000..cfa4f97b828614ee817666d9324afc8f9b2ad1e6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/clvp.md @@ -0,0 +1,130 @@ + + +# CLVP + +
+PyTorch +
+ +## Overview + +The CLVP (Contrastive Language-Voice Pretrained Transformer) model was proposed in [Better speech synthesis through scaling](https://arxiv.org/abs/2305.07243) by James Betker. + +The abstract from the paper is the following: + +*In recent years, the field of image generation has been revolutionized by the application of autoregressive transformers and DDPMs. These approaches model the process of image generation as a step-wise probabilistic processes and leverage large amounts of compute and data to learn the image distribution. This methodology of improving performance need not be confined to images. This paper describes a way to apply advances in the image generative domain to speech synthesis. The result is TorToise - an expressive, multi-voice text-to-speech system.* + + +This model was contributed by [Susnato Dhar](https://huggingface.co/susnato). +The original code can be found [here](https://github.com/neonbjb/tortoise-tts). + + +## Usage tips + +1. CLVP is an integral part of the Tortoise TTS model. +2. CLVP can be used to compare different generated speech candidates with the provided text, and the best speech tokens are forwarded to the diffusion model. +3. The use of the [`ClvpModelForConditionalGeneration.generate()`] method is strongly recommended for tortoise usage. +4. Note that the CLVP model expects the audio to be sampled at 22.05 kHz contrary to other audio models which expects 16 kHz. + + +## Brief Explanation: + +- The [`ClvpTokenizer`] tokenizes the text input, and the [`ClvpFeatureExtractor`] extracts the log mel-spectrogram from the desired audio. +- [`ClvpConditioningEncoder`] takes those text tokens and audio representations and converts them into embeddings conditioned on the text and audio. +- The [`ClvpForCausalLM`] uses those embeddings to generate multiple speech candidates. +- Each speech candidate is passed through the speech encoder ([`ClvpEncoder`]) which converts them into a vector representation, and the text encoder ([`ClvpEncoder`]) converts the text tokens into the same latent space. +- At the end, we compare each speech vector with the text vector to see which speech vector is most similar to the text vector. +- [`ClvpModelForConditionalGeneration.generate()`] compresses all of the logic described above into a single method. + + +Example : + +```python +>>> import datasets +>>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration + +>>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library). +>>> text = "This is an example text." + +>>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +>>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050)) +>>> sample = ds[0]["audio"] + +>>> # Define processor and model. +>>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev") +>>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev") + +>>> # Generate processor output and model output. +>>> processor_output = processor(raw_speech=sample["array"], sampling_rate=sample["sampling_rate"], text=text, return_tensors="pt") +>>> generated_output = model.generate(**processor_output) +``` + + +## ClvpConfig + +[[autodoc]] ClvpConfig + - from_sub_model_configs + +## ClvpEncoderConfig + +[[autodoc]] ClvpEncoderConfig + +## ClvpDecoderConfig + +[[autodoc]] ClvpDecoderConfig + +## ClvpTokenizer + +[[autodoc]] ClvpTokenizer + - save_vocabulary + +## ClvpFeatureExtractor + +[[autodoc]] ClvpFeatureExtractor + - __call__ + +## ClvpProcessor + +[[autodoc]] ClvpProcessor + - __call__ + - decode + - batch_decode + +## ClvpModelForConditionalGeneration + +[[autodoc]] ClvpModelForConditionalGeneration + - forward + - generate + - get_text_features + - get_speech_features + +## ClvpForCausalLM + +[[autodoc]] ClvpForCausalLM + +## ClvpModel + +[[autodoc]] ClvpModel + +## ClvpEncoder + +[[autodoc]] ClvpEncoder + +## ClvpDecoder + +[[autodoc]] ClvpDecoder + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/code_llama.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/code_llama.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3e66769c9cc4aeb77603455197d668383a8b45 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/code_llama.md @@ -0,0 +1,135 @@ + + +# CodeLlama + +
+PyTorch +Flax +
+ +## Overview + +The Code Llama model was proposed in [Code Llama: Open Foundation Models for Code](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/) by Baptiste Rozière, Jonas Gehring, Fabian Gloeckle, Sten Sootla, Itai Gat, Xiaoqing Ellen Tan, Yossi Adi, Jingyu Liu, Tal Remez, Jérémy Rapin, Artyom Kozhevnikov, Ivan Evtimov, Joanna Bitton, Manish Bhatt, Cristian Canton Ferrer, Aaron Grattafiori, Wenhan Xiong, Alexandre Défossez, Jade Copet, Faisal Azhar, Hugo Touvron, Louis Martin, Nicolas Usunier, Thomas Scialom, Gabriel Synnaeve. + +The abstract from the paper is the following: + +*We release Code Llama, a family of large language models for code based on Llama 2 providing state-of-the-art performance among open models, infilling capabilities, support for large input contexts, and zero-shot instruction following ability for programming tasks. We provide multiple flavors to cover a wide range of applications: foundation models (Code Llama), Python specializations (Code Llama - Python), and instruction-following models (Code Llama - Instruct) with 7B, 13B and 34B parameters each. All models are trained on sequences of 16k tokens and show improvements on inputs with up to 100k tokens. 7B and 13B Code Llama and Code Llama - Instruct variants support infilling based on surrounding content. Code Llama reaches state-of-the-art performance among open models on several code benchmarks, with scores of up to 53% and 55% on HumanEval and MBPP, respectively. Notably, Code Llama - Python 7B outperforms Llama 2 70B on HumanEval and MBPP, and all our models outperform every other publicly available model on MultiPL-E. We release Code Llama under a permissive license that allows for both research and commercial use.* + +Check out all Code Llama model checkpoints [here](https://huggingface.co/models?search=code_llama) and the officially released ones in the [Meta Llama org](https://huggingface.co/meta-llama). + +This model was contributed by [ArthurZucker](https://huggingface.co/ArthurZ). The original code of the authors can be found [here](https://github.com/facebookresearch/llama). + +## Usage tips and examples + + + +The `Llama2` family models, on which Code Llama is based, were trained using `bfloat16`, but the original inference uses `float16`. Let's look at the different precisions: + +* `float32`: PyTorch convention on model initialization is to load models in `float32`, no matter with which `dtype` the model weights were stored. `transformers` also follows this convention for consistency with PyTorch. This will be picked by default. If you want the `AutoModel` API to load the checkpoints with the storage weights type, you must specify `torch_dtype="auto"`, e.g. `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`. +* `bfloat16`: Code Llama was trained with this precision, so we recommend using it for further training or fine-tuning. +* `float16`: We recommend running inference using this precision, as it's usually faster than `bfloat16`, and evaluation metrics show no discernible degradation with respect to `bfloat16`. You can also run inference using `bfloat16`, and we recommend you check inference results with both `float16` and `bfloat16` after fine-tuning. + +As mentioned above, the `dtype` of the storage weights is mostly irrelevant unless you are using `torch_dtype="auto"` when initializing a model using. The reason is that the model will first be downloaded (using the `dtype` of the checkpoints online) and then will be casted to the default `dtype` of `torch` (becomes `torch.float32`). If there is a specified `torch_dtype`, it will be used instead. + + + + +Tips: +- The infilling task is supported out of the box. You should be using the `tokenizer.fill_token` where you want your input to be filled. +- The model conversion script is the same as for the `Llama2` family: + +Here is a sample usage: + +```bash +python src/transformers/models/llama/convert_llama_weights_to_hf.py \ + --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path +``` + +Note that executing the script requires enough CPU RAM to host the whole model in float16 precision (even if the biggest versions +come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). + +After conversion, the model and tokenizer can be loaded via: + +```python +>>> from transformers import LlamaForCausalLM, CodeLlamaTokenizer + +>>> tokenizer = CodeLlamaTokenizer.from_pretrained("meta-llama/CodeLlama-7b-hf") +>>> model = LlamaForCausalLM.from_pretrained("meta-llama/CodeLlama-7b-hf") +>>> PROMPT = '''def remove_non_ascii(s: str) -> str: +... """ +... return result +... ''' +>>> input_ids = tokenizer(PROMPT, return_tensors="pt")["input_ids"] +>>> generated_ids = model.generate(input_ids, max_new_tokens=128) + +>>> filling = tokenizer.batch_decode(generated_ids[:, input_ids.shape[1]:], skip_special_tokens = True)[0] +>>> print(PROMPT.replace("", filling)) +def remove_non_ascii(s: str) -> str: + """ Remove non-ASCII characters from a string. + + Args: + s: The string to remove non-ASCII characters from. + + Returns: + The string with non-ASCII characters removed. + """ + result = "" + for c in s: + if ord(c) < 128: + result += c + return result + +``` + +If you only want the infilled part: +```python +>>> from transformers import pipeline +>>> import torch + +>>> generator = pipeline("text-generation",model="meta-llama/CodeLlama-7b-hf",torch_dtype=torch.float16, device_map="auto") +>>> generator('def remove_non_ascii(s: str) -> str:\n """ \n return result', max_new_tokens = 128) +[{'generated_text': 'def remove_non_ascii(s: str) -> str:\n """ \n return resultRemove non-ASCII characters from a string. """\n result = ""\n for c in s:\n if ord(c) < 128:\n result += c'}] +``` + +Under the hood, the tokenizer [automatically splits by ``](https://huggingface.co/docs/transformers/main/model_doc/code_llama#transformers.CodeLlamaTokenizer.fill_token) to create a formatted input string that follows [the original training pattern](https://github.com/facebookresearch/codellama/blob/cb51c14ec761370ba2e2bc351374a79265d0465e/llama/generation.py#L402). This is more robust than preparing the pattern yourself: it avoids pitfalls, such as token glueing, that are very hard to debug. To see how much CPU and GPU memory you need for this model or others, try [this calculator](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) which can help determine that value. + +The LLaMA tokenizer is a BPE model based on [sentencepiece](https://github.com/google/sentencepiece). One quirk of sentencepiece is that when decoding a sequence, if the first token is the start of the word (e.g. "Banana"), the tokenizer does not prepend the prefix space to the string. + + + +Code Llama has the same architecture as the `Llama2` models, refer to [Llama2's documentation page](llama2) for the API reference. +Find Code Llama tokenizer reference below. + + + +## CodeLlamaTokenizer + +[[autodoc]] CodeLlamaTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## CodeLlamaTokenizerFast + +[[autodoc]] CodeLlamaTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/codegen.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/codegen.md new file mode 100644 index 0000000000000000000000000000000000000000..465c8e5445b898dedc28dd900dd14b4b6c7459dd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/codegen.md @@ -0,0 +1,94 @@ + + +# CodeGen + +
+PyTorch +
+ +## Overview + +The CodeGen model was proposed in [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and Caiming Xiong. + +CodeGen is an autoregressive language model for program synthesis trained sequentially on [The Pile](https://pile.eleuther.ai/), BigQuery, and BigPython. + +The abstract from the paper is the following: + +*Program synthesis strives to generate a computer program as a solution to a given problem specification. We propose a conversational program synthesis approach via large language models, which addresses the challenges of searching over a vast program space and user intent specification faced in prior approaches. Our new approach casts the process of writing a specification and program as a multi-turn conversation between a user and a system. It treats program synthesis as a sequence prediction problem, in which the specification is expressed in natural language and the desired program is conditionally sampled. We train a family of large language models, called CodeGen, on natural language and programming language data. With weak supervision in the data and the scaling up of data size and model size, conversational capacities emerge from the simple autoregressive language modeling. To study the model behavior on conversational program synthesis, we develop a multi-turn programming benchmark (MTPB), where solving each problem requires multi-step synthesis via multi-turn conversation between the user and the model. Our findings show the emergence of conversational capabilities and the effectiveness of the proposed conversational program synthesis paradigm. In addition, our model CodeGen (with up to 16B parameters trained on TPU-v4) outperforms OpenAI's Codex on the HumanEval benchmark. We make the training library JaxFormer including checkpoints available as open source contribution: [this https URL](https://github.com/salesforce/codegen).* + +This model was contributed by [Hiroaki Hayashi](https://huggingface.co/rooa). +The original code can be found [here](https://github.com/salesforce/codegen). + +## Checkpoint Naming + +* CodeGen model [checkpoints](https://huggingface.co/models?other=codegen) are available on different pre-training data with variable sizes. +* The format is: `Salesforce/codegen-{size}-{data}`, where + * `size`: `350M`, `2B`, `6B`, `16B` + * `data`: + * `nl`: Pre-trained on the Pile + * `multi`: Initialized with `nl`, then further pre-trained on multiple programming languages data + * `mono`: Initialized with `multi`, then further pre-trained on Python data +* For example, `Salesforce/codegen-350M-mono` offers a 350 million-parameter checkpoint pre-trained sequentially on the Pile, multiple programming languages, and Python. + +## Usage example + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> checkpoint = "Salesforce/codegen-350M-mono" +>>> model = AutoModelForCausalLM.from_pretrained(checkpoint) +>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) + +>>> text = "def hello_world():" + +>>> completion = model.generate(**tokenizer(text, return_tensors="pt")) + +>>> print(tokenizer.decode(completion[0])) +def hello_world(): + print("Hello World") + +hello_world() +``` + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) + +## CodeGenConfig + +[[autodoc]] CodeGenConfig + - all + +## CodeGenTokenizer + +[[autodoc]] CodeGenTokenizer + - create_token_type_ids_from_sequences + - save_vocabulary + +## CodeGenTokenizerFast + +[[autodoc]] CodeGenTokenizerFast + +## CodeGenModel + +[[autodoc]] CodeGenModel + - forward + +## CodeGenForCausalLM + +[[autodoc]] CodeGenForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere.md new file mode 100644 index 0000000000000000000000000000000000000000..2ab75e9d1c8bf65ac3d8a5cc313251763542ce48 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere.md @@ -0,0 +1,147 @@ +# Cohere + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Cohere Command-R model was proposed in the blogpost [Command-R: Retrieval Augmented Generation at Production Scale](https://txt.cohere.com/command-r/) by the Cohere Team. + +The abstract from the paper is the following: + +*Command-R is a scalable generative model targeting RAG and Tool Use to enable production-scale AI for enterprise. Today, we are introducing Command-R, a new LLM aimed at large-scale production workloads. Command-R targets the emerging “scalable” category of models that balance high efficiency with strong accuracy, enabling companies to move beyond proof of concept, and into production.* + +*Command-R is a generative model optimized for long context tasks such as retrieval augmented generation (RAG) and using external APIs and tools. It is designed to work in concert with our industry-leading Embed and Rerank models to provide best-in-class integration for RAG applications and excel at enterprise use cases. As a model built for companies to implement at scale, Command-R boasts: +- Strong accuracy on RAG and Tool Use +- Low latency, and high throughput +- Longer 128k context and lower pricing +- Strong capabilities across 10 key languages +- Model weights available on HuggingFace for research and evaluation + +Checkout model checkpoints [here](https://huggingface.co/CohereForAI/c4ai-command-r-v01). +This model was contributed by [Saurabh Dash](https://huggingface.co/saurabhdash) and [Ahmet Üstün](https://huggingface.co/ahmetustun). The code of the implementation in Hugging Face is based on GPT-NeoX [here](https://github.com/EleutherAI/gpt-neox). + +## Usage tips + + + +The checkpoints uploaded on the Hub use `torch_dtype = 'float16'`, which will be +used by the `AutoModel` API to cast the checkpoints from `torch.float32` to `torch.float16`. + +The `dtype` of the online weights is mostly irrelevant unless you are using `torch_dtype="auto"` when initializing a model using `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`. The reason is that the model will first be downloaded ( using the `dtype` of the checkpoints online), then it will be casted to the default `dtype` of `torch` (becomes `torch.float32`), and finally, if there is a `torch_dtype` provided in the config, it will be used. + +Training the model in `float16` is not recommended and is known to produce `nan`; as such, the model should be trained in `bfloat16`. + + +The model and tokenizer can be loaded via: + +```python +# pip install transformers +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "CohereForAI/c4ai-command-r-v01" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id) + +# Format message with the command-r chat template +messages = [{"role": "user", "content": "Hello, how are you?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +## <|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|> + +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` + +- When using Flash Attention 2 via `attn_implementation="flash_attention_2"`, don't pass `torch_dtype` to the `from_pretrained` class method and use Automatic Mixed-Precision training. When using `Trainer`, it is simply specifying either `fp16` or `bf16` to `True`. Otherwise, make sure you are using `torch.autocast`. This is required because the Flash Attention only support `fp16` and `bf16` data type. + + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Command-R. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + + +Loading FP16 model +```python +# pip install transformers +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "CohereForAI/c4ai-command-r-v01" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id) + +# Format message with the command-r chat template +messages = [{"role": "user", "content": "Hello, how are you?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") +## <|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|> + +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` + +Loading bitsnbytes 4bit quantized model +```python +# pip install transformers bitsandbytes accelerate +from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig + +bnb_config = BitsAndBytesConfig(load_in_4bit=True) + +model_id = "CohereForAI/c4ai-command-r-v01" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config) + +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, + ) + +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` + + +## CohereConfig + +[[autodoc]] CohereConfig + +## CohereTokenizerFast + +[[autodoc]] CohereTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary + +## CohereModel + +[[autodoc]] CohereModel + - forward + + +## CohereForCausalLM + +[[autodoc]] CohereForCausalLM + - forward + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere2.md new file mode 100644 index 0000000000000000000000000000000000000000..3b0b6e1740a976d2bce8ce147043d5fe9aaaa5b7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cohere2.md @@ -0,0 +1,57 @@ +# Cohere + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview +[C4AI Command R7B](https://cohere.com/blog/command-r7b) is an open weights research release of a 7B billion parameter model developed by Cohere and Cohere For AI. It has advanced capabilities optimized for various use cases, including reasoning, summarization, question answering, and code. The model is trained to perform sophisticated tasks including Retrieval Augmented Generation (RAG) and tool use. The model also has powerful agentic capabilities that can use and combine multiple tools over multiple steps to accomplish more difficult tasks. It obtains top performance on enterprise-relevant code use cases. C4AI Command R7B is a multilingual model trained on 23 languages. + +The model features three layers with sliding window attention (window size 4096) and ROPE for efficient local context modeling and relative positional encoding. A fourth layer uses global attention without positional embeddings, enabling unrestricted token interactions across the entire sequence. + +The model has been trained on 23 languages: English, French, Spanish, Italian, German, Portuguese, Japanese, Korean, Arabic, Chinese, Russian, Polish, Turkish, Vietnamese, Dutch, Czech, Indonesian, Ukrainian, Romanian, Greek, Hindi, Hebrew, and Persian. + +## Usage tips +The model and tokenizer can be loaded via: + +```python +# pip install transformers +from transformers import AutoTokenizer, AutoModelForCausalLM + +model_id = "CohereForAI/c4ai-command-r7b-12-2024" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id) + +# Format message with the command-r chat template +messages = [{"role": "user", "content": "Hello, how are you?"}] +input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") + +gen_tokens = model.generate( + input_ids, + max_new_tokens=100, + do_sample=True, + temperature=0.3, +) + +gen_text = tokenizer.decode(gen_tokens[0]) +print(gen_text) +``` + +## Cohere2Config + +[[autodoc]] Cohere2Config + +## Cohere2Model + +[[autodoc]] Cohere2Model + - forward + + +## Cohere2ForCausalLM + +[[autodoc]] Cohere2ForCausalLM + - forward + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/colpali.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/colpali.md new file mode 100644 index 0000000000000000000000000000000000000000..07c4b45f140a2eac54b19ac503873291ecd5526c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/colpali.md @@ -0,0 +1,94 @@ + + +# ColPali + +
+PyTorch +
+ +## Overview + +The *ColPali* model was proposed in [ColPali: Efficient Document Retrieval with Vision Language Models](https://doi.org/10.48550/arXiv.2407.01449) by **Manuel Faysse***, **Hugues Sibille***, **Tony Wu***, Bilel Omrani, Gautier Viaud, Céline Hudelot, Pierre Colombo (* denotes equal contribution). Work lead by ILLUIN Technology. + +In our proposed *ColPali* approach, we leverage VLMs to construct efficient multi-vector embeddings directly from document images (“screenshots”) for document retrieval. We train the model to maximize the similarity between these document embeddings and the corresponding query embeddings, using the late interaction method introduced in ColBERT. + +Using *ColPali* removes the need for potentially complex and brittle layout recognition and OCR pipelines with a single model that can take into account both the textual and visual content (layout, charts, etc.) of a document. + +## Resources + +- The *ColPali* arXiv paper can be found [here](https://doi.org/10.48550/arXiv.2407.01449). 📄 +- The official blog post detailing ColPali can be found [here](https://huggingface.co/blog/manu/colpali). 📝 +- The original model implementation code for the ColPali model and for the `colpali-engine` package can be found [here](https://github.com/illuin-tech/colpali). 🌎 +- Cookbooks for learning to use the transformers-native version of *ColPali*, fine-tuning, and similarity maps generation can be found [here](https://github.com/tonywu71/colpali-cookbooks). 📚 + +This model was contributed by [@tonywu71](https://huggingface.co/tonywu71) and [@yonigozlan](https://huggingface.co/yonigozlan). + +## Usage + +This example demonstrates how to use *ColPali* to embed both queries and images, calculate their similarity scores, and identify the most relevant matches. For a specific query, you can retrieve the top-k most similar images by selecting the ones with the highest similarity scores. + +```python +import torch +from PIL import Image + +from transformers import ColPaliForRetrieval, ColPaliProcessor + +model_name = "vidore/colpali-v1.2-hf" + +model = ColPaliForRetrieval.from_pretrained( + model_name, + torch_dtype=torch.bfloat16, + device_map="cuda:0", # or "mps" if on Apple Silicon +).eval() + +processor = ColPaliProcessor.from_pretrained(model_name) + +# Your inputs (replace dummy images with screenshots of your documents) +images = [ + Image.new("RGB", (32, 32), color="white"), + Image.new("RGB", (16, 16), color="black"), +] +queries = [ + "What is the organizational structure for our R&D department?", + "Can you provide a breakdown of last year’s financial performance?", +] + +# Process the inputs +batch_images = processor(images=images).to(model.device) +batch_queries = processor(text=queries).to(model.device) + +# Forward pass +with torch.no_grad(): + image_embeddings = model(**batch_images).embeddings + query_embeddings = model(**batch_queries).embeddings + +# Score the queries against the images +scores = processor.score_retrieval(query_embeddings, image_embeddings) +``` + +## ColPaliConfig + +[[autodoc]] ColPaliConfig + +## ColPaliProcessor + +[[autodoc]] ColPaliProcessor + +## ColPaliForRetrieval + +[[autodoc]] ColPaliForRetrieval + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/conditional_detr.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/conditional_detr.md new file mode 100644 index 0000000000000000000000000000000000000000..6a03d14d969ca89268b7c8f6832653f93b5668c8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/conditional_detr.md @@ -0,0 +1,78 @@ + + +# Conditional DETR + +
+PyTorch +
+ +## Overview + +The Conditional DETR model was proposed in [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang. Conditional DETR presents a conditional cross-attention mechanism for fast DETR training. Conditional DETR converges 6.7× to 10× faster than DETR. + +The abstract from the paper is the following: + +*The recently-developed DETR approach applies the transformer encoder and decoder architecture to object detection and achieves promising performance. In this paper, we handle the critical issue, slow training convergence, and present a conditional cross-attention mechanism for fast DETR training. Our approach is motivated by that the cross-attention in DETR relies highly on the content embeddings for localizing the four extremities and predicting the box, which increases the need for high-quality content embeddings and thus the training difficulty. Our approach, named conditional DETR, learns a conditional spatial query from the decoder embedding for decoder multi-head cross-attention. The benefit is that through the conditional spatial query, each cross-attention head is able to attend to a band containing a distinct region, e.g., one object extremity or a region inside the object box. This narrows down the spatial range for localizing the distinct regions for object classification and box regression, thus relaxing the dependence on the content embeddings and easing the training. Empirical results show that conditional DETR converges 6.7× faster for the backbones R50 and R101 and 10× faster for stronger backbones DC5-R50 and DC5-R101. Code is available at https://github.com/Atten4Vis/ConditionalDETR.* + + + + Conditional DETR shows much faster convergence compared to the original DETR. Taken from the original paper. + +This model was contributed by [DepuMeng](https://huggingface.co/DepuMeng). The original code can be found [here](https://github.com/Atten4Vis/ConditionalDETR). + +## Resources + +- Scripts for finetuning [`ConditionalDetrForObjectDetection`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/object-detection). +- See also: [Object detection task guide](../tasks/object_detection). + +## ConditionalDetrConfig + +[[autodoc]] ConditionalDetrConfig + +## ConditionalDetrImageProcessor + +[[autodoc]] ConditionalDetrImageProcessor + - preprocess + - post_process_object_detection + - post_process_instance_segmentation + - post_process_semantic_segmentation + - post_process_panoptic_segmentation + +## ConditionalDetrFeatureExtractor + +[[autodoc]] ConditionalDetrFeatureExtractor + - __call__ + - post_process_object_detection + - post_process_instance_segmentation + - post_process_semantic_segmentation + - post_process_panoptic_segmentation + +## ConditionalDetrModel + +[[autodoc]] ConditionalDetrModel + - forward + +## ConditionalDetrForObjectDetection + +[[autodoc]] ConditionalDetrForObjectDetection + - forward + +## ConditionalDetrForSegmentation + +[[autodoc]] ConditionalDetrForSegmentation + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convbert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convbert.md new file mode 100644 index 0000000000000000000000000000000000000000..e52bbd5c4772ec62e2f06e0dece55abab09b801d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convbert.md @@ -0,0 +1,141 @@ + + +# ConvBERT + +
+PyTorch +TensorFlow +
+ +## Overview + +The ConvBERT model was proposed in [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng +Yan. + +The abstract from the paper is the following: + +*Pre-trained language models like BERT and its variants have recently achieved impressive performance in various +natural language understanding tasks. However, BERT heavily relies on the global self-attention block and thus suffers +large memory footprint and computation cost. Although all its attention heads query on the whole input sequence for +generating the attention map from a global perspective, we observe some heads only need to learn local dependencies, +which means the existence of computation redundancy. We therefore propose a novel span-based dynamic convolution to +replace these self-attention heads to directly model local dependencies. The novel convolution heads, together with the +rest self-attention heads, form a new mixed attention block that is more efficient at both global and local context +learning. We equip BERT with this mixed attention design and build a ConvBERT model. Experiments have shown that +ConvBERT significantly outperforms BERT and its variants in various downstream tasks, with lower training cost and +fewer model parameters. Remarkably, ConvBERTbase model achieves 86.4 GLUE score, 0.7 higher than ELECTRAbase, while +using less than 1/4 training cost. Code and pre-trained models will be released.* + +This model was contributed by [abhishek](https://huggingface.co/abhishek). The original implementation can be found +here: https://github.com/yitu-opensource/ConvBert + +## Usage tips + +ConvBERT training tips are similar to those of BERT. For usage tips refer to [BERT documentation](bert). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## ConvBertConfig + +[[autodoc]] ConvBertConfig + +## ConvBertTokenizer + +[[autodoc]] ConvBertTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## ConvBertTokenizerFast + +[[autodoc]] ConvBertTokenizerFast + + + + +## ConvBertModel + +[[autodoc]] ConvBertModel + - forward + +## ConvBertForMaskedLM + +[[autodoc]] ConvBertForMaskedLM + - forward + +## ConvBertForSequenceClassification + +[[autodoc]] ConvBertForSequenceClassification + - forward + +## ConvBertForMultipleChoice + +[[autodoc]] ConvBertForMultipleChoice + - forward + +## ConvBertForTokenClassification + +[[autodoc]] ConvBertForTokenClassification + - forward + +## ConvBertForQuestionAnswering + +[[autodoc]] ConvBertForQuestionAnswering + - forward + + + + +## TFConvBertModel + +[[autodoc]] TFConvBertModel + - call + +## TFConvBertForMaskedLM + +[[autodoc]] TFConvBertForMaskedLM + - call + +## TFConvBertForSequenceClassification + +[[autodoc]] TFConvBertForSequenceClassification + - call + +## TFConvBertForMultipleChoice + +[[autodoc]] TFConvBertForMultipleChoice + - call + +## TFConvBertForTokenClassification + +[[autodoc]] TFConvBertForTokenClassification + - call + +## TFConvBertForQuestionAnswering + +[[autodoc]] TFConvBertForQuestionAnswering + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnext.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnext.md new file mode 100644 index 0000000000000000000000000000000000000000..576e95ee043d11e46d5ba583459ff00c7702669d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnext.md @@ -0,0 +1,104 @@ + + +# ConvNeXT + +
+PyTorch +TensorFlow +
+ +## Overview + +The ConvNeXT model was proposed in [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie. +ConvNeXT is a pure convolutional model (ConvNet), inspired by the design of Vision Transformers, that claims to outperform them. + +The abstract from the paper is the following: + +*The "Roaring 20s" of visual recognition began with the introduction of Vision Transformers (ViTs), which quickly superseded ConvNets as the state-of-the-art image classification model. +A vanilla ViT, on the other hand, faces difficulties when applied to general computer vision tasks such as object detection and semantic segmentation. It is the hierarchical Transformers +(e.g., Swin Transformers) that reintroduced several ConvNet priors, making Transformers practically viable as a generic vision backbone and demonstrating remarkable performance on a wide +variety of vision tasks. However, the effectiveness of such hybrid approaches is still largely credited to the intrinsic superiority of Transformers, rather than the inherent inductive +biases of convolutions. In this work, we reexamine the design spaces and test the limits of what a pure ConvNet can achieve. We gradually "modernize" a standard ResNet toward the design +of a vision Transformer, and discover several key components that contribute to the performance difference along the way. The outcome of this exploration is a family of pure ConvNet models +dubbed ConvNeXt. Constructed entirely from standard ConvNet modules, ConvNeXts compete favorably with Transformers in terms of accuracy and scalability, achieving 87.8% ImageNet top-1 accuracy +and outperforming Swin Transformers on COCO detection and ADE20K segmentation, while maintaining the simplicity and efficiency of standard ConvNets.* + + + + ConvNeXT architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). TensorFlow version of the model was contributed by [ariG23498](https://github.com/ariG23498), +[gante](https://github.com/gante), and [sayakpaul](https://github.com/sayakpaul) (equal contribution). The original code can be found [here](https://github.com/facebookresearch/ConvNeXt). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ConvNeXT. + + + +- [`ConvNextForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## ConvNextConfig + +[[autodoc]] ConvNextConfig + +## ConvNextFeatureExtractor + +[[autodoc]] ConvNextFeatureExtractor + +## ConvNextImageProcessor + +[[autodoc]] ConvNextImageProcessor + - preprocess + +## ConvNextImageProcessorFast + +[[autodoc]] ConvNextImageProcessorFast + - preprocess + + + + +## ConvNextModel + +[[autodoc]] ConvNextModel + - forward + +## ConvNextForImageClassification + +[[autodoc]] ConvNextForImageClassification + - forward + + + + +## TFConvNextModel + +[[autodoc]] TFConvNextModel + - call + +## TFConvNextForImageClassification + +[[autodoc]] TFConvNextForImageClassification + - call + + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnextv2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnextv2.md new file mode 100644 index 0000000000000000000000000000000000000000..87a261b8dede7bc140fb010e19bd790e71ea6b92 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/convnextv2.md @@ -0,0 +1,73 @@ + + +# ConvNeXt V2 + +
+PyTorch +TensorFlow +
+ +## Overview + +The ConvNeXt V2 model was proposed in [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie. +ConvNeXt V2 is a pure convolutional model (ConvNet), inspired by the design of Vision Transformers, and a successor of [ConvNeXT](convnext). + +The abstract from the paper is the following: + +*Driven by improved architectures and better representation learning frameworks, the field of visual recognition has enjoyed rapid modernization and performance boost in the early 2020s. For example, modern ConvNets, represented by ConvNeXt, have demonstrated strong performance in various scenarios. While these models were originally designed for supervised learning with ImageNet labels, they can also potentially benefit from self-supervised learning techniques such as masked autoencoders (MAE). However, we found that simply combining these two approaches leads to subpar performance. In this paper, we propose a fully convolutional masked autoencoder framework and a new Global Response Normalization (GRN) layer that can be added to the ConvNeXt architecture to enhance inter-channel feature competition. This co-design of self-supervised learning techniques and architectural improvement results in a new model family called ConvNeXt V2, which significantly improves the performance of pure ConvNets on various recognition benchmarks, including ImageNet classification, COCO detection, and ADE20K segmentation. We also provide pre-trained ConvNeXt V2 models of various sizes, ranging from an efficient 3.7M-parameter Atto model with 76.7% top-1 accuracy on ImageNet, to a 650M Huge model that achieves a state-of-the-art 88.9% accuracy using only public training data.* + + + + ConvNeXt V2 architecture. Taken from the original paper. + +This model was contributed by [adirik](https://huggingface.co/adirik). The original code can be found [here](https://github.com/facebookresearch/ConvNeXt-V2). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ConvNeXt V2. + + + +- [`ConvNextV2ForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## ConvNextV2Config + +[[autodoc]] ConvNextV2Config + +## ConvNextV2Model + +[[autodoc]] ConvNextV2Model + - forward + +## ConvNextV2ForImageClassification + +[[autodoc]] ConvNextV2ForImageClassification + - forward + +## TFConvNextV2Model + +[[autodoc]] TFConvNextV2Model + - call + + +## TFConvNextV2ForImageClassification + +[[autodoc]] TFConvNextV2ForImageClassification + - call diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpm.md new file mode 100644 index 0000000000000000000000000000000000000000..8a1826a25c6d2bcc027036875907e8a1b69dc33b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpm.md @@ -0,0 +1,62 @@ + + +# CPM + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The CPM model was proposed in [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, +Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, +Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun. + +The abstract from the paper is the following: + +*Pre-trained Language Models (PLMs) have proven to be beneficial for various downstream NLP tasks. Recently, GPT-3, +with 175 billion parameters and 570GB training data, drew a lot of attention due to the capacity of few-shot (even +zero-shot) learning. However, applying GPT-3 to address Chinese NLP tasks is still challenging, as the training corpus +of GPT-3 is primarily English, and the parameters are not publicly available. In this technical report, we release the +Chinese Pre-trained Language Model (CPM) with generative pre-training on large-scale Chinese training data. To the best +of our knowledge, CPM, with 2.6 billion parameters and 100GB Chinese training data, is the largest Chinese pre-trained +language model, which could facilitate several downstream Chinese NLP tasks, such as conversation, essay generation, +cloze test, and language understanding. Extensive experiments demonstrate that CPM achieves strong performance on many +NLP tasks in the settings of few-shot (even zero-shot) learning.* + +This model was contributed by [canwenxu](https://huggingface.co/canwenxu). The original implementation can be found +here: https://github.com/TsinghuaAI/CPM-Generate + + + + +CPM's architecture is the same as GPT-2, except for tokenization method. Refer to [GPT-2 documentation](gpt2) for +API reference information. + + + + +## CpmTokenizer + +[[autodoc]] CpmTokenizer + +## CpmTokenizerFast + +[[autodoc]] CpmTokenizerFast diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpmant.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpmant.md new file mode 100644 index 0000000000000000000000000000000000000000..f8e2b3b515ece21689dafffb3ac3869ff659fb9c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cpmant.md @@ -0,0 +1,51 @@ + + +# CPMAnt + +
+PyTorch +
+ +## Overview + +CPM-Ant is an open-source Chinese pre-trained language model (PLM) with 10B parameters. It is also the first milestone of the live training process of CPM-Live. The training process is cost-effective and environment-friendly. CPM-Ant also achieves promising results with delta tuning on the CUGE benchmark. Besides the full model, we also provide various compressed versions to meet the requirements of different hardware configurations. [See more](https://github.com/OpenBMB/CPM-Live/tree/cpm-ant/cpm-live) + +This model was contributed by [OpenBMB](https://huggingface.co/openbmb). The original code can be found [here](https://github.com/OpenBMB/CPM-Live/tree/cpm-ant/cpm-live). + +## Resources + +- A tutorial on [CPM-Live](https://github.com/OpenBMB/CPM-Live/tree/cpm-ant/cpm-live). + +## CpmAntConfig + +[[autodoc]] CpmAntConfig + - all + +## CpmAntTokenizer + +[[autodoc]] CpmAntTokenizer + - all + +## CpmAntModel + +[[autodoc]] CpmAntModel + - all + +## CpmAntForCausalLM + +[[autodoc]] CpmAntForCausalLM + - all \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ctrl.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ctrl.md new file mode 100644 index 0000000000000000000000000000000000000000..0253d4e007e04421591181aab2b1a2f495ec53de --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ctrl.md @@ -0,0 +1,110 @@ + + +# CTRL + +
+PyTorch +TensorFlow +
+ +## Overview + +CTRL model was proposed in [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and +Richard Socher. It's a causal (unidirectional) transformer pre-trained using language modeling on a very large corpus +of ~140 GB of text data with the first token reserved as a control code (such as Links, Books, Wikipedia etc.). + +The abstract from the paper is the following: + +*Large-scale language models show promising text generation capabilities, but users cannot easily control particular +aspects of the generated text. We release CTRL, a 1.63 billion-parameter conditional transformer language model, +trained to condition on control codes that govern style, content, and task-specific behavior. Control codes were +derived from structure that naturally co-occurs with raw text, preserving the advantages of unsupervised learning while +providing more explicit control over text generation. These codes also allow CTRL to predict which parts of the +training data are most likely given a sequence. This provides a potential method for analyzing large amounts of data +via model-based source attribution.* + +This model was contributed by [keskarnitishr](https://huggingface.co/keskarnitishr). The original code can be found +[here](https://github.com/salesforce/ctrl). + +## Usage tips + +- CTRL makes use of control codes to generate text: it requires generations to be started by certain words, sentences + or links to generate coherent text. Refer to the [original implementation](https://github.com/salesforce/ctrl) for + more information. +- CTRL is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. +- CTRL was trained with a causal language modeling (CLM) objective and is therefore powerful at predicting the next + token in a sequence. Leveraging this feature allows CTRL to generate syntactically coherent text as it can be + observed in the *run_generation.py* example script. +- The PyTorch models can take the `past_key_values` as input, which is the previously computed key/value attention pairs. + TensorFlow models accepts `past` as input. Using the `past_key_values` value prevents the model from re-computing + pre-computed values in the context of text generation. See the [`forward`](model_doc/ctrl#transformers.CTRLModel.forward) + method for more information on the usage of this argument. + + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Causal language modeling task guide](../tasks/language_modeling) + +## CTRLConfig + +[[autodoc]] CTRLConfig + +## CTRLTokenizer + +[[autodoc]] CTRLTokenizer + - save_vocabulary + + + + +## CTRLModel + +[[autodoc]] CTRLModel + - forward + +## CTRLLMHeadModel + +[[autodoc]] CTRLLMHeadModel + - forward + +## CTRLForSequenceClassification + +[[autodoc]] CTRLForSequenceClassification + - forward + + + + +## TFCTRLModel + +[[autodoc]] TFCTRLModel + - call + +## TFCTRLLMHeadModel + +[[autodoc]] TFCTRLLMHeadModel + - call + +## TFCTRLForSequenceClassification + +[[autodoc]] TFCTRLForSequenceClassification + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cvt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cvt.md new file mode 100644 index 0000000000000000000000000000000000000000..fec632ed84d1091b360ddfe3196cb2ba484c7f93 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/cvt.md @@ -0,0 +1,92 @@ + + +# Convolutional Vision Transformer (CvT) + +
+PyTorch +TensorFlow +
+ +## Overview + +The CvT model was proposed in [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan and Lei Zhang. The Convolutional vision Transformer (CvT) improves the [Vision Transformer (ViT)](vit) in performance and efficiency by introducing convolutions into ViT to yield the best of both designs. + +The abstract from the paper is the following: + +*We present in this paper a new architecture, named Convolutional vision Transformer (CvT), that improves Vision Transformer (ViT) +in performance and efficiency by introducing convolutions into ViT to yield the best of both designs. This is accomplished through +two primary modifications: a hierarchy of Transformers containing a new convolutional token embedding, and a convolutional Transformer +block leveraging a convolutional projection. These changes introduce desirable properties of convolutional neural networks (CNNs) +to the ViT architecture (\ie shift, scale, and distortion invariance) while maintaining the merits of Transformers (\ie dynamic attention, +global context, and better generalization). We validate CvT by conducting extensive experiments, showing that this approach achieves +state-of-the-art performance over other Vision Transformers and ResNets on ImageNet-1k, with fewer parameters and lower FLOPs. In addition, +performance gains are maintained when pretrained on larger datasets (\eg ImageNet-22k) and fine-tuned to downstream tasks. Pre-trained on +ImageNet-22k, our CvT-W24 obtains a top-1 accuracy of 87.7\% on the ImageNet-1k val set. Finally, our results show that the positional encoding, +a crucial component in existing Vision Transformers, can be safely removed in our model, simplifying the design for higher resolution vision tasks.* + +This model was contributed by [anugunj](https://huggingface.co/anugunj). The original code can be found [here](https://github.com/microsoft/CvT). + +## Usage tips + +- CvT models are regular Vision Transformers, but trained with convolutions. They outperform the [original model (ViT)](vit) when fine-tuned on ImageNet-1K and CIFAR-100. +- You can check out demo notebooks regarding inference as well as fine-tuning on custom data [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer) (you can just replace [`ViTFeatureExtractor`] by [`AutoImageProcessor`] and [`ViTForImageClassification`] by [`CvtForImageClassification`]). +- The available checkpoints are either (1) pre-trained on [ImageNet-22k](http://www.image-net.org/) (a collection of 14 million images and 22k classes) only, (2) also fine-tuned on ImageNet-22k or (3) also fine-tuned on [ImageNet-1k](http://www.image-net.org/challenges/LSVRC/2012/) (also referred to as ILSVRC 2012, a collection of 1.3 million + images and 1,000 classes). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with CvT. + + + +- [`CvtForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## CvtConfig + +[[autodoc]] CvtConfig + + + + +## CvtModel + +[[autodoc]] CvtModel + - forward + +## CvtForImageClassification + +[[autodoc]] CvtForImageClassification + - forward + + + + +## TFCvtModel + +[[autodoc]] TFCvtModel + - call + +## TFCvtForImageClassification + +[[autodoc]] TFCvtForImageClassification + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dab-detr.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dab-detr.md new file mode 100644 index 0000000000000000000000000000000000000000..d19b45b486b0a1d432d58a10d228dca8c8cfa6d1 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dab-detr.md @@ -0,0 +1,123 @@ + + +# DAB-DETR + +
+PyTorch +
+ +## Overview + +The DAB-DETR model was proposed in [DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR](https://arxiv.org/abs/2201.12329) by Shilong Liu, Feng Li, Hao Zhang, Xiao Yang, Xianbiao Qi, Hang Su, Jun Zhu, Lei Zhang. +DAB-DETR is an enhanced variant of Conditional DETR. It utilizes dynamically updated anchor boxes to provide both a reference query point (x, y) and a reference anchor size (w, h), improving cross-attention computation. This new approach achieves 45.7% AP when trained for 50 epochs with a single ResNet-50 model as the backbone. + + + +The abstract from the paper is the following: + +*We present in this paper a novel query formulation using dynamic anchor boxes +for DETR (DEtection TRansformer) and offer a deeper understanding of the role +of queries in DETR. This new formulation directly uses box coordinates as queries +in Transformer decoders and dynamically updates them layer-by-layer. Using box +coordinates not only helps using explicit positional priors to improve the query-to-feature similarity and eliminate the slow training convergence issue in DETR, +but also allows us to modulate the positional attention map using the box width +and height information. Such a design makes it clear that queries in DETR can be +implemented as performing soft ROI pooling layer-by-layer in a cascade manner. +As a result, it leads to the best performance on MS-COCO benchmark among +the DETR-like detection models under the same setting, e.g., AP 45.7% using +ResNet50-DC5 as backbone trained in 50 epochs. We also conducted extensive +experiments to confirm our analysis and verify the effectiveness of our methods.* + +This model was contributed by [davidhajdu](https://huggingface.co/davidhajdu). +The original code can be found [here](https://github.com/IDEA-Research/DAB-DETR). + +## How to Get Started with the Model + +Use the code below to get started with the model. + +```python +import torch +import requests + +from PIL import Image +from transformers import AutoModelForObjectDetection, AutoImageProcessor + +url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +image = Image.open(requests.get(url, stream=True).raw) + +image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab-detr-resnet-50") +model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50") + +inputs = image_processor(images=image, return_tensors="pt") + +with torch.no_grad(): + outputs = model(**inputs) + +results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3) + +for result in results: + for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]): + score, label = score.item(), label_id.item() + box = [round(i, 2) for i in box.tolist()] + print(f"{model.config.id2label[label]}: {score:.2f} {box}") +``` +This should output +``` +cat: 0.87 [14.7, 49.39, 320.52, 469.28] +remote: 0.86 [41.08, 72.37, 173.39, 117.2] +cat: 0.86 [344.45, 19.43, 639.85, 367.86] +remote: 0.61 [334.27, 75.93, 367.92, 188.81] +couch: 0.59 [-0.04, 1.34, 639.9, 477.09] +``` + +There are three other ways to instantiate a DAB-DETR model (depending on what you prefer): + +Option 1: Instantiate DAB-DETR with pre-trained weights for entire model +```py +>>> from transformers import DabDetrForObjectDetection + +>>> model = DabDetrForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50") +``` + +Option 2: Instantiate DAB-DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone +```py +>>> from transformers import DabDetrConfig, DabDetrForObjectDetection + +>>> config = DabDetrConfig() +>>> model = DabDetrForObjectDetection(config) +``` +Option 3: Instantiate DAB-DETR with randomly initialized weights for backbone + Transformer +```py +>>> config = DabDetrConfig(use_pretrained_backbone=False) +>>> model = DabDetrForObjectDetection(config) +``` + + +## DabDetrConfig + +[[autodoc]] DabDetrConfig + +## DabDetrModel + +[[autodoc]] DabDetrModel + - forward + +## DabDetrForObjectDetection + +[[autodoc]] DabDetrForObjectDetection + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dac.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dac.md new file mode 100644 index 0000000000000000000000000000000000000000..3ee4d92b58e0277b868db701596adf1ea3c95023 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dac.md @@ -0,0 +1,84 @@ + + +# DAC + +
+PyTorch +
+ +## Overview + + +The DAC model was proposed in [Descript Audio Codec: High-Fidelity Audio Compression with Improved RVQGAN](https://arxiv.org/abs/2306.06546) by Rithesh Kumar, Prem Seetharaman, Alejandro Luebs, Ishaan Kumar, Kundan Kumar. + +The Descript Audio Codec (DAC) model is a powerful tool for compressing audio data, making it highly efficient for storage and transmission. By compressing 44.1 KHz audio into tokens at just 8kbps bandwidth, the DAC model enables high-quality audio processing while significantly reducing the data footprint. This is particularly useful in scenarios where bandwidth is limited or storage space is at a premium, such as in streaming applications, remote conferencing, and archiving large audio datasets. + +The abstract from the paper is the following: + +*Language models have been successfully used to model natural signals, such as images, speech, and music. A key component of these models is a high quality neural compression model that can compress high-dimensional natural signals into lower dimensional discrete tokens. To that end, we introduce a high-fidelity universal neural audio compression algorithm that achieves ~90x compression of 44.1 KHz audio into tokens at just 8kbps bandwidth. We achieve this by combining advances in high-fidelity audio generation with better vector quantization techniques from the image domain, along with improved adversarial and reconstruction losses. We compress all domains (speech, environment, music, etc.) with a single universal model, making it widely applicable to generative modeling of all audio. We compare with competing audio compression algorithms, and find our method outperforms them significantly. We provide thorough ablations for every design choice, as well as open-source code and trained model weights. We hope our work can lay the foundation for the next generation of high-fidelity audio modeling.* + +This model was contributed by [Kamil Akesbi](https://huggingface.co/kamilakesbi). +The original code can be found [here](https://github.com/descriptinc/descript-audio-codec/tree/main?tab=readme-ov-file). + + +## Model structure + +The Descript Audio Codec (DAC) model is structured into three distinct stages: + +1. Encoder Model: This stage compresses the input audio, reducing its size while retaining essential information. +2. Residual Vector Quantizer (RVQ) Model: Working in tandem with the encoder, this model quantizes the latent codes of the audio, refining the compression and ensuring high-quality reconstruction. +3. Decoder Model: This final stage reconstructs the audio from its compressed form, restoring it to a state that closely resembles the original input. + +## Usage example + +Here is a quick example of how to encode and decode an audio using this model: + +```python +>>> from datasets import load_dataset, Audio +>>> from transformers import DacModel, AutoProcessor +>>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +>>> model = DacModel.from_pretrained("descript/dac_16khz") +>>> processor = AutoProcessor.from_pretrained("descript/dac_16khz") +>>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=processor.sampling_rate)) +>>> audio_sample = librispeech_dummy[-1]["audio"]["array"] +>>> inputs = processor(raw_audio=audio_sample, sampling_rate=processor.sampling_rate, return_tensors="pt") + +>>> encoder_outputs = model.encode(inputs["input_values"]) +>>> # Get the intermediate audio codes +>>> audio_codes = encoder_outputs.audio_codes +>>> # Reconstruct the audio from its quantized representation +>>> audio_values = model.decode(encoder_outputs.quantized_representation) +>>> # or the equivalent with a forward pass +>>> audio_values = model(inputs["input_values"]).audio_values +``` + +## DacConfig + +[[autodoc]] DacConfig + +## DacFeatureExtractor + +[[autodoc]] DacFeatureExtractor + - __call__ + +## DacModel + +[[autodoc]] DacModel + - decode + - encode + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/data2vec.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/data2vec.md new file mode 100644 index 0000000000000000000000000000000000000000..62ddbd8ff184b63ec36df8c2a5c7df8df6ae66d6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/data2vec.md @@ -0,0 +1,233 @@ + + +# Data2Vec + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Data2Vec model was proposed in [data2vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/pdf/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu and Michael Auli. +Data2Vec proposes a unified framework for self-supervised learning across different data modalities - text, audio and images. +Importantly, predicted targets for pre-training are contextualized latent representations of the inputs, rather than modality-specific, context-independent targets. + +The abstract from the paper is the following: + +*While the general idea of self-supervised learning is identical across modalities, the actual algorithms and +objectives differ widely because they were developed with a single modality in mind. To get us closer to general +self-supervised learning, we present data2vec, a framework that uses the same learning method for either speech, +NLP or computer vision. The core idea is to predict latent representations of the full input data based on a +masked view of the input in a selfdistillation setup using a standard Transformer architecture. +Instead of predicting modality-specific targets such as words, visual tokens or units of human speech which +are local in nature, data2vec predicts contextualized latent representations that contain information from +the entire input. Experiments on the major benchmarks of speech recognition, image classification, and +natural language understanding demonstrate a new state of the art or competitive performance to predominant approaches. +Models and code are available at www.github.com/pytorch/fairseq/tree/master/examples/data2vec.* + +This model was contributed by [edugp](https://huggingface.co/edugp) and [patrickvonplaten](https://huggingface.co/patrickvonplaten). +[sayakpaul](https://github.com/sayakpaul) and [Rocketknight1](https://github.com/Rocketknight1) contributed Data2Vec for vision in TensorFlow. + +The original code (for NLP and Speech) can be found [here](https://github.com/pytorch/fairseq/tree/main/examples/data2vec). +The original code for vision can be found [here](https://github.com/facebookresearch/data2vec_vision/tree/main/beit). + +## Usage tips + +- Data2VecAudio, Data2VecText, and Data2VecVision have all been trained using the same self-supervised learning method. +- For Data2VecAudio, preprocessing is identical to [`Wav2Vec2Model`], including feature extraction +- For Data2VecText, preprocessing is identical to [`RobertaModel`], including tokenization. +- For Data2VecVision, preprocessing is identical to [`BeitModel`], including feature extraction. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +The SDPA implementation is currently available for the Data2VecAudio and Data2VecVision models. + +``` +from transformers import Data2VecVisionForImageClassification +model = Data2VecVisionForImageClassification.from_pretrained("facebook/data2vec-vision-base", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +For the Data2VecVision model, on a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.5.1, OS Ubuntu 20.04) +with `float16` and `facebook/data2vec-vision-base` model, we saw the following improvements during training and +inference: + +#### Training + +| num_training_steps | batch_size | image_size | is_cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | SDPA peak mem (MB) | Mem saving (%) | +|--------------------|------------|--------------|---------|----------------------------|---------------------------|-------------|----------------------|--------------------|----------------| +| 50 | 2 | (1048, 640) | True | 0.996 | 0.754 | 32.147 | 6722.198 | 4264.653 | 57.626 | + +#### Inference + +| Image batch size | Eager (s/iter) | Eager CI, % | Eager memory (MB) | SDPA (s/iter) | SDPA CI, % | SDPA memory (MB) | SDPA speedup | SDPA memory saved | +|-------------------:|-----------------:|:--------------|--------------------:|----------------:|:-------------|-------------------:|---------------:|--------------------:| +| 1 | 0.011 | ±0.3% | 3.76143e+08 | 0.01 | ±0.3% | 3.74397e+08 | 1.101 | 0.466 | +| 4 | 0.014 | ±0.1% | 4.02756e+08 | 0.012 | ±0.2% | 3.91373e+08 | 1.219 | 2.909 | +| 16 | 0.046 | ±0.3% | 4.96482e+08 | 0.035 | ±0.2% | 4.51017e+08 | 1.314 | 10.081 | +| 32 | 0.088 | ±0.1% | 6.23903e+08 | 0.067 | ±0.1% | 5.32974e+08 | 1.33 | 17.061 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Data2Vec. + + + +- [`Data2VecVisionForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- To fine-tune [`TFData2VecVisionForImageClassification`] on a custom dataset, see [this notebook](https://colab.research.google.com/github/sayakpaul/TF-2.0-Hacks/blob/master/data2vec_vision_image_classification.ipynb). + +**Data2VecText documentation resources** +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +**Data2VecAudio documentation resources** +- [Audio classification task guide](../tasks/audio_classification) +- [Automatic speech recognition task guide](../tasks/asr) + +**Data2VecVision documentation resources** +- [Image classification](../tasks/image_classification) +- [Semantic segmentation](../tasks/semantic_segmentation) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## Data2VecTextConfig + +[[autodoc]] Data2VecTextConfig + +## Data2VecAudioConfig + +[[autodoc]] Data2VecAudioConfig + +## Data2VecVisionConfig + +[[autodoc]] Data2VecVisionConfig + + + + +## Data2VecAudioModel + +[[autodoc]] Data2VecAudioModel + - forward + +## Data2VecAudioForAudioFrameClassification + +[[autodoc]] Data2VecAudioForAudioFrameClassification + - forward + +## Data2VecAudioForCTC + +[[autodoc]] Data2VecAudioForCTC + - forward + +## Data2VecAudioForSequenceClassification + +[[autodoc]] Data2VecAudioForSequenceClassification + - forward + +## Data2VecAudioForXVector + +[[autodoc]] Data2VecAudioForXVector + - forward + +## Data2VecTextModel + +[[autodoc]] Data2VecTextModel + - forward + +## Data2VecTextForCausalLM + +[[autodoc]] Data2VecTextForCausalLM + - forward + +## Data2VecTextForMaskedLM + +[[autodoc]] Data2VecTextForMaskedLM + - forward + +## Data2VecTextForSequenceClassification + +[[autodoc]] Data2VecTextForSequenceClassification + - forward + +## Data2VecTextForMultipleChoice + +[[autodoc]] Data2VecTextForMultipleChoice + - forward + +## Data2VecTextForTokenClassification + +[[autodoc]] Data2VecTextForTokenClassification + - forward + +## Data2VecTextForQuestionAnswering + +[[autodoc]] Data2VecTextForQuestionAnswering + - forward + +## Data2VecVisionModel + +[[autodoc]] Data2VecVisionModel + - forward + +## Data2VecVisionForImageClassification + +[[autodoc]] Data2VecVisionForImageClassification + - forward + +## Data2VecVisionForSemanticSegmentation + +[[autodoc]] Data2VecVisionForSemanticSegmentation + - forward + + + + +## TFData2VecVisionModel + +[[autodoc]] TFData2VecVisionModel + - call + +## TFData2VecVisionForImageClassification + +[[autodoc]] TFData2VecVisionForImageClassification + - call + +## TFData2VecVisionForSemanticSegmentation + +[[autodoc]] TFData2VecVisionForSemanticSegmentation + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dbrx.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dbrx.md new file mode 100644 index 0000000000000000000000000000000000000000..11463e93d16024411f9232fc57f69a9a95028814 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dbrx.md @@ -0,0 +1,125 @@ + + +# DBRX + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +DBRX is a [transformer-based](https://www.isattentionallyouneed.com/) decoder-only large language model (LLM) that was trained using next-token prediction. +It uses a *fine-grained* mixture-of-experts (MoE) architecture with 132B total parameters of which 36B parameters are active on any input. +It was pre-trained on 12T tokens of text and code data. +Compared to other open MoE models like Mixtral-8x7B and Grok-1, DBRX is fine-grained, meaning it uses a larger number of smaller experts. DBRX has 16 experts and chooses 4, while Mixtral-8x7B and Grok-1 have 8 experts and choose 2. +This provides 65x more possible combinations of experts and we found that this improves model quality. +DBRX uses rotary position encodings (RoPE), gated linear units (GLU), and grouped query attention (GQA). +It is a BPE based model and uses the GPT-4 tokenizer as described in the [tiktoken](https://github.com/openai/tiktoken) repository. +We made these choices based on exhaustive evaluation and scaling experiments. + +DBRX was pretrained on 12T tokens of carefully curated data and a maximum context length of 32K tokens. +We estimate that this data is at least 2x better token-for-token than the data we used to pretrain the MPT family of models. +This new dataset was developed using the full suite of Databricks tools, including Apache Spark™ and Databricks notebooks for data processing, and Unity Catalog for data management and governance. +We used curriculum learning for pretraining, changing the data mix during training in ways we found to substantially improve model quality. + + +More detailed information about DBRX Instruct and DBRX Base can be found in our [technical blog post](https://www.databricks.com/blog/introducing-dbrx-new-state-art-open-llm). + +This model was contributed by [eitan-turok](https://huggingface.co/eitanturok) and [abhi-db](https://huggingface.co/abhi-db). The original code can be found [here](https://github.com/databricks/dbrx-instruct), though this may not be up to date. + +## Usage Examples + +The `generate()` method can be used to generate text using DBRX. You can generate using the standard attention implementation, flash-attention, and the PyTorch scaled dot product attention. The last two attention implementations give speed ups. + +```python +from transformers import DbrxForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx-instruct", token="YOUR_HF_TOKEN") +model = DbrxForCausalLM.from_pretrained( + "databricks/dbrx-instruct", + device_map="auto", + torch_dtype=torch.bfloat16, + token="YOUR_HF_TOKEN", + ) + +input_text = "What does it take to build a great LLM?" +messages = [{"role": "user", "content": input_text}] +input_ids = tokenizer.apply_chat_template(messages, return_dict=True, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda") + +outputs = model.generate(**input_ids, max_new_tokens=200) +print(tokenizer.decode(outputs[0])) +``` + +If you have flash-attention installed (`pip install flash-attn`), it is possible to generate faster. (The HuggingFace documentation for flash-attention can be found [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one#flashattention-2).) +```python +from transformers import DbrxForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx-instruct", token="YOUR_HF_TOKEN") +model = DbrxForCausalLM.from_pretrained( + "databricks/dbrx-instruct", + device_map="auto", + torch_dtype=torch.bfloat16, + token="YOUR_HF_TOKEN", + attn_implementation="flash_attention_2", + ) + +input_text = "What does it take to build a great LLM?" +messages = [{"role": "user", "content": input_text}] +input_ids = tokenizer.apply_chat_template(messages, return_dict=True, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda") + +outputs = model.generate(**input_ids, max_new_tokens=200) +print(tokenizer.decode(outputs[0])) +``` + +You can also generate faster using the PyTorch scaled dot product attention. (The HuggingFace documentation for scaled dot product attention can be found [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one#pytorch-scaled-dot-product-attention).) +```python +from transformers import DbrxForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx-instruct", token="YOUR_HF_TOKEN") +model = DbrxForCausalLM.from_pretrained( + "databricks/dbrx-instruct", + device_map="auto", + torch_dtype=torch.bfloat16, + token="YOUR_HF_TOKEN", + attn_implementation="sdpa", + ) + +input_text = "What does it take to build a great LLM?" +messages = [{"role": "user", "content": input_text}] +input_ids = tokenizer.apply_chat_template(messages, return_dict=True, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda") + +outputs = model.generate(**input_ids, max_new_tokens=200) +print(tokenizer.decode(outputs[0])) +``` + +## DbrxConfig + +[[autodoc]] DbrxConfig + + +## DbrxModel + +[[autodoc]] DbrxModel + - forward + + +## DbrxForCausalLM + +[[autodoc]] DbrxForCausalLM + - forward + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta-v2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..2e48a3e9a7fca3b9fa004250be2bc8233c5e9b37 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta-v2.md @@ -0,0 +1,173 @@ + + +# DeBERTa-v2 + +
+PyTorch +TensorFlow +
+ +## Overview + +The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen It is based on Google's +BERT model released in 2018 and Facebook's RoBERTa model released in 2019. + +It builds on RoBERTa with disentangled attention and enhanced mask decoder training with half of the data used in +RoBERTa. + +The abstract from the paper is the following: + +*Recent progress in pre-trained neural language models has significantly improved the performance of many natural +language processing (NLP) tasks. In this paper we propose a new model architecture DeBERTa (Decoding-enhanced BERT with +disentangled attention) that improves the BERT and RoBERTa models using two novel techniques. The first is the +disentangled attention mechanism, where each word is represented using two vectors that encode its content and +position, respectively, and the attention weights among words are computed using disentangled matrices on their +contents and relative positions. Second, an enhanced mask decoder is used to replace the output softmax layer to +predict the masked tokens for model pretraining. We show that these two techniques significantly improve the efficiency +of model pretraining and performance of downstream tasks. Compared to RoBERTa-Large, a DeBERTa model trained on half of +the training data performs consistently better on a wide range of NLP tasks, achieving improvements on MNLI by +0.9% +(90.2% vs. 91.1%), on SQuAD v2.0 by +2.3% (88.4% vs. 90.7%) and RACE by +3.6% (83.2% vs. 86.8%). The DeBERTa code and +pre-trained models will be made publicly available at https://github.com/microsoft/DeBERTa.* + + +The following information is visible directly on the [original implementation +repository](https://github.com/microsoft/DeBERTa). DeBERTa v2 is the second version of the DeBERTa model. It includes +the 1.5B model used for the SuperGLUE single-model submission and achieving 89.9, versus human baseline 89.8. You can +find more details about this submission in the authors' +[blog](https://www.microsoft.com/en-us/research/blog/microsoft-deberta-surpasses-human-performance-on-the-superglue-benchmark/) + +New in v2: + +- **Vocabulary** In v2 the tokenizer is changed to use a new vocabulary of size 128K built from the training data. + Instead of a GPT2-based tokenizer, the tokenizer is now + [sentencepiece-based](https://github.com/google/sentencepiece) tokenizer. +- **nGiE(nGram Induced Input Encoding)** The DeBERTa-v2 model uses an additional convolution layer aside with the first + transformer layer to better learn the local dependency of input tokens. +- **Sharing position projection matrix with content projection matrix in attention layer** Based on previous + experiments, this can save parameters without affecting the performance. +- **Apply bucket to encode relative positions** The DeBERTa-v2 model uses log bucket to encode relative positions + similar to T5. +- **900M model & 1.5B model** Two additional model sizes are available: 900M and 1.5B, which significantly improves the + performance of downstream tasks. + +This model was contributed by [DeBERTa](https://huggingface.co/DeBERTa). This model TF 2.0 implementation was +contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/microsoft/DeBERTa). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## DebertaV2Config + +[[autodoc]] DebertaV2Config + +## DebertaV2Tokenizer + +[[autodoc]] DebertaV2Tokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## DebertaV2TokenizerFast + +[[autodoc]] DebertaV2TokenizerFast + - build_inputs_with_special_tokens + - create_token_type_ids_from_sequences + + + + +## DebertaV2Model + +[[autodoc]] DebertaV2Model + - forward + +## DebertaV2PreTrainedModel + +[[autodoc]] DebertaV2PreTrainedModel + - forward + +## DebertaV2ForMaskedLM + +[[autodoc]] DebertaV2ForMaskedLM + - forward + +## DebertaV2ForSequenceClassification + +[[autodoc]] DebertaV2ForSequenceClassification + - forward + +## DebertaV2ForTokenClassification + +[[autodoc]] DebertaV2ForTokenClassification + - forward + +## DebertaV2ForQuestionAnswering + +[[autodoc]] DebertaV2ForQuestionAnswering + - forward + +## DebertaV2ForMultipleChoice + +[[autodoc]] DebertaV2ForMultipleChoice + - forward + + + + +## TFDebertaV2Model + +[[autodoc]] TFDebertaV2Model + - call + +## TFDebertaV2PreTrainedModel + +[[autodoc]] TFDebertaV2PreTrainedModel + - call + +## TFDebertaV2ForMaskedLM + +[[autodoc]] TFDebertaV2ForMaskedLM + - call + +## TFDebertaV2ForSequenceClassification + +[[autodoc]] TFDebertaV2ForSequenceClassification + - call + +## TFDebertaV2ForTokenClassification + +[[autodoc]] TFDebertaV2ForTokenClassification + - call + +## TFDebertaV2ForQuestionAnswering + +[[autodoc]] TFDebertaV2ForQuestionAnswering + - call + +## TFDebertaV2ForMultipleChoice + +[[autodoc]] TFDebertaV2ForMultipleChoice + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta.md new file mode 100644 index 0000000000000000000000000000000000000000..39afe83f5fe3f1794b8f3fc0067c154dae08ec94 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deberta.md @@ -0,0 +1,169 @@ + + +# DeBERTa + +
+PyTorch +TensorFlow +
+ +## Overview + +The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen It is based on Google's +BERT model released in 2018 and Facebook's RoBERTa model released in 2019. + +It builds on RoBERTa with disentangled attention and enhanced mask decoder training with half of the data used in +RoBERTa. + +The abstract from the paper is the following: + +*Recent progress in pre-trained neural language models has significantly improved the performance of many natural +language processing (NLP) tasks. In this paper we propose a new model architecture DeBERTa (Decoding-enhanced BERT with +disentangled attention) that improves the BERT and RoBERTa models using two novel techniques. The first is the +disentangled attention mechanism, where each word is represented using two vectors that encode its content and +position, respectively, and the attention weights among words are computed using disentangled matrices on their +contents and relative positions. Second, an enhanced mask decoder is used to replace the output softmax layer to +predict the masked tokens for model pretraining. We show that these two techniques significantly improve the efficiency +of model pretraining and performance of downstream tasks. Compared to RoBERTa-Large, a DeBERTa model trained on half of +the training data performs consistently better on a wide range of NLP tasks, achieving improvements on MNLI by +0.9% +(90.2% vs. 91.1%), on SQuAD v2.0 by +2.3% (88.4% vs. 90.7%) and RACE by +3.6% (83.2% vs. 86.8%). The DeBERTa code and +pre-trained models will be made publicly available at https://github.com/microsoft/DeBERTa.* + + +This model was contributed by [DeBERTa](https://huggingface.co/DeBERTa). This model TF 2.0 implementation was +contributed by [kamalkraj](https://huggingface.co/kamalkraj) . The original code can be found [here](https://github.com/microsoft/DeBERTa). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DeBERTa. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A blog post on how to [Accelerate Large Model Training using DeepSpeed](https://huggingface.co/blog/accelerate-deepspeed) with DeBERTa. +- A blog post on [Supercharged Customer Service with Machine Learning](https://huggingface.co/blog/supercharge-customer-service-with-machine-learning) with DeBERTa. +- [`DebertaForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb). +- [`TFDebertaForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). +- [Text classification task guide](../tasks/sequence_classification) + + + +- [`DebertaForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb). +- [`TFDebertaForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). +- [Token classification](https://huggingface.co/course/chapter7/2?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Byte-Pair Encoding tokenization](https://huggingface.co/course/chapter6/5?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Token classification task guide](../tasks/token_classification) + + + +- [`DebertaForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFDebertaForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Masked language modeling task guide](../tasks/masked_language_modeling) + + + +- [`DebertaForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb). +- [`TFDebertaForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). +- [Question answering](https://huggingface.co/course/chapter7/7?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Question answering task guide](../tasks/question_answering) + +## DebertaConfig + +[[autodoc]] DebertaConfig + +## DebertaTokenizer + +[[autodoc]] DebertaTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## DebertaTokenizerFast + +[[autodoc]] DebertaTokenizerFast + - build_inputs_with_special_tokens + - create_token_type_ids_from_sequences + + + + +## DebertaModel + +[[autodoc]] DebertaModel + - forward + +## DebertaPreTrainedModel + +[[autodoc]] DebertaPreTrainedModel + +## DebertaForMaskedLM + +[[autodoc]] DebertaForMaskedLM + - forward + +## DebertaForSequenceClassification + +[[autodoc]] DebertaForSequenceClassification + - forward + +## DebertaForTokenClassification + +[[autodoc]] DebertaForTokenClassification + - forward + +## DebertaForQuestionAnswering + +[[autodoc]] DebertaForQuestionAnswering + - forward + + + + +## TFDebertaModel + +[[autodoc]] TFDebertaModel + - call + +## TFDebertaPreTrainedModel + +[[autodoc]] TFDebertaPreTrainedModel + - call + +## TFDebertaForMaskedLM + +[[autodoc]] TFDebertaForMaskedLM + - call + +## TFDebertaForSequenceClassification + +[[autodoc]] TFDebertaForSequenceClassification + - call + +## TFDebertaForTokenClassification + +[[autodoc]] TFDebertaForTokenClassification + - call + +## TFDebertaForQuestionAnswering + +[[autodoc]] TFDebertaForQuestionAnswering + - call + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/decision_transformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/decision_transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..fb932ce3ec7a6aceee46673ef80f90cdabf4e991 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/decision_transformer.md @@ -0,0 +1,57 @@ + + +# Decision Transformer + +
+PyTorch +
+ +## Overview + +The Decision Transformer model was proposed in [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) +by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch. + +The abstract from the paper is the following: + +*We introduce a framework that abstracts Reinforcement Learning (RL) as a sequence modeling problem. +This allows us to draw upon the simplicity and scalability of the Transformer architecture, and associated advances + in language modeling such as GPT-x and BERT. In particular, we present Decision Transformer, an architecture that + casts the problem of RL as conditional sequence modeling. Unlike prior approaches to RL that fit value functions or + compute policy gradients, Decision Transformer simply outputs the optimal actions by leveraging a causally masked + Transformer. By conditioning an autoregressive model on the desired return (reward), past states, and actions, our + Decision Transformer model can generate future actions that achieve the desired return. Despite its simplicity, + Decision Transformer matches or exceeds the performance of state-of-the-art model-free offline RL baselines on + Atari, OpenAI Gym, and Key-to-Door tasks.* + +This version of the model is for tasks where the state is a vector. + +This model was contributed by [edbeeching](https://huggingface.co/edbeeching). The original code can be found [here](https://github.com/kzl/decision-transformer). + +## DecisionTransformerConfig + +[[autodoc]] DecisionTransformerConfig + + +## DecisionTransformerGPT2Model + +[[autodoc]] DecisionTransformerGPT2Model + - forward + +## DecisionTransformerModel + +[[autodoc]] DecisionTransformerModel + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deformable_detr.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deformable_detr.md new file mode 100644 index 0000000000000000000000000000000000000000..5b83f23cf5b3f98a629527825871ee779a41b296 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deformable_detr.md @@ -0,0 +1,85 @@ + + +# Deformable DETR + +
+PyTorch +
+ +## Overview + +The Deformable DETR model was proposed in [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai. +Deformable DETR mitigates the slow convergence issues and limited feature spatial resolution of the original [DETR](detr) by leveraging a new deformable attention module which only attends to a small set of key sampling points around a reference. + +The abstract from the paper is the following: + +*DETR has been recently proposed to eliminate the need for many hand-designed components in object detection while demonstrating good performance. However, it suffers from slow convergence and limited feature spatial resolution, due to the limitation of Transformer attention modules in processing image feature maps. To mitigate these issues, we proposed Deformable DETR, whose attention modules only attend to a small set of key sampling points around a reference. Deformable DETR can achieve better performance than DETR (especially on small objects) with 10 times less training epochs. Extensive experiments on the COCO benchmark demonstrate the effectiveness of our approach.* + + + + Deformable DETR architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/fundamentalvision/Deformable-DETR). + +## Usage tips + +- Training Deformable DETR is equivalent to training the original [DETR](detr) model. See the [resources](#resources) section below for demo notebooks. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Deformable DETR. + + + +- Demo notebooks regarding inference + fine-tuning on a custom dataset for [`DeformableDetrForObjectDetection`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Deformable-DETR). +- Scripts for finetuning [`DeformableDetrForObjectDetection`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/object-detection). +- See also: [Object detection task guide](../tasks/object_detection). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DeformableDetrImageProcessor + +[[autodoc]] DeformableDetrImageProcessor + - preprocess + - post_process_object_detection + +## DeformableDetrImageProcessorFast + +[[autodoc]] DeformableDetrImageProcessorFast + - preprocess + - post_process_object_detection + +## DeformableDetrFeatureExtractor + +[[autodoc]] DeformableDetrFeatureExtractor + - __call__ + - post_process_object_detection + +## DeformableDetrConfig + +[[autodoc]] DeformableDetrConfig + +## DeformableDetrModel + +[[autodoc]] DeformableDetrModel + - forward + +## DeformableDetrForObjectDetection + +[[autodoc]] DeformableDetrForObjectDetection + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deit.md new file mode 100644 index 0000000000000000000000000000000000000000..0750d4000a442b6f3f1326c314e6aae5349738d3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deit.md @@ -0,0 +1,186 @@ + + +# DeiT + +
+PyTorch +TensorFlow +SDPA +
+ +## Overview + +The DeiT model was proposed in [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre +Sablayrolles, Hervé Jégou. The [Vision Transformer (ViT)](vit) introduced in [Dosovitskiy et al., 2020](https://arxiv.org/abs/2010.11929) has shown that one can match or even outperform existing convolutional neural +networks using a Transformer encoder (BERT-like). However, the ViT models introduced in that paper required training on +expensive infrastructure for multiple weeks, using external data. DeiT (data-efficient image transformers) are more +efficiently trained transformers for image classification, requiring far less data and far less computing resources +compared to the original ViT models. + +The abstract from the paper is the following: + +*Recently, neural networks purely based on attention were shown to address image understanding tasks such as image +classification. However, these visual transformers are pre-trained with hundreds of millions of images using an +expensive infrastructure, thereby limiting their adoption. In this work, we produce a competitive convolution-free +transformer by training on Imagenet only. We train them on a single computer in less than 3 days. Our reference vision +transformer (86M parameters) achieves top-1 accuracy of 83.1% (single-crop evaluation) on ImageNet with no external +data. More importantly, we introduce a teacher-student strategy specific to transformers. It relies on a distillation +token ensuring that the student learns from the teacher through attention. We show the interest of this token-based +distillation, especially when using a convnet as a teacher. This leads us to report results competitive with convnets +for both Imagenet (where we obtain up to 85.2% accuracy) and when transferring to other tasks. We share our code and +models.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The TensorFlow version of this model was added by [amyeroberts](https://huggingface.co/amyeroberts). + +## Usage tips + +- Compared to ViT, DeiT models use a so-called distillation token to effectively learn from a teacher (which, in the + DeiT paper, is a ResNet like-model). The distillation token is learned through backpropagation, by interacting with + the class ([CLS]) and patch tokens through the self-attention layers. +- There are 2 ways to fine-tune distilled models, either (1) in a classic way, by only placing a prediction head on top + of the final hidden state of the class token and not using the distillation signal, or (2) by placing both a + prediction head on top of the class token and on top of the distillation token. In that case, the [CLS] prediction + head is trained using regular cross-entropy between the prediction of the head and the ground-truth label, while the + distillation prediction head is trained using hard distillation (cross-entropy between the prediction of the + distillation head and the label predicted by the teacher). At inference time, one takes the average prediction + between both heads as final prediction. (2) is also called "fine-tuning with distillation", because one relies on a + teacher that has already been fine-tuned on the downstream dataset. In terms of models, (1) corresponds to + [`DeiTForImageClassification`] and (2) corresponds to + [`DeiTForImageClassificationWithTeacher`]. +- Note that the authors also did try soft distillation for (2) (in which case the distillation prediction head is + trained using KL divergence to match the softmax output of the teacher), but hard distillation gave the best results. +- All released checkpoints were pre-trained and fine-tuned on ImageNet-1k only. No external data was used. This is in + contrast with the original ViT model, which used external data like the JFT-300M dataset/Imagenet-21k for + pre-training. +- The authors of DeiT also released more efficiently trained ViT models, which you can directly plug into + [`ViTModel`] or [`ViTForImageClassification`]. Techniques like data + augmentation, optimization, and regularization were used in order to simulate training on a much larger dataset + (while only using ImageNet-1k for pre-training). There are 4 variants available (in 3 different sizes): + *facebook/deit-tiny-patch16-224*, *facebook/deit-small-patch16-224*, *facebook/deit-base-patch16-224* and + *facebook/deit-base-patch16-384*. Note that one should use [`DeiTImageProcessor`] in order to + prepare images for the model. + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import DeiTForImageClassification +model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16) +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `facebook/deit-base-distilled-patch16-224` model, we saw the following speedups during inference. + +| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) | +|--------------|-------------------------------------------|-------------------------------------------|------------------------------| +| 1 | 8 | 6 | 1.33 | +| 2 | 9 | 6 | 1.5 | +| 4 | 9 | 6 | 1.5 | +| 8 | 8 | 6 | 1.33 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DeiT. + + + +- [`DeiTForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +Besides that: + +- [`DeiTForMaskedImageModeling`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DeiTConfig + +[[autodoc]] DeiTConfig + +## DeiTFeatureExtractor + +[[autodoc]] DeiTFeatureExtractor + - __call__ + +## DeiTImageProcessor + +[[autodoc]] DeiTImageProcessor + - preprocess + +## DeiTImageProcessorFast + +[[autodoc]] DeiTImageProcessorFast + - preprocess + + + + +## DeiTModel + +[[autodoc]] DeiTModel + - forward + +## DeiTForMaskedImageModeling + +[[autodoc]] DeiTForMaskedImageModeling + - forward + +## DeiTForImageClassification + +[[autodoc]] DeiTForImageClassification + - forward + +## DeiTForImageClassificationWithTeacher + +[[autodoc]] DeiTForImageClassificationWithTeacher + - forward + + + + +## TFDeiTModel + +[[autodoc]] TFDeiTModel + - call + +## TFDeiTForMaskedImageModeling + +[[autodoc]] TFDeiTForMaskedImageModeling + - call + +## TFDeiTForImageClassification + +[[autodoc]] TFDeiTForImageClassification + - call + +## TFDeiTForImageClassificationWithTeacher + +[[autodoc]] TFDeiTForImageClassificationWithTeacher + - call + + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deplot.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deplot.md new file mode 100644 index 0000000000000000000000000000000000000000..d3c0de7b7f84f44f720e2288bbd3ba77ea2c6268 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deplot.md @@ -0,0 +1,70 @@ + + +# DePlot + +
+PyTorch +
+ +## Overview + +DePlot was proposed in the paper [DePlot: One-shot visual language reasoning by plot-to-table translation](https://arxiv.org/abs/2212.10505) from Fangyu Liu, Julian Martin Eisenschlos, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Wenhu Chen, Nigel Collier, Yasemin Altun. + +The abstract of the paper states the following: + +*Visual language such as charts and plots is ubiquitous in the human world. Comprehending plots and charts requires strong reasoning skills. Prior state-of-the-art (SOTA) models require at least tens of thousands of training examples and their reasoning capabilities are still much limited, especially on complex human-written queries. This paper presents the first one-shot solution to visual language reasoning. We decompose the challenge of visual language reasoning into two steps: (1) plot-to-text translation, and (2) reasoning over the translated text. The key in this method is a modality conversion module, named as DePlot, which translates the image of a plot or chart to a linearized table. The output of DePlot can then be directly used to prompt a pretrained large language model (LLM), exploiting the few-shot reasoning capabilities of LLMs. To obtain DePlot, we standardize the plot-to-table task by establishing unified task formats and metrics, and train DePlot end-to-end on this task. DePlot can then be used off-the-shelf together with LLMs in a plug-and-play fashion. Compared with a SOTA model finetuned on more than >28k data points, DePlot+LLM with just one-shot prompting achieves a 24.0% improvement over finetuned SOTA on human-written queries from the task of chart QA.* + +DePlot is a model that is trained using `Pix2Struct` architecture. You can find more information about `Pix2Struct` in the [Pix2Struct documentation](https://huggingface.co/docs/transformers/main/en/model_doc/pix2struct). +DePlot is a Visual Question Answering subset of `Pix2Struct` architecture. It renders the input question on the image and predicts the answer. + +## Usage example + +Currently one checkpoint is available for DePlot: + +- `google/deplot`: DePlot fine-tuned on ChartQA dataset + + +```python +from transformers import AutoProcessor, Pix2StructForConditionalGeneration +import requests +from PIL import Image + +model = Pix2StructForConditionalGeneration.from_pretrained("google/deplot") +processor = AutoProcessor.from_pretrained("google/deplot") +url = "https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/5090.png" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(images=image, text="Generate underlying data table of the figure below:", return_tensors="pt") +predictions = model.generate(**inputs, max_new_tokens=512) +print(processor.decode(predictions[0], skip_special_tokens=True)) +``` + +## Fine-tuning + +To fine-tune DePlot, refer to the pix2struct [fine-tuning notebook](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_pix2struct.ipynb). For `Pix2Struct` models, we have found out that fine-tuning the model with Adafactor and cosine learning rate scheduler leads to faster convergence: +```python +from transformers.optimization import Adafactor, get_cosine_schedule_with_warmup + +optimizer = Adafactor(self.parameters(), scale_parameter=False, relative_step=False, lr=0.01, weight_decay=1e-05) +scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=1000, num_training_steps=40000) +``` + + + +DePlot is a model trained using `Pix2Struct` architecture. For API reference, see [`Pix2Struct` documentation](pix2struct). + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything.md new file mode 100644 index 0000000000000000000000000000000000000000..07bed70880375859b029773582df6262e681c790 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything.md @@ -0,0 +1,120 @@ + + +# Depth Anything + +
+PyTorch +
+ +## Overview + +The Depth Anything model was proposed in [Depth Anything: Unleashing the Power of Large-Scale Unlabeled Data](https://arxiv.org/abs/2401.10891) by Lihe Yang, Bingyi Kang, Zilong Huang, Xiaogang Xu, Jiashi Feng, Hengshuang Zhao. Depth Anything is based on the [DPT](dpt) architecture, trained on ~62 million images, obtaining state-of-the-art results for both relative and absolute depth estimation. + + + +[Depth Anything V2](depth_anything_v2) was released in June 2024. It uses the same architecture as Depth Anything and therefore it is compatible with all code examples and existing workflows. However, it leverages synthetic data and a larger capacity teacher model to achieve much finer and robust depth predictions. + + + +The abstract from the paper is the following: + +*This work presents Depth Anything, a highly practical solution for robust monocular depth estimation. Without pursuing novel technical modules, we aim to build a simple yet powerful foundation model dealing with any images under any circumstances. To this end, we scale up the dataset by designing a data engine to collect and automatically annotate large-scale unlabeled data (~62M), which significantly enlarges the data coverage and thus is able to reduce the generalization error. We investigate two simple yet effective strategies that make data scaling-up promising. First, a more challenging optimization target is created by leveraging data augmentation tools. It compels the model to actively seek extra visual knowledge and acquire robust representations. Second, an auxiliary supervision is developed to enforce the model to inherit rich semantic priors from pre-trained encoders. We evaluate its zero-shot capabilities extensively, including six public datasets and randomly captured photos. It demonstrates impressive generalization ability. Further, through fine-tuning it with metric depth information from NYUv2 and KITTI, new SOTAs are set. Our better depth model also results in a better depth-conditioned ControlNet.* + + + + Depth Anything overview. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/LiheYoung/Depth-Anything). + +## Usage example + +There are 2 main ways to use Depth Anything: either using the pipeline API, which abstracts away all the complexity for you, or by using the `DepthAnythingForDepthEstimation` class yourself. + +### Pipeline API + +The pipeline allows to use the model in a few lines of code: + +```python +>>> from transformers import pipeline +>>> from PIL import Image +>>> import requests + +>>> # load pipe +>>> pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-small-hf") + +>>> # load image +>>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> # inference +>>> depth = pipe(image)["depth"] +``` + +### Using the model yourself + +If you want to do the pre- and postprocessing yourself, here's how to do that: + +```python +>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation +>>> import torch +>>> import numpy as np +>>> from PIL import Image +>>> import requests + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf") +>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf") + +>>> # prepare image for the model +>>> inputs = image_processor(images=image, return_tensors="pt") + +>>> with torch.no_grad(): +... outputs = model(**inputs) + +>>> # interpolate to original size and visualize the prediction +>>> post_processed_output = image_processor.post_process_depth_estimation( +... outputs, +... target_sizes=[(image.height, image.width)], +... ) + +>>> predicted_depth = post_processed_output[0]["predicted_depth"] +>>> depth = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min()) +>>> depth = depth.detach().cpu().numpy() * 255 +>>> depth = Image.fromarray(depth.astype("uint8")) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Depth Anything. + +- [Monocular depth estimation task guide](../tasks/monocular_depth_estimation) +- A notebook showcasing inference with [`DepthAnythingForDepthEstimation`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Depth%20Anything/Predicting_depth_in_an_image_with_Depth_Anything.ipynb). 🌎 + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DepthAnythingConfig + +[[autodoc]] DepthAnythingConfig + +## DepthAnythingForDepthEstimation + +[[autodoc]] DepthAnythingForDepthEstimation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything_v2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything_v2.md new file mode 100644 index 0000000000000000000000000000000000000000..c98017d2bbc510afe68b46c8021659958d835692 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_anything_v2.md @@ -0,0 +1,112 @@ + + +# Depth Anything V2 + +## Overview + +Depth Anything V2 was introduced in [the paper of the same name](https://arxiv.org/abs/2406.09414) by Lihe Yang et al. It uses the same architecture as the original [Depth Anything model](depth_anything), but uses synthetic data and a larger capacity teacher model to achieve much finer and robust depth predictions. + +The abstract from the paper is the following: + +*This work presents Depth Anything V2. Without pursuing fancy techniques, we aim to reveal crucial findings to pave the way towards building a powerful monocular depth estimation model. Notably, compared with V1, this version produces much finer and more robust depth predictions through three key practices: 1) replacing all labeled real images with synthetic images, 2) scaling up the capacity of our teacher model, and 3) teaching student models via the bridge of large-scale pseudo-labeled real images. Compared with the latest models built on Stable Diffusion, our models are significantly more efficient (more than 10x faster) and more accurate. We offer models of different scales (ranging from 25M to 1.3B params) to support extensive scenarios. Benefiting from their strong generalization capability, we fine-tune them with metric depth labels to obtain our metric depth models. In addition to our models, considering the limited diversity and frequent noise in current test sets, we construct a versatile evaluation benchmark with precise annotations and diverse scenes to facilitate future research.* + + + + Depth Anything overview. Taken from the original paper. + +The Depth Anything models were contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/DepthAnything/Depth-Anything-V2). + +## Usage example + +There are 2 main ways to use Depth Anything V2: either using the pipeline API, which abstracts away all the complexity for you, or by using the `DepthAnythingForDepthEstimation` class yourself. + +### Pipeline API + +The pipeline allows to use the model in a few lines of code: + +```python +>>> from transformers import pipeline +>>> from PIL import Image +>>> import requests + +>>> # load pipe +>>> pipe = pipeline(task="depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf") + +>>> # load image +>>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> # inference +>>> depth = pipe(image)["depth"] +``` + +### Using the model yourself + +If you want to do the pre- and post-processing yourself, here's how to do that: + +```python +>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation +>>> import torch +>>> import numpy as np +>>> from PIL import Image +>>> import requests + +>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> image_processor = AutoImageProcessor.from_pretrained("depth-anything/Depth-Anything-V2-Small-hf") +>>> model = AutoModelForDepthEstimation.from_pretrained("depth-anything/Depth-Anything-V2-Small-hf") + +>>> # prepare image for the model +>>> inputs = image_processor(images=image, return_tensors="pt") + +>>> with torch.no_grad(): +... outputs = model(**inputs) + +>>> # interpolate to original size and visualize the prediction +>>> post_processed_output = image_processor.post_process_depth_estimation( +... outputs, +... target_sizes=[(image.height, image.width)], +... ) + +>>> predicted_depth = post_processed_output[0]["predicted_depth"] +>>> depth = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min()) +>>> depth = depth.detach().cpu().numpy() * 255 +>>> depth = Image.fromarray(depth.astype("uint8")) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Depth Anything. + +- [Monocular depth estimation task guide](../tasks/monocular_depth_estimation) +- [Depth Anything V2 demo](https://huggingface.co/spaces/depth-anything/Depth-Anything-V2). +- A notebook showcasing inference with [`DepthAnythingForDepthEstimation`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Depth%20Anything/Predicting_depth_in_an_image_with_Depth_Anything.ipynb). 🌎 +- [Core ML conversion of the `small` variant for use on Apple Silicon](https://huggingface.co/apple/coreml-depth-anything-v2-small). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DepthAnythingConfig + +[[autodoc]] DepthAnythingConfig + +## DepthAnythingForDepthEstimation + +[[autodoc]] DepthAnythingForDepthEstimation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_pro.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_pro.md new file mode 100644 index 0000000000000000000000000000000000000000..42fd725a9abefb52fdf3af82e966983268af436f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/depth_pro.md @@ -0,0 +1,187 @@ + + +# DepthPro + +
+PyTorch +
+ +## Overview + +The DepthPro model was proposed in [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://arxiv.org/abs/2410.02073) by Aleksei Bochkovskii, Amaël Delaunoy, Hugo Germain, Marcel Santos, Yichao Zhou, Stephan R. Richter, Vladlen Koltun. + +DepthPro is a foundation model for zero-shot metric monocular depth estimation, designed to generate high-resolution depth maps with remarkable sharpness and fine-grained details. It employs a multi-scale Vision Transformer (ViT)-based architecture, where images are downsampled, divided into patches, and processed using a shared Dinov2 encoder. The extracted patch-level features are merged, upsampled, and refined using a DPT-like fusion stage, enabling precise depth estimation. + +The abstract from the paper is the following: + +*We present a foundation model for zero-shot metric monocular depth estimation. Our model, Depth Pro, synthesizes high-resolution depth maps with unparalleled sharpness and high-frequency details. The predictions are metric, with absolute scale, without relying on the availability of metadata such as camera intrinsics. And the model is fast, producing a 2.25-megapixel depth map in 0.3 seconds on a standard GPU. These characteristics are enabled by a number of technical contributions, including an efficient multi-scale vision transformer for dense prediction, a training protocol that combines real and synthetic datasets to achieve high metric accuracy alongside fine boundary tracing, dedicated evaluation metrics for boundary accuracy in estimated depth maps, and state-of-the-art focal length estimation from a single image. Extensive experiments analyze specific design choices and demonstrate that Depth Pro outperforms prior work along multiple dimensions.* + + + + DepthPro Outputs. Taken from the official code. + +This model was contributed by [geetu040](https://github.com/geetu040). The original code can be found [here](https://github.com/apple/ml-depth-pro). + +## Usage Tips + +The DepthPro model processes an input image by first downsampling it at multiple scales and splitting each scaled version into patches. These patches are then encoded using a shared Vision Transformer (ViT)-based Dinov2 patch encoder, while the full image is processed by a separate image encoder. The extracted patch features are merged into feature maps, upsampled, and fused using a DPT-like decoder to generate the final depth estimation. If enabled, an additional Field of View (FOV) encoder processes the image for estimating the camera's field of view, aiding in depth accuracy. + +```py +>>> import requests +>>> from PIL import Image +>>> import torch +>>> from transformers import DepthProImageProcessorFast, DepthProForDepthEstimation + +>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +>>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> image_processor = DepthProImageProcessorFast.from_pretrained("apple/DepthPro-hf") +>>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf").to(device) + +>>> inputs = image_processor(images=image, return_tensors="pt").to(device) + +>>> with torch.no_grad(): +... outputs = model(**inputs) + +>>> post_processed_output = image_processor.post_process_depth_estimation( +... outputs, target_sizes=[(image.height, image.width)], +... ) + +>>> field_of_view = post_processed_output[0]["field_of_view"] +>>> focal_length = post_processed_output[0]["focal_length"] +>>> depth = post_processed_output[0]["predicted_depth"] +>>> depth = (depth - depth.min()) / depth.max() +>>> depth = depth * 255. +>>> depth = depth.detach().cpu().numpy() +>>> depth = Image.fromarray(depth.astype("uint8")) +``` + +### Architecture and Configuration + + + + DepthPro architecture. Taken from the original paper. + +The `DepthProForDepthEstimation` model uses a `DepthProEncoder`, for encoding the input image and a `FeatureFusionStage` for fusing the output features from encoder. + +The `DepthProEncoder` further uses two encoders: +- `patch_encoder` + - Input image is scaled with multiple ratios, as specified in the `scaled_images_ratios` configuration. + - Each scaled image is split into smaller **patches** of size `patch_size` with overlapping areas determined by `scaled_images_overlap_ratios`. + - These patches are processed by the **`patch_encoder`** +- `image_encoder` + - Input image is also rescaled to `patch_size` and processed by the **`image_encoder`** + +Both these encoders can be configured via `patch_model_config` and `image_model_config` respectively, both of which are separate `Dinov2Model` by default. + +Outputs from both encoders (`last_hidden_state`) and selected intermediate states (`hidden_states`) from **`patch_encoder`** are fused by a `DPT`-based `FeatureFusionStage` for depth estimation. + +### Field-of-View (FOV) Prediction + +The network is supplemented with a focal length estimation head. A small convolutional head ingests frozen features from the depth estimation network and task-specific features from a separate ViT image encoder to predict the horizontal angular field-of-view. + +The `use_fov_model` parameter in `DepthProConfig` controls whether **FOV prediction** is enabled. By default, it is set to `False` to conserve memory and computation. When enabled, the **FOV encoder** is instantiated based on the `fov_model_config` parameter, which defaults to a `Dinov2Model`. The `use_fov_model` parameter can also be passed when initializing the `DepthProForDepthEstimation` model. + +The pretrained model at checkpoint `apple/DepthPro-hf` uses the FOV encoder. To use the pretrained-model without FOV encoder, set `use_fov_model=False` when loading the model, which saves computation. +```py +>>> from transformers import DepthProForDepthEstimation +>>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", use_fov_model=False) +``` + +To instantiate a new model with FOV encoder, set `use_fov_model=True` in the config. +```py +>>> from transformers import DepthProConfig, DepthProForDepthEstimation +>>> config = DepthProConfig(use_fov_model=True) +>>> model = DepthProForDepthEstimation(config) +``` + +Or set `use_fov_model=True` when initializing the model, which overrides the value in config. +```py +>>> from transformers import DepthProConfig, DepthProForDepthEstimation +>>> config = DepthProConfig() +>>> model = DepthProForDepthEstimation(config, use_fov_model=True) +``` + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +```py +from transformers import DepthProForDepthEstimation +model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", attn_implementation="sdpa", torch_dtype=torch.float16) +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `google/vit-base-patch16-224` model, we saw the following speedups during inference. + +| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) | +|--------------|-------------------------------------------|-------------------------------------------|------------------------------| +| 1 | 7 | 6 | 1.17 | +| 2 | 8 | 6 | 1.33 | +| 4 | 8 | 6 | 1.33 | +| 8 | 8 | 6 | 1.33 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DepthPro: + +- Research Paper: [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://arxiv.org/pdf/2410.02073) +- Official Implementation: [apple/ml-depth-pro](https://github.com/apple/ml-depth-pro) +- DepthPro Inference Notebook: [DepthPro Inference](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/DepthPro_inference.ipynb) +- DepthPro for Super Resolution and Image Segmentation + - Read blog on Medium: [Depth Pro: Beyond Depth](https://medium.com/@raoarmaghanshakir040/depth-pro-beyond-depth-9d822fc557ba) + - Code on Github: [geetu040/depthpro-beyond-depth](https://github.com/geetu040/depthpro-beyond-depth) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DepthProConfig + +[[autodoc]] DepthProConfig + +## DepthProImageProcessor + +[[autodoc]] DepthProImageProcessor + - preprocess + - post_process_depth_estimation + +## DepthProImageProcessorFast + +[[autodoc]] DepthProImageProcessorFast + - preprocess + - post_process_depth_estimation + +## DepthProModel + +[[autodoc]] DepthProModel + - forward + +## DepthProForDepthEstimation + +[[autodoc]] DepthProForDepthEstimation + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deta.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deta.md new file mode 100644 index 0000000000000000000000000000000000000000..e3859341a71af9ec7ae0d74ba9cfb4882587fe6a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/deta.md @@ -0,0 +1,77 @@ + + +# DETA + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The DETA model was proposed in [NMS Strikes Back](https://arxiv.org/abs/2212.06137) by Jeffrey Ouyang-Zhang, Jang Hyun Cho, Xingyi Zhou, Philipp Krähenbühl. +DETA (short for Detection Transformers with Assignment) improves [Deformable DETR](deformable_detr) by replacing the one-to-one bipartite Hungarian matching loss +with one-to-many label assignments used in traditional detectors with non-maximum suppression (NMS). This leads to significant gains of up to 2.5 mAP. + +The abstract from the paper is the following: + +*Detection Transformer (DETR) directly transforms queries to unique objects by using one-to-one bipartite matching during training and enables end-to-end object detection. Recently, these models have surpassed traditional detectors on COCO with undeniable elegance. However, they differ from traditional detectors in multiple designs, including model architecture and training schedules, and thus the effectiveness of one-to-one matching is not fully understood. In this work, we conduct a strict comparison between the one-to-one Hungarian matching in DETRs and the one-to-many label assignments in traditional detectors with non-maximum supervision (NMS). Surprisingly, we observe one-to-many assignments with NMS consistently outperform standard one-to-one matching under the same setting, with a significant gain of up to 2.5 mAP. Our detector that trains Deformable-DETR with traditional IoU-based label assignment achieved 50.2 COCO mAP within 12 epochs (1x schedule) with ResNet50 backbone, outperforming all existing traditional or transformer-based detectors in this setting. On multiple datasets, schedules, and architectures, we consistently show bipartite matching is unnecessary for performant detection transformers. Furthermore, we attribute the success of detection transformers to their expressive transformer architecture.* + + + + DETA overview. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/jozhang97/DETA). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DETA. + +- Demo notebooks for DETA can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DETA). +- Scripts for finetuning [`DetaForObjectDetection`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/object-detection). +- See also: [Object detection task guide](../tasks/object_detection). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DetaConfig + +[[autodoc]] DetaConfig + +## DetaImageProcessor + +[[autodoc]] DetaImageProcessor + - preprocess + - post_process_object_detection + +## DetaModel + +[[autodoc]] DetaModel + - forward + +## DetaForObjectDetection + +[[autodoc]] DetaForObjectDetection + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/detr.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/detr.md new file mode 100644 index 0000000000000000000000000000000000000000..4614d549a180fe51d9d1947471dabc8c126fbc11 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/detr.md @@ -0,0 +1,227 @@ + + +# DETR + +
+PyTorch +
+ +## Overview + +The DETR model was proposed in [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by +Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov and Sergey Zagoruyko. DETR +consists of a convolutional backbone followed by an encoder-decoder Transformer which can be trained end-to-end for +object detection. It greatly simplifies a lot of the complexity of models like Faster-R-CNN and Mask-R-CNN, which use +things like region proposals, non-maximum suppression procedure and anchor generation. Moreover, DETR can also be +naturally extended to perform panoptic segmentation, by simply adding a mask head on top of the decoder outputs. + +The abstract from the paper is the following: + +*We present a new method that views object detection as a direct set prediction problem. Our approach streamlines the +detection pipeline, effectively removing the need for many hand-designed components like a non-maximum suppression +procedure or anchor generation that explicitly encode our prior knowledge about the task. The main ingredients of the +new framework, called DEtection TRansformer or DETR, are a set-based global loss that forces unique predictions via +bipartite matching, and a transformer encoder-decoder architecture. Given a fixed small set of learned object queries, +DETR reasons about the relations of the objects and the global image context to directly output the final set of +predictions in parallel. The new model is conceptually simple and does not require a specialized library, unlike many +other modern detectors. DETR demonstrates accuracy and run-time performance on par with the well-established and +highly-optimized Faster RCNN baseline on the challenging COCO object detection dataset. Moreover, DETR can be easily +generalized to produce panoptic segmentation in a unified manner. We show that it significantly outperforms competitive +baselines.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/facebookresearch/detr). + +## How DETR works + +Here's a TLDR explaining how [`~transformers.DetrForObjectDetection`] works: + +First, an image is sent through a pre-trained convolutional backbone (in the paper, the authors use +ResNet-50/ResNet-101). Let's assume we also add a batch dimension. This means that the input to the backbone is a +tensor of shape `(batch_size, 3, height, width)`, assuming the image has 3 color channels (RGB). The CNN backbone +outputs a new lower-resolution feature map, typically of shape `(batch_size, 2048, height/32, width/32)`. This is +then projected to match the hidden dimension of the Transformer of DETR, which is `256` by default, using a +`nn.Conv2D` layer. So now, we have a tensor of shape `(batch_size, 256, height/32, width/32).` Next, the +feature map is flattened and transposed to obtain a tensor of shape `(batch_size, seq_len, d_model)` = +`(batch_size, width/32*height/32, 256)`. So a difference with NLP models is that the sequence length is actually +longer than usual, but with a smaller `d_model` (which in NLP is typically 768 or higher). + +Next, this is sent through the encoder, outputting `encoder_hidden_states` of the same shape (you can consider +these as image features). Next, so-called **object queries** are sent through the decoder. This is a tensor of shape +`(batch_size, num_queries, d_model)`, with `num_queries` typically set to 100 and initialized with zeros. +These input embeddings are learnt positional encodings that the authors refer to as object queries, and similarly to +the encoder, they are added to the input of each attention layer. Each object query will look for a particular object +in the image. The decoder updates these embeddings through multiple self-attention and encoder-decoder attention layers +to output `decoder_hidden_states` of the same shape: `(batch_size, num_queries, d_model)`. Next, two heads +are added on top for object detection: a linear layer for classifying each object query into one of the objects or "no +object", and a MLP to predict bounding boxes for each query. + +The model is trained using a **bipartite matching loss**: so what we actually do is compare the predicted classes + +bounding boxes of each of the N = 100 object queries to the ground truth annotations, padded up to the same length N +(so if an image only contains 4 objects, 96 annotations will just have a "no object" as class and "no bounding box" as +bounding box). The [Hungarian matching algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm) is used to find +an optimal one-to-one mapping of each of the N queries to each of the N annotations. Next, standard cross-entropy (for +the classes) and a linear combination of the L1 and [generalized IoU loss](https://giou.stanford.edu/) (for the +bounding boxes) are used to optimize the parameters of the model. + +DETR can be naturally extended to perform panoptic segmentation (which unifies semantic segmentation and instance +segmentation). [`~transformers.DetrForSegmentation`] adds a segmentation mask head on top of +[`~transformers.DetrForObjectDetection`]. The mask head can be trained either jointly, or in a two steps process, +where one first trains a [`~transformers.DetrForObjectDetection`] model to detect bounding boxes around both +"things" (instances) and "stuff" (background things like trees, roads, sky), then freeze all the weights and train only +the mask head for 25 epochs. Experimentally, these two approaches give similar results. Note that predicting boxes is +required for the training to be possible, since the Hungarian matching is computed using distances between boxes. + +## Usage tips + +- DETR uses so-called **object queries** to detect objects in an image. The number of queries determines the maximum + number of objects that can be detected in a single image, and is set to 100 by default (see parameter + `num_queries` of [`~transformers.DetrConfig`]). Note that it's good to have some slack (in COCO, the + authors used 100, while the maximum number of objects in a COCO image is ~70). +- The decoder of DETR updates the query embeddings in parallel. This is different from language models like GPT-2, + which use autoregressive decoding instead of parallel. Hence, no causal attention mask is used. +- DETR adds position embeddings to the hidden states at each self-attention and cross-attention layer before projecting + to queries and keys. For the position embeddings of the image, one can choose between fixed sinusoidal or learned + absolute position embeddings. By default, the parameter `position_embedding_type` of + [`~transformers.DetrConfig`] is set to `"sine"`. +- During training, the authors of DETR did find it helpful to use auxiliary losses in the decoder, especially to help + the model output the correct number of objects of each class. If you set the parameter `auxiliary_loss` of + [`~transformers.DetrConfig`] to `True`, then prediction feedforward neural networks and Hungarian losses + are added after each decoder layer (with the FFNs sharing parameters). +- If you want to train the model in a distributed environment across multiple nodes, then one should update the + _num_boxes_ variable in the _DetrLoss_ class of _modeling_detr.py_. When training on multiple nodes, this should be + set to the average number of target boxes across all nodes, as can be seen in the original implementation [here](https://github.com/facebookresearch/detr/blob/a54b77800eb8e64e3ad0d8237789fcbf2f8350c5/models/detr.py#L227-L232). +- [`~transformers.DetrForObjectDetection`] and [`~transformers.DetrForSegmentation`] can be initialized with + any convolutional backbone available in the [timm library](https://github.com/rwightman/pytorch-image-models). + Initializing with a MobileNet backbone for example can be done by setting the `backbone` attribute of + [`~transformers.DetrConfig`] to `"tf_mobilenetv3_small_075"`, and then initializing the model with that + config. +- DETR resizes the input images such that the shortest side is at least a certain amount of pixels while the longest is + at most 1333 pixels. At training time, scale augmentation is used such that the shortest side is randomly set to at + least 480 and at most 800 pixels. At inference time, the shortest side is set to 800. One can use + [`~transformers.DetrImageProcessor`] to prepare images (and optional annotations in COCO format) for the + model. Due to this resizing, images in a batch can have different sizes. DETR solves this by padding images up to the + largest size in a batch, and by creating a pixel mask that indicates which pixels are real/which are padding. + Alternatively, one can also define a custom `collate_fn` in order to batch images together, using + [`~transformers.DetrImageProcessor.pad_and_create_pixel_mask`]. +- The size of the images will determine the amount of memory being used, and will thus determine the `batch_size`. + It is advised to use a batch size of 2 per GPU. See [this Github thread](https://github.com/facebookresearch/detr/issues/150) for more info. + +There are three ways to instantiate a DETR model (depending on what you prefer): + +Option 1: Instantiate DETR with pre-trained weights for entire model +```py +>>> from transformers import DetrForObjectDetection + +>>> model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50") +``` + +Option 2: Instantiate DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone +```py +>>> from transformers import DetrConfig, DetrForObjectDetection + +>>> config = DetrConfig() +>>> model = DetrForObjectDetection(config) +``` +Option 3: Instantiate DETR with randomly initialized weights for backbone + Transformer +```py +>>> config = DetrConfig(use_pretrained_backbone=False) +>>> model = DetrForObjectDetection(config) +``` + +As a summary, consider the following table: + +| Task | Object detection | Instance segmentation | Panoptic segmentation | +|------|------------------|-----------------------|-----------------------| +| **Description** | Predicting bounding boxes and class labels around objects in an image | Predicting masks around objects (i.e. instances) in an image | Predicting masks around both objects (i.e. instances) as well as "stuff" (i.e. background things like trees and roads) in an image | +| **Model** | [`~transformers.DetrForObjectDetection`] | [`~transformers.DetrForSegmentation`] | [`~transformers.DetrForSegmentation`] | +| **Example dataset** | COCO detection | COCO detection, COCO panoptic | COCO panoptic | | +| **Format of annotations to provide to** [`~transformers.DetrImageProcessor`] | {'image_id': `int`, 'annotations': `List[Dict]`} each Dict being a COCO object annotation | {'image_id': `int`, 'annotations': `List[Dict]`} (in case of COCO detection) or {'file_name': `str`, 'image_id': `int`, 'segments_info': `List[Dict]`} (in case of COCO panoptic) | {'file_name': `str`, 'image_id': `int`, 'segments_info': `List[Dict]`} and masks_path (path to directory containing PNG files of the masks) | +| **Postprocessing** (i.e. converting the output of the model to Pascal VOC format) | [`~transformers.DetrImageProcessor.post_process`] | [`~transformers.DetrImageProcessor.post_process_segmentation`] | [`~transformers.DetrImageProcessor.post_process_segmentation`], [`~transformers.DetrImageProcessor.post_process_panoptic`] | +| **evaluators** | `CocoEvaluator` with `iou_types="bbox"` | `CocoEvaluator` with `iou_types="bbox"` or `"segm"` | `CocoEvaluator` with `iou_tupes="bbox"` or `"segm"`, `PanopticEvaluator` | + +In short, one should prepare the data either in COCO detection or COCO panoptic format, then use +[`~transformers.DetrImageProcessor`] to create `pixel_values`, `pixel_mask` and optional +`labels`, which can then be used to train (or fine-tune) a model. For evaluation, one should first convert the +outputs of the model using one of the postprocessing methods of [`~transformers.DetrImageProcessor`]. These can +be provided to either `CocoEvaluator` or `PanopticEvaluator`, which allow you to calculate metrics like +mean Average Precision (mAP) and Panoptic Quality (PQ). The latter objects are implemented in the [original repository](https://github.com/facebookresearch/detr). See the [example notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DETR) for more info regarding evaluation. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DETR. + + + +- All example notebooks illustrating fine-tuning [`DetrForObjectDetection`] and [`DetrForSegmentation`] on a custom dataset can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DETR). +- Scripts for finetuning [`DetrForObjectDetection`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/object-detection). +- See also: [Object detection task guide](../tasks/object_detection). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DetrConfig + +[[autodoc]] DetrConfig + +## DetrImageProcessor + +[[autodoc]] DetrImageProcessor + - preprocess + - post_process_object_detection + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation + +## DetrImageProcessorFast + +[[autodoc]] DetrImageProcessorFast + - preprocess + - post_process_object_detection + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation + +## DetrFeatureExtractor + +[[autodoc]] DetrFeatureExtractor + - __call__ + - post_process_object_detection + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation + +## DETR specific outputs + +[[autodoc]] models.detr.modeling_detr.DetrModelOutput + +[[autodoc]] models.detr.modeling_detr.DetrObjectDetectionOutput + +[[autodoc]] models.detr.modeling_detr.DetrSegmentationOutput + +## DetrModel + +[[autodoc]] DetrModel + - forward + +## DetrForObjectDetection + +[[autodoc]] DetrForObjectDetection + - forward + +## DetrForSegmentation + +[[autodoc]] DetrForSegmentation + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dialogpt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dialogpt.md new file mode 100644 index 0000000000000000000000000000000000000000..33d7e3b16d8869218a0c198e31cfbc195989989e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dialogpt.md @@ -0,0 +1,63 @@ + + +# DialoGPT + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +DialoGPT was proposed in [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, +Jianfeng Gao, Jingjing Liu, Bill Dolan. It's a GPT2 Model trained on 147M conversation-like exchanges extracted from +Reddit. + +The abstract from the paper is the following: + +*We present a large, tunable neural conversational response generation model, DialoGPT (dialogue generative pre-trained +transformer). Trained on 147M conversation-like exchanges extracted from Reddit comment chains over a period spanning +from 2005 through 2017, DialoGPT extends the Hugging Face PyTorch transformer to attain a performance close to human +both in terms of automatic and human evaluation in single-turn dialogue settings. We show that conversational systems +that leverage DialoGPT generate more relevant, contentful and context-consistent responses than strong baseline +systems. The pre-trained model and training pipeline are publicly released to facilitate research into neural response +generation and the development of more intelligent open-domain dialogue systems.* + +The original code can be found [here](https://github.com/microsoft/DialoGPT). + +## Usage tips + +- DialoGPT is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather + than the left. +- DialoGPT was trained with a causal language modeling (CLM) objective on conversational data and is therefore powerful + at response generation in open-domain dialogue systems. +- DialoGPT enables the user to create a chat bot in just 10 lines of code as shown on [DialoGPT's model card](https://huggingface.co/microsoft/DialoGPT-medium). + +Training: + +In order to train or fine-tune DialoGPT, one can use causal language modeling training. To cite the official paper: *We +follow the OpenAI GPT-2 to model a multiturn dialogue session as a long text and frame the generation task as language +modeling. We first concatenate all dialog turns within a dialogue session into a long text x_1,..., x_N (N is the +sequence length), ended by the end-of-text token.* For more information please confer to the original paper. + + + +DialoGPT's architecture is based on the GPT2 model, refer to [GPT2's documentation page](gpt2) for API reference and examples. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/diffllama.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/diffllama.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a170c265724dae6010ddb31d4e7e7cd296af13 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/diffllama.md @@ -0,0 +1,65 @@ + + +# DiffLlama + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The DiffLlama model was proposed in [Differential Transformer](https://arxiv.org/abs/2410.05258) by Kazuma Matsumoto and . +This model is combine Llama model and Differential Transformer's Attention. + +The abstract from the paper is the following: + +*Transformer tends to overallocate attention to irrelevant context. In this work, we introduce Diff Transformer, which amplifies attention to the relevant context while canceling noise. Specifically, the differential attention mechanism calculates attention scores as the difference between two separate softmax attention maps. The subtraction cancels noise, promoting the emergence of sparse attention patterns. Experimental results on language modeling show that Diff Transformer outperforms Transformer in various settings of scaling up model size and training tokens. More intriguingly, it offers notable advantages in practical applications, such as long-context modeling, key information retrieval, hallucination mitigation, in-context learning, and reduction of activation outliers. By being less distracted by irrelevant context, Diff Transformer can mitigate hallucination in question answering and text summarization. For in-context learning, Diff Transformer not only enhances accuracy but is also more robust to order permutation, which was considered as a chronic robustness issue. The results position Diff Transformer as a highly effective and promising architecture to advance large language models.* + +### Usage tips +The hyperparameters of this model is the same as Llama model. + + +## DiffLlamaConfig + +[[autodoc]] DiffLlamaConfig + +## DiffLlamaModel + +[[autodoc]] DiffLlamaModel + - forward + +## DiffLlamaForCausalLM + +[[autodoc]] DiffLlamaForCausalLM + - forward + +## DiffLlamaForSequenceClassification + +[[autodoc]] DiffLlamaForSequenceClassification + - forward + +## DiffLlamaForQuestionAnswering + +[[autodoc]] DiffLlamaForQuestionAnswering + - forward + +## DiffLlamaForTokenClassification + +[[autodoc]] DiffLlamaForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinat.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinat.md new file mode 100644 index 0000000000000000000000000000000000000000..cd1d67073be68770b94ff4442887853fbf788bc5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinat.md @@ -0,0 +1,95 @@ + + +# Dilated Neighborhood Attention Transformer + +
+PyTorch +
+ +## Overview + +DiNAT was proposed in [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001) +by Ali Hassani and Humphrey Shi. + +It extends [NAT](nat) by adding a Dilated Neighborhood Attention pattern to capture global context, +and shows significant performance improvements over it. + +The abstract from the paper is the following: + +*Transformers are quickly becoming one of the most heavily applied deep learning architectures across modalities, +domains, and tasks. In vision, on top of ongoing efforts into plain transformers, hierarchical transformers have +also gained significant attention, thanks to their performance and easy integration into existing frameworks. +These models typically employ localized attention mechanisms, such as the sliding-window Neighborhood Attention (NA) +or Swin Transformer's Shifted Window Self Attention. While effective at reducing self attention's quadratic complexity, +local attention weakens two of the most desirable properties of self attention: long range inter-dependency modeling, +and global receptive field. In this paper, we introduce Dilated Neighborhood Attention (DiNA), a natural, flexible and +efficient extension to NA that can capture more global context and expand receptive fields exponentially at no +additional cost. NA's local attention and DiNA's sparse global attention complement each other, and therefore we +introduce Dilated Neighborhood Attention Transformer (DiNAT), a new hierarchical vision transformer built upon both. +DiNAT variants enjoy significant improvements over strong baselines such as NAT, Swin, and ConvNeXt. +Our large model is faster and ahead of its Swin counterpart by 1.5% box AP in COCO object detection, +1.3% mask AP in COCO instance segmentation, and 1.1% mIoU in ADE20K semantic segmentation. +Paired with new frameworks, our large variant is the new state of the art panoptic segmentation model on COCO (58.2 PQ) +and ADE20K (48.5 PQ), and instance segmentation model on Cityscapes (44.5 AP) and ADE20K (35.4 AP) (no extra data). +It also matches the state of the art specialized semantic segmentation models on ADE20K (58.2 mIoU), +and ranks second on Cityscapes (84.5 mIoU) (no extra data). * + + + + Neighborhood Attention with different dilation values. +Taken from the original paper. + +This model was contributed by [Ali Hassani](https://huggingface.co/alihassanijr). +The original code can be found [here](https://github.com/SHI-Labs/Neighborhood-Attention-Transformer). + +## Usage tips + +DiNAT can be used as a *backbone*. When `output_hidden_states = True`, +it will output both `hidden_states` and `reshaped_hidden_states`. The `reshaped_hidden_states` have a shape of `(batch, num_channels, height, width)` rather than `(batch_size, height, width, num_channels)`. + +Notes: +- DiNAT depends on [NATTEN](https://github.com/SHI-Labs/NATTEN/)'s implementation of Neighborhood Attention and Dilated Neighborhood Attention. +You can install it with pre-built wheels for Linux by referring to [shi-labs.com/natten](https://shi-labs.com/natten), or build on your system by running `pip install natten`. +Note that the latter will likely take time to compile. NATTEN does not support Windows devices yet. +- Patch size of 4 is only supported at the moment. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DiNAT. + + + +- [`DinatForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DinatConfig + +[[autodoc]] DinatConfig + +## DinatModel + +[[autodoc]] DinatModel + - forward + +## DinatForImageClassification + +[[autodoc]] DinatForImageClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2.md new file mode 100644 index 0000000000000000000000000000000000000000..5c130dabda90d37e9aba00c40dcbda7b2c6ee550 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2.md @@ -0,0 +1,110 @@ + + +# DINOv2 + +
+PyTorch +Flax +SDPA +
+ +## Overview + +The DINOv2 model was proposed in [DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/abs/2304.07193) by +Maxime Oquab, Timothée Darcet, Théo Moutakanni, Huy Vo, Marc Szafraniec, Vasil Khalidov, Pierre Fernandez, Daniel Haziza, Francisco Massa, Alaaeldin El-Nouby, Mahmoud Assran, Nicolas Ballas, Wojciech Galuba, Russell Howes, Po-Yao Huang, Shang-Wen Li, Ishan Misra, Michael Rabbat, Vasu Sharma, Gabriel Synnaeve, Hu Xu, Hervé Jegou, Julien Mairal, Patrick Labatut, Armand Joulin, Piotr Bojanowski. +DINOv2 is an upgrade of [DINO](https://arxiv.org/abs/2104.14294), a self-supervised method applied on [Vision Transformers](vit). This method enables all-purpose visual features, i.e., features that work across image distributions and tasks without finetuning. + +The abstract from the paper is the following: + +*The recent breakthroughs in natural language processing for model pretraining on large quantities of data have opened the way for similar foundation models in computer vision. These models could greatly simplify the use of images in any system by producing all-purpose visual features, i.e., features that work across image distributions and tasks without finetuning. This work shows that existing pretraining methods, especially self-supervised methods, can produce such features if trained on enough curated data from diverse sources. We revisit existing approaches and combine different techniques to scale our pretraining in terms of data and model size. Most of the technical contributions aim at accelerating and stabilizing the training at scale. In terms of data, we propose an automatic pipeline to build a dedicated, diverse, and curated image dataset instead of uncurated data, as typically done in the self-supervised literature. In terms of models, we train a ViT model (Dosovitskiy et al., 2020) with 1B parameters and distill it into a series of smaller models that surpass the best available all-purpose features, OpenCLIP (Ilharco et al., 2021) on most of the benchmarks at image and pixel levels.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/facebookresearch/dinov2). + +## Usage tips + +The model can be traced using `torch.jit.trace` which leverages JIT compilation to optimize the model making it faster to run. Note this still produces some mis-matched elements and the difference between the original model and the traced model is of the order of 1e-4. + +```python +import torch +from transformers import AutoImageProcessor, AutoModel +from PIL import Image +import requests + +url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +image = Image.open(requests.get(url, stream=True).raw) + +processor = AutoImageProcessor.from_pretrained('facebook/dinov2-base') +model = AutoModel.from_pretrained('facebook/dinov2-base') + +inputs = processor(images=image, return_tensors="pt") +outputs = model(**inputs) +last_hidden_states = outputs[0] + +# We have to force return_dict=False for tracing +model.config.return_dict = False + +with torch.no_grad(): + traced_model = torch.jit.trace(model, [inputs.pixel_values]) + traced_outputs = traced_model(inputs.pixel_values) + +print((last_hidden_states - traced_outputs[0]).abs().max()) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DINOv2. + +- Demo notebooks for DINOv2 can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DINOv2). 🌎 + + + +- [`Dinov2ForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## Dinov2Config + +[[autodoc]] Dinov2Config + + + + +## Dinov2Model + +[[autodoc]] Dinov2Model + - forward + +## Dinov2ForImageClassification + +[[autodoc]] Dinov2ForImageClassification + - forward + + + + +## FlaxDinov2Model + +[[autodoc]] FlaxDinov2Model + - __call__ + + +## FlaxDinov2ForImageClassification + +[[autodoc]] FlaxDinov2ForImageClassification + - __call__ + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2_with_registers.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2_with_registers.md new file mode 100644 index 0000000000000000000000000000000000000000..7151dc45356a6219126c7ead1fd7d082766c0eee --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dinov2_with_registers.md @@ -0,0 +1,59 @@ + + +# DINOv2 with Registers + +
+PyTorch +SDPA +
+ +## Overview + +The DINOv2 with Registers model was proposed in [Vision Transformers Need Registers](https://arxiv.org/abs/2309.16588) by Timothée Darcet, Maxime Oquab, Julien Mairal, Piotr Bojanowski. + +The [Vision Transformer](vit) (ViT) is a transformer encoder model (BERT-like) originally introduced to do supervised image classification on ImageNet. + +Next, people figured out ways to make ViT work really well on self-supervised image feature extraction (i.e. learning meaningful features, also called embeddings) on images without requiring any labels. Some example papers here include [DINOv2](dinov2) and [MAE](vit_mae). + +The authors of DINOv2 noticed that ViTs have artifacts in attention maps. It’s due to the model using some image patches as “registers”. The authors propose a fix: just add some new tokens (called "register" tokens), which you only use during pre-training (and throw away afterwards). This results in: +- no artifacts +- interpretable attention maps +- and improved performances. + +The abstract from the paper is the following: + +*Transformers have recently emerged as a powerful tool for learning visual representations. In this paper, we identify and characterize artifacts in feature maps of both supervised and self-supervised ViT networks. The artifacts correspond to high-norm tokens appearing during inference primarily in low-informative background areas of images, that are repurposed for internal computations. We propose a simple yet effective solution based on providing additional tokens to the input sequence of the Vision Transformer to fill that role. We show that this solution fixes that problem entirely for both supervised and self-supervised models, sets a new state of the art for self-supervised visual models on dense visual prediction tasks, enables object discovery methods with larger models, and most importantly leads to smoother feature maps and attention maps for downstream visual processing.* + + + + Visualization of attention maps of various models trained with vs. without registers. Taken from the original paper. + +Tips: + +- Usage of DINOv2 with Registers is identical to DINOv2 without, you'll just get better performance. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/facebookresearch/dinov2). + + +## Dinov2WithRegistersConfig + +[[autodoc]] Dinov2WithRegistersConfig + +## Dinov2WithRegistersModel + +[[autodoc]] Dinov2WithRegistersModel + - forward + +## Dinov2WithRegistersForImageClassification + +[[autodoc]] Dinov2WithRegistersForImageClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/distilbert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/distilbert.md new file mode 100644 index 0000000000000000000000000000000000000000..3f949d9443a6ffdf3e5853eac17abd26b28c9b59 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/distilbert.md @@ -0,0 +1,327 @@ + + +# DistilBERT + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +## Overview + +The DistilBERT model was proposed in the blog post [Smaller, faster, cheaper, lighter: Introducing DistilBERT, a +distilled version of BERT](https://medium.com/huggingface/distilbert-8cf3380435b5), and the paper [DistilBERT, a +distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108). DistilBERT is a +small, fast, cheap and light Transformer model trained by distilling BERT base. It has 40% less parameters than +*google-bert/bert-base-uncased*, runs 60% faster while preserving over 95% of BERT's performances as measured on the GLUE language +understanding benchmark. + +The abstract from the paper is the following: + +*As Transfer Learning from large-scale pre-trained models becomes more prevalent in Natural Language Processing (NLP), +operating these large models in on-the-edge and/or under constrained computational training or inference budgets +remains challenging. In this work, we propose a method to pre-train a smaller general-purpose language representation +model, called DistilBERT, which can then be fine-tuned with good performances on a wide range of tasks like its larger +counterparts. While most prior work investigated the use of distillation for building task-specific models, we leverage +knowledge distillation during the pretraining phase and show that it is possible to reduce the size of a BERT model by +40%, while retaining 97% of its language understanding capabilities and being 60% faster. To leverage the inductive +biases learned by larger models during pretraining, we introduce a triple loss combining language modeling, +distillation and cosine-distance losses. Our smaller, faster and lighter model is cheaper to pre-train and we +demonstrate its capabilities for on-device computations in a proof-of-concept experiment and a comparative on-device +study.* + +This model was contributed by [victorsanh](https://huggingface.co/victorsanh). This model jax version was +contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/huggingface/transformers-research-projects/tree/main/distillation). + +## Usage tips + +- DistilBERT doesn't have `token_type_ids`, you don't need to indicate which token belongs to which segment. Just + separate your segments with the separation token `tokenizer.sep_token` (or `[SEP]`). +- DistilBERT doesn't have options to select the input positions (`position_ids` input). This could be added if + necessary though, just let us know if you need this option. +- Same as BERT but smaller. Trained by distillation of the pretrained BERT model, meaning it’s been trained to predict the same probabilities as the larger model. The actual objective is a combination of: + + * finding the same probabilities as the teacher model + * predicting the masked tokens correctly (but no next-sentence objective) + * a cosine similarity between the hidden states of the student and the teacher model + +### Using Scaled Dot Product Attention (SDPA) + +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +``` +from transformers import DistilBertModel +model = DistilBertModel.from_pretrained("distilbert-base-uncased", torch_dtype=torch.float16, attn_implementation="sdpa") +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.3.1, OS Ubuntu 20.04) with `float16` and the `distilbert-base-uncased` model with +a MaskedLM head, we saw the following speedups during training and inference. + +#### Training + +| num_training_steps | batch_size | seq_len | is cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | sdpa peak mem (MB) | Mem saving (%) | +|--------------------|------------|---------|---------|----------------------------|---------------------------|-------------|---------------------|--------------------|----------------| +| 100 | 1 | 128 | False | 0.010 | 0.008 | 28.870 | 397.038 | 399.629 | -0.649 | +| 100 | 1 | 256 | False | 0.011 | 0.009 | 20.681 | 412.505 | 412.606 | -0.025 | +| 100 | 2 | 128 | False | 0.011 | 0.009 | 23.741 | 412.213 | 412.606 | -0.095 | +| 100 | 2 | 256 | False | 0.015 | 0.013 | 16.502 | 427.491 | 425.787 | 0.400 | +| 100 | 4 | 128 | False | 0.015 | 0.013 | 13.828 | 427.491 | 425.787 | 0.400 | +| 100 | 4 | 256 | False | 0.025 | 0.022 | 12.882 | 594.156 | 502.745 | 18.182 | +| 100 | 8 | 128 | False | 0.023 | 0.022 | 8.010 | 545.922 | 502.745 | 8.588 | +| 100 | 8 | 256 | False | 0.046 | 0.041 | 12.763 | 983.450 | 798.480 | 23.165 | + +#### Inference + +| num_batches | batch_size | seq_len | is cuda | is half | use mask | Per token latency eager (ms) | Per token latency SDPA (ms) | Speedup (%) | Mem eager (MB) | Mem BT (MB) | Mem saved (%) | +|-------------|------------|---------|---------|---------|----------|-----------------------------|-----------------------------|-------------|----------------|--------------|---------------| +| 50 | 2 | 64 | True | True | True | 0.032 | 0.025 | 28.192 | 154.532 | 155.531 | -0.642 | +| 50 | 2 | 128 | True | True | True | 0.033 | 0.025 | 32.636 | 157.286 | 157.482 | -0.125 | +| 50 | 4 | 64 | True | True | True | 0.032 | 0.026 | 24.783 | 157.023 | 157.449 | -0.271 | +| 50 | 4 | 128 | True | True | True | 0.034 | 0.028 | 19.299 | 162.794 | 162.269 | 0.323 | +| 50 | 8 | 64 | True | True | True | 0.035 | 0.028 | 25.105 | 160.958 | 162.204 | -0.768 | +| 50 | 8 | 128 | True | True | True | 0.052 | 0.046 | 12.375 | 173.155 | 171.844 | 0.763 | +| 50 | 16 | 64 | True | True | True | 0.051 | 0.045 | 12.882 | 172.106 | 171.713 | 0.229 | +| 50 | 16 | 128 | True | True | True | 0.096 | 0.081 | 18.524 | 191.257 | 191.517 | -0.136 | + + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DistilBERT. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A blog post on [Getting Started with Sentiment Analysis using Python](https://huggingface.co/blog/sentiment-analysis-python) with DistilBERT. +- A blog post on how to [train DistilBERT with Blurr for sequence classification](https://huggingface.co/blog/fastai). +- A blog post on how to use [Ray to tune DistilBERT hyperparameters](https://huggingface.co/blog/ray-tune). +- A blog post on how to [train DistilBERT with Hugging Face and Amazon SageMaker](https://huggingface.co/blog/the-partnership-amazon-sagemaker-and-hugging-face). +- A notebook on how to [finetune DistilBERT for multi-label classification](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb). 🌎 +- A notebook on how to [finetune DistilBERT for multiclass classification with PyTorch](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb). 🌎 +- A notebook on how to [finetune DistilBERT for text classification in TensorFlow](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb). 🌎 +- [`DistilBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb). +- [`TFDistilBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb). +- [`FlaxDistilBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb). +- [Text classification task guide](../tasks/sequence_classification) + + + + +- [`DistilBertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb). +- [`TFDistilBertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb). +- [`FlaxDistilBertForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/token-classification). +- [Token classification](https://huggingface.co/course/chapter7/2?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Token classification task guide](../tasks/token_classification) + + + + +- [`DistilBertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFDistilBertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxDistilBertForMaskedLM`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). +- [Masked language modeling](https://huggingface.co/course/chapter7/3?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Masked language modeling task guide](../tasks/masked_language_modeling) + + + +- [`DistilBertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb). +- [`TFDistilBertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb). +- [`FlaxDistilBertForQuestionAnswering`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/question-answering). +- [Question answering](https://huggingface.co/course/chapter7/7?fw=pt) chapter of the 🤗 Hugging Face Course. +- [Question answering task guide](../tasks/question_answering) + +**Multiple choice** +- [`DistilBertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb). +- [`TFDistilBertForMultipleChoice`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb). +- [Multiple choice task guide](../tasks/multiple_choice) + +⚗️ Optimization + +- A blog post on how to [quantize DistilBERT with 🤗 Optimum and Intel](https://huggingface.co/blog/intel). +- A blog post on how [Optimizing Transformers for GPUs with 🤗 Optimum](https://www.philschmid.de/optimizing-transformers-with-optimum-gpu). +- A blog post on [Optimizing Transformers with Hugging Face Optimum](https://www.philschmid.de/optimizing-transformers-with-optimum). + +⚡️ Inference + +- A blog post on how to [Accelerate BERT inference with Hugging Face Transformers and AWS Inferentia](https://huggingface.co/blog/bert-inferentia-sagemaker) with DistilBERT. +- A blog post on [Serverless Inference with Hugging Face's Transformers, DistilBERT and Amazon SageMaker](https://www.philschmid.de/sagemaker-serverless-huggingface-distilbert). + +🚀 Deploy + +- A blog post on how to [deploy DistilBERT on Google Cloud](https://huggingface.co/blog/how-to-deploy-a-pipeline-to-google-clouds). +- A blog post on how to [deploy DistilBERT with Amazon SageMaker](https://huggingface.co/blog/deploy-hugging-face-models-easily-with-amazon-sagemaker). +- A blog post on how to [Deploy BERT with Hugging Face Transformers, Amazon SageMaker and Terraform module](https://www.philschmid.de/terraform-huggingface-amazon-sagemaker). + + +## Combining DistilBERT and Flash Attention 2 + +First, make sure to install the latest version of Flash Attention 2 to include the sliding window attention feature. + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of flash-attn repository. Make also sure to load your model in half-precision (e.g. `torch.float16`) + +To load and run a model using Flash Attention 2, refer to the snippet below: + +```python +>>> import torch +>>> from transformers import AutoTokenizer, AutoModel + +>>> device = "cuda" # the device to load the model onto + +>>> tokenizer = AutoTokenizer.from_pretrained('distilbert/distilbert-base-uncased') +>>> model = AutoModel.from_pretrained("distilbert/distilbert-base-uncased", torch_dtype=torch.float16, attn_implementation="flash_attention_2") + +>>> text = "Replace me by any text you'd like." + +>>> encoded_input = tokenizer(text, return_tensors='pt').to(device) +>>> model.to(device) + +>>> output = model(**encoded_input) +``` + + +## DistilBertConfig + +[[autodoc]] DistilBertConfig + +## DistilBertTokenizer + +[[autodoc]] DistilBertTokenizer + +## DistilBertTokenizerFast + +[[autodoc]] DistilBertTokenizerFast + + + + +## DistilBertModel + +[[autodoc]] DistilBertModel + - forward + +## DistilBertForMaskedLM + +[[autodoc]] DistilBertForMaskedLM + - forward + +## DistilBertForSequenceClassification + +[[autodoc]] DistilBertForSequenceClassification + - forward + +## DistilBertForMultipleChoice + +[[autodoc]] DistilBertForMultipleChoice + - forward + +## DistilBertForTokenClassification + +[[autodoc]] DistilBertForTokenClassification + - forward + +## DistilBertForQuestionAnswering + +[[autodoc]] DistilBertForQuestionAnswering + - forward + + + + +## TFDistilBertModel + +[[autodoc]] TFDistilBertModel + - call + +## TFDistilBertForMaskedLM + +[[autodoc]] TFDistilBertForMaskedLM + - call + +## TFDistilBertForSequenceClassification + +[[autodoc]] TFDistilBertForSequenceClassification + - call + +## TFDistilBertForMultipleChoice + +[[autodoc]] TFDistilBertForMultipleChoice + - call + +## TFDistilBertForTokenClassification + +[[autodoc]] TFDistilBertForTokenClassification + - call + +## TFDistilBertForQuestionAnswering + +[[autodoc]] TFDistilBertForQuestionAnswering + - call + + + + +## FlaxDistilBertModel + +[[autodoc]] FlaxDistilBertModel + - __call__ + +## FlaxDistilBertForMaskedLM + +[[autodoc]] FlaxDistilBertForMaskedLM + - __call__ + +## FlaxDistilBertForSequenceClassification + +[[autodoc]] FlaxDistilBertForSequenceClassification + - __call__ + +## FlaxDistilBertForMultipleChoice + +[[autodoc]] FlaxDistilBertForMultipleChoice + - __call__ + +## FlaxDistilBertForTokenClassification + +[[autodoc]] FlaxDistilBertForTokenClassification + - __call__ + +## FlaxDistilBertForQuestionAnswering + +[[autodoc]] FlaxDistilBertForQuestionAnswering + - __call__ + + + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dit.md new file mode 100644 index 0000000000000000000000000000000000000000..8848948375e85e5c7e1a68bf869a1469e467d4be --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dit.md @@ -0,0 +1,92 @@ + + +# DiT + +
+PyTorch +Flax +
+ +## Overview + +DiT was proposed in [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei. +DiT applies the self-supervised objective of [BEiT](beit) (BERT pre-training of Image Transformers) to 42 million document images, allowing for state-of-the-art results on tasks including: + +- document image classification: the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset (a collection of + 400,000 images belonging to one of 16 classes). +- document layout analysis: the [PubLayNet](https://github.com/ibm-aur-nlp/PubLayNet) dataset (a collection of more + than 360,000 document images constructed by automatically parsing PubMed XML files). +- table detection: the [ICDAR 2019 cTDaR](https://github.com/cndplab-founder/ICDAR2019_cTDaR) dataset (a collection of + 600 training images and 240 testing images). + +The abstract from the paper is the following: + +*Image Transformer has recently achieved significant progress for natural image understanding, either using supervised (ViT, DeiT, etc.) or self-supervised (BEiT, MAE, etc.) pre-training techniques. In this paper, we propose DiT, a self-supervised pre-trained Document Image Transformer model using large-scale unlabeled text images for Document AI tasks, which is essential since no supervised counterparts ever exist due to the lack of human labeled document images. We leverage DiT as the backbone network in a variety of vision-based Document AI tasks, including document image classification, document layout analysis, as well as table detection. Experiment results have illustrated that the self-supervised pre-trained DiT model achieves new state-of-the-art results on these downstream tasks, e.g. document image classification (91.11 → 92.69), document layout analysis (91.0 → 94.9) and table detection (94.23 → 96.55). * + + + + Summary of the approach. Taken from the [original paper](https://arxiv.org/abs/2203.02378). + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/dit). + +## Usage tips + +One can directly use the weights of DiT with the AutoModel API: + +```python +from transformers import AutoModel + +model = AutoModel.from_pretrained("microsoft/dit-base") +``` + +This will load the model pre-trained on masked image modeling. Note that this won't include the language modeling head on top, used to predict visual tokens. + +To include the head, you can load the weights into a `BeitForMaskedImageModeling` model, like so: + +```python +from transformers import BeitForMaskedImageModeling + +model = BeitForMaskedImageModeling.from_pretrained("microsoft/dit-base") +``` + +You can also load a fine-tuned model from the [hub](https://huggingface.co/models?other=dit), like so: + +```python +from transformers import AutoModelForImageClassification + +model = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip") +``` + +This particular checkpoint was fine-tuned on [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/), an important benchmark for document image classification. +A notebook that illustrates inference for document image classification can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DiT/Inference_with_DiT_(Document_Image_Transformer)_for_document_image_classification.ipynb). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DiT. + + + +- [`BeitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + + As DiT's architecture is equivalent to that of BEiT, one can refer to [BEiT's documentation page](beit) for all tips, code examples and notebooks. + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/donut.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/donut.md new file mode 100644 index 0000000000000000000000000000000000000000..6e5cfe648d0963577de3b93b236ce18b21765efb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/donut.md @@ -0,0 +1,217 @@ + + +# Donut + +## Overview + +The Donut model was proposed in [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by +Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park. +Donut consists of an image Transformer encoder and an autoregressive text Transformer decoder to perform document understanding +tasks such as document image classification, form understanding and visual question answering. + +The abstract from the paper is the following: + +*Understanding document images (e.g., invoices) is a core but challenging task since it requires complex functions such as reading text and a holistic understanding of the document. Current Visual Document Understanding (VDU) methods outsource the task of reading text to off-the-shelf Optical Character Recognition (OCR) engines and focus on the understanding task with the OCR outputs. Although such OCR-based approaches have shown promising performance, they suffer from 1) high computational costs for using OCR; 2) inflexibility of OCR models on languages or types of document; 3) OCR error propagation to the subsequent process. To address these issues, in this paper, we introduce a novel OCR-free VDU model named Donut, which stands for Document understanding transformer. As the first step in OCR-free VDU research, we propose a simple architecture (i.e., Transformer) with a pre-training objective (i.e., cross-entropy loss). Donut is conceptually simple yet effective. Through extensive experiments and analyses, we show a simple OCR-free VDU model, Donut, achieves state-of-the-art performances on various VDU tasks in terms of both speed and accuracy. In addition, we offer a synthetic data generator that helps the model pre-training to be flexible in various languages and domains.* + + + + Donut high-level overview. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found +[here](https://github.com/clovaai/donut). + +## Usage tips + +- The quickest way to get started with Donut is by checking the [tutorial + notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Donut), which show how to use the model + at inference time as well as fine-tuning on custom data. +- Donut is always used within the [VisionEncoderDecoder](vision-encoder-decoder) framework. + +## Inference examples + +Donut's [`VisionEncoderDecoder`] model accepts images as input and makes use of +[`~generation.GenerationMixin.generate`] to autoregressively generate text given the input image. + +The [`DonutImageProcessor`] class is responsible for preprocessing the input image and +[`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`] decodes the generated target tokens to the target string. The +[`DonutProcessor`] wraps [`DonutImageProcessor`] and [`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`] +into a single instance to both extract the input features and decode the predicted token ids. + +- Step-by-step Document Image Classification + +```py +>>> import re + +>>> from transformers import DonutProcessor, VisionEncoderDecoderModel +>>> from datasets import load_dataset +>>> import torch + +>>> processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip") +>>> model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip") + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model.to(device) # doctest: +IGNORE_RESULT + +>>> # load document image +>>> dataset = load_dataset("hf-internal-testing/example-documents", split="test") +>>> image = dataset[1]["image"] + +>>> # prepare decoder inputs +>>> task_prompt = "" +>>> decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids + +>>> pixel_values = processor(image, return_tensors="pt").pixel_values + +>>> outputs = model.generate( +... pixel_values.to(device), +... decoder_input_ids=decoder_input_ids.to(device), +... max_length=model.decoder.config.max_position_embeddings, +... pad_token_id=processor.tokenizer.pad_token_id, +... eos_token_id=processor.tokenizer.eos_token_id, +... use_cache=True, +... bad_words_ids=[[processor.tokenizer.unk_token_id]], +... return_dict_in_generate=True, +... ) + +>>> sequence = processor.batch_decode(outputs.sequences)[0] +>>> sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") +>>> sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token +>>> print(processor.token2json(sequence)) +{'class': 'advertisement'} +``` + +- Step-by-step Document Parsing + +```py +>>> import re + +>>> from transformers import DonutProcessor, VisionEncoderDecoderModel +>>> from datasets import load_dataset +>>> import torch + +>>> processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2") +>>> model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2") + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model.to(device) # doctest: +IGNORE_RESULT + +>>> # load document image +>>> dataset = load_dataset("hf-internal-testing/example-documents", split="test") +>>> image = dataset[2]["image"] + +>>> # prepare decoder inputs +>>> task_prompt = "" +>>> decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids + +>>> pixel_values = processor(image, return_tensors="pt").pixel_values + +>>> outputs = model.generate( +... pixel_values.to(device), +... decoder_input_ids=decoder_input_ids.to(device), +... max_length=model.decoder.config.max_position_embeddings, +... pad_token_id=processor.tokenizer.pad_token_id, +... eos_token_id=processor.tokenizer.eos_token_id, +... use_cache=True, +... bad_words_ids=[[processor.tokenizer.unk_token_id]], +... return_dict_in_generate=True, +... ) + +>>> sequence = processor.batch_decode(outputs.sequences)[0] +>>> sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") +>>> sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token +>>> print(processor.token2json(sequence)) +{'menu': {'nm': 'CINNAMON SUGAR', 'unitprice': '17,000', 'cnt': '1 x', 'price': '17,000'}, 'sub_total': {'subtotal_price': '17,000'}, 'total': {'total_price': '17,000', 'cashprice': '20,000', 'changeprice': '3,000'}} +``` + +- Step-by-step Document Visual Question Answering (DocVQA) + +```py +>>> import re + +>>> from transformers import DonutProcessor, VisionEncoderDecoderModel +>>> from datasets import load_dataset +>>> import torch + +>>> processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa") +>>> model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa") + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model.to(device) # doctest: +IGNORE_RESULT + +>>> # load document image from the DocVQA dataset +>>> dataset = load_dataset("hf-internal-testing/example-documents", split="test") +>>> image = dataset[0]["image"] + +>>> # prepare decoder inputs +>>> task_prompt = "{user_input}" +>>> question = "When is the coffee break?" +>>> prompt = task_prompt.replace("{user_input}", question) +>>> decoder_input_ids = processor.tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids + +>>> pixel_values = processor(image, return_tensors="pt").pixel_values + +>>> outputs = model.generate( +... pixel_values.to(device), +... decoder_input_ids=decoder_input_ids.to(device), +... max_length=model.decoder.config.max_position_embeddings, +... pad_token_id=processor.tokenizer.pad_token_id, +... eos_token_id=processor.tokenizer.eos_token_id, +... use_cache=True, +... bad_words_ids=[[processor.tokenizer.unk_token_id]], +... return_dict_in_generate=True, +... ) + +>>> sequence = processor.batch_decode(outputs.sequences)[0] +>>> sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") +>>> sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token +>>> print(processor.token2json(sequence)) +{'question': 'When is the coffee break?', 'answer': '11-14 to 11:39 a.m.'} +``` + +See the [model hub](https://huggingface.co/models?filter=donut) to look for Donut checkpoints. + +## Training + +We refer to the [tutorial notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Donut). + +## DonutSwinConfig + +[[autodoc]] DonutSwinConfig + +## DonutImageProcessor + +[[autodoc]] DonutImageProcessor + - preprocess + +## DonutFeatureExtractor + +[[autodoc]] DonutFeatureExtractor + - __call__ + +## DonutProcessor + +[[autodoc]] DonutProcessor + - __call__ + - from_pretrained + - save_pretrained + - batch_decode + - decode + +## DonutSwinModel + +[[autodoc]] DonutSwinModel + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpr.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpr.md new file mode 100644 index 0000000000000000000000000000000000000000..0f6b19c90014b0eef86c9c0c57cb115443ae79f7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpr.md @@ -0,0 +1,125 @@ + + +# DPR + +
+PyTorch +TensorFlow +SDPA +
+ +## Overview + +Dense Passage Retrieval (DPR) is a set of tools and models for state-of-the-art open-domain Q&A research. It was +introduced in [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by +Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen-tau Yih. + +The abstract from the paper is the following: + +*Open-domain question answering relies on efficient passage retrieval to select candidate contexts, where traditional +sparse vector space models, such as TF-IDF or BM25, are the de facto method. In this work, we show that retrieval can +be practically implemented using dense representations alone, where embeddings are learned from a small number of +questions and passages by a simple dual-encoder framework. When evaluated on a wide range of open-domain QA datasets, +our dense retriever outperforms a strong Lucene-BM25 system largely by 9%-19% absolute in terms of top-20 passage +retrieval accuracy, and helps our end-to-end QA system establish new state-of-the-art on multiple open-domain QA +benchmarks.* + +This model was contributed by [lhoestq](https://huggingface.co/lhoestq). The original code can be found [here](https://github.com/facebookresearch/DPR). + +## Usage tips + +- DPR consists in three models: + + * Question encoder: encode questions as vectors + * Context encoder: encode contexts as vectors + * Reader: extract the answer of the questions inside retrieved contexts, along with a relevance score (high if the inferred span actually answers the question). + +## DPRConfig + +[[autodoc]] DPRConfig + +## DPRContextEncoderTokenizer + +[[autodoc]] DPRContextEncoderTokenizer + +## DPRContextEncoderTokenizerFast + +[[autodoc]] DPRContextEncoderTokenizerFast + +## DPRQuestionEncoderTokenizer + +[[autodoc]] DPRQuestionEncoderTokenizer + +## DPRQuestionEncoderTokenizerFast + +[[autodoc]] DPRQuestionEncoderTokenizerFast + +## DPRReaderTokenizer + +[[autodoc]] DPRReaderTokenizer + +## DPRReaderTokenizerFast + +[[autodoc]] DPRReaderTokenizerFast + +## DPR specific outputs + +[[autodoc]] models.dpr.modeling_dpr.DPRContextEncoderOutput + +[[autodoc]] models.dpr.modeling_dpr.DPRQuestionEncoderOutput + +[[autodoc]] models.dpr.modeling_dpr.DPRReaderOutput + + + + +## DPRContextEncoder + +[[autodoc]] DPRContextEncoder + - forward + +## DPRQuestionEncoder + +[[autodoc]] DPRQuestionEncoder + - forward + +## DPRReader + +[[autodoc]] DPRReader + - forward + + + + +## TFDPRContextEncoder + +[[autodoc]] TFDPRContextEncoder + - call + +## TFDPRQuestionEncoder + +[[autodoc]] TFDPRQuestionEncoder + - call + +## TFDPRReader + +[[autodoc]] TFDPRReader + - call + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpt.md new file mode 100644 index 0000000000000000000000000000000000000000..7010d03cdc684d752818f54f14c782f556b53c1d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/dpt.md @@ -0,0 +1,94 @@ + + +# DPT + +
+PyTorch +
+ +## Overview + +The DPT model was proposed in [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun. +DPT is a model that leverages the [Vision Transformer (ViT)](vit) as backbone for dense prediction tasks like semantic segmentation and depth estimation. + +The abstract from the paper is the following: + +*We introduce dense vision transformers, an architecture that leverages vision transformers in place of convolutional networks as a backbone for dense prediction tasks. We assemble tokens from various stages of the vision transformer into image-like representations at various resolutions and progressively combine them into full-resolution predictions using a convolutional decoder. The transformer backbone processes representations at a constant and relatively high resolution and has a global receptive field at every stage. These properties allow the dense vision transformer to provide finer-grained and more globally coherent predictions when compared to fully-convolutional networks. Our experiments show that this architecture yields substantial improvements on dense prediction tasks, especially when a large amount of training data is available. For monocular depth estimation, we observe an improvement of up to 28% in relative performance when compared to a state-of-the-art fully-convolutional network. When applied to semantic segmentation, dense vision transformers set a new state of the art on ADE20K with 49.02% mIoU. We further show that the architecture can be fine-tuned on smaller datasets such as NYUv2, KITTI, and Pascal Context where it also sets the new state of the art.* + + + + DPT architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/isl-org/DPT). + +## Usage tips + +DPT is compatible with the [`AutoBackbone`] class. This allows to use the DPT framework with various computer vision backbones available in the library, such as [`VitDetBackbone`] or [`Dinov2Backbone`]. One can create it as follows: + +```python +from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation + +# initialize with a Transformer-based backbone such as DINOv2 +# in that case, we also specify `reshape_hidden_states=False` to get feature maps of shape (batch_size, num_channels, height, width) +backbone_config = Dinov2Config.from_pretrained("facebook/dinov2-base", out_features=["stage1", "stage2", "stage3", "stage4"], reshape_hidden_states=False) + +config = DPTConfig(backbone_config=backbone_config) +model = DPTForDepthEstimation(config=config) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DPT. + +- Demo notebooks for [`DPTForDepthEstimation`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DPT). + +- [Semantic segmentation task guide](../tasks/semantic_segmentation) +- [Monocular depth estimation task guide](../tasks/monocular_depth_estimation) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## DPTConfig + +[[autodoc]] DPTConfig + +## DPTFeatureExtractor + +[[autodoc]] DPTFeatureExtractor + - __call__ + - post_process_semantic_segmentation + +## DPTImageProcessor + +[[autodoc]] DPTImageProcessor + - preprocess + - post_process_semantic_segmentation + +## DPTModel + +[[autodoc]] DPTModel + - forward + +## DPTForDepthEstimation + +[[autodoc]] DPTForDepthEstimation + - forward + +## DPTForSemanticSegmentation + +[[autodoc]] DPTForSemanticSegmentation + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientformer.md new file mode 100644 index 0000000000000000000000000000000000000000..f05ccacc3dbf596ad590ce001b9b3480565bed90 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientformer.md @@ -0,0 +1,109 @@ + + +# EfficientFormer + +
+PyTorch +TensorFlow +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The EfficientFormer model was proposed in [EfficientFormer: Vision Transformers at MobileNet Speed](https://arxiv.org/abs/2206.01191) +by Yanyu Li, Geng Yuan, Yang Wen, Eric Hu, Georgios Evangelidis, Sergey Tulyakov, Yanzhi Wang, Jian Ren. EfficientFormer proposes a +dimension-consistent pure transformer that can be run on mobile devices for dense prediction tasks like image classification, object +detection and semantic segmentation. + +The abstract from the paper is the following: + +*Vision Transformers (ViT) have shown rapid progress in computer vision tasks, achieving promising results on various benchmarks. +However, due to the massive number of parameters and model design, e.g., attention mechanism, ViT-based models are generally +times slower than lightweight convolutional networks. Therefore, the deployment of ViT for real-time applications is particularly +challenging, especially on resource-constrained hardware such as mobile devices. Recent efforts try to reduce the computation +complexity of ViT through network architecture search or hybrid design with MobileNet block, yet the inference speed is still +unsatisfactory. This leads to an important question: can transformers run as fast as MobileNet while obtaining high performance? +To answer this, we first revisit the network architecture and operators used in ViT-based models and identify inefficient designs. +Then we introduce a dimension-consistent pure transformer (without MobileNet blocks) as a design paradigm. +Finally, we perform latency-driven slimming to get a series of final models dubbed EfficientFormer. +Extensive experiments show the superiority of EfficientFormer in performance and speed on mobile devices. +Our fastest model, EfficientFormer-L1, achieves 79.2% top-1 accuracy on ImageNet-1K with only 1.6 ms inference latency on +iPhone 12 (compiled with CoreML), which { runs as fast as MobileNetV2×1.4 (1.6 ms, 74.7% top-1),} and our largest model, +EfficientFormer-L7, obtains 83.3% accuracy with only 7.0 ms latency. Our work proves that properly designed transformers can +reach extremely low latency on mobile devices while maintaining high performance.* + +This model was contributed by [novice03](https://huggingface.co/novice03) and [Bearnardd](https://huggingface.co/Bearnardd). +The original code can be found [here](https://github.com/snap-research/EfficientFormer). The TensorFlow version of this model was added by [D-Roberts](https://huggingface.co/D-Roberts). + +## Documentation resources + +- [Image classification task guide](../tasks/image_classification) + +## EfficientFormerConfig + +[[autodoc]] EfficientFormerConfig + +## EfficientFormerImageProcessor + +[[autodoc]] EfficientFormerImageProcessor + - preprocess + + + + +## EfficientFormerModel + +[[autodoc]] EfficientFormerModel + - forward + +## EfficientFormerForImageClassification + +[[autodoc]] EfficientFormerForImageClassification + - forward + +## EfficientFormerForImageClassificationWithTeacher + +[[autodoc]] EfficientFormerForImageClassificationWithTeacher + - forward + + + + +## TFEfficientFormerModel + +[[autodoc]] TFEfficientFormerModel + - call + +## TFEfficientFormerForImageClassification + +[[autodoc]] TFEfficientFormerForImageClassification + - call + +## TFEfficientFormerForImageClassificationWithTeacher + +[[autodoc]] TFEfficientFormerForImageClassificationWithTeacher + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientnet.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientnet.md new file mode 100644 index 0000000000000000000000000000000000000000..a34378fa4709bcc49f7a8f95f9f771a729788e94 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/efficientnet.md @@ -0,0 +1,55 @@ + + +# EfficientNet + +
+PyTorch +
+ +## Overview + +The EfficientNet model was proposed in [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) +by Mingxing Tan and Quoc V. Le. EfficientNets are a family of image classification models, which achieve state-of-the-art accuracy, yet being an order-of-magnitude smaller and faster than previous models. + +The abstract from the paper is the following: + +*Convolutional Neural Networks (ConvNets) are commonly developed at a fixed resource budget, and then scaled up for better accuracy if more resources are available. In this paper, we systematically study model scaling and identify that carefully balancing network depth, width, and resolution can lead to better performance. Based on this observation, we propose a new scaling method that uniformly scales all dimensions of depth/width/resolution using a simple yet highly effective compound coefficient. We demonstrate the effectiveness of this method on scaling up MobileNets and ResNet. +To go even further, we use neural architecture search to design a new baseline network and scale it up to obtain a family of models, called EfficientNets, which achieve much better accuracy and efficiency than previous ConvNets. In particular, our EfficientNet-B7 achieves state-of-the-art 84.3% top-1 accuracy on ImageNet, while being 8.4x smaller and 6.1x faster on inference than the best existing ConvNet. Our EfficientNets also transfer well and achieve state-of-the-art accuracy on CIFAR-100 (91.7%), Flowers (98.8%), and 3 other transfer learning datasets, with an order of magnitude fewer parameters.* + +This model was contributed by [adirik](https://huggingface.co/adirik). +The original code can be found [here](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet). + + +## EfficientNetConfig + +[[autodoc]] EfficientNetConfig + +## EfficientNetImageProcessor + +[[autodoc]] EfficientNetImageProcessor + - preprocess + +## EfficientNetModel + +[[autodoc]] EfficientNetModel + - forward + +## EfficientNetForImageClassification + +[[autodoc]] EfficientNetForImageClassification + - forward + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/electra.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/electra.md new file mode 100644 index 0000000000000000000000000000000000000000..bee883d64153d2b008b2b2dc1be0a9dffe4ef5ca --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/electra.md @@ -0,0 +1,221 @@ + + +# ELECTRA + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The ELECTRA model was proposed in the paper [ELECTRA: Pre-training Text Encoders as Discriminators Rather Than +Generators](https://openreview.net/pdf?id=r1xMH1BtvB). ELECTRA is a new pretraining approach which trains two +transformer models: the generator and the discriminator. The generator's role is to replace tokens in a sequence, and +is therefore trained as a masked language model. The discriminator, which is the model we're interested in, tries to +identify which tokens were replaced by the generator in the sequence. + +The abstract from the paper is the following: + +*Masked language modeling (MLM) pretraining methods such as BERT corrupt the input by replacing some tokens with [MASK] +and then train a model to reconstruct the original tokens. While they produce good results when transferred to +downstream NLP tasks, they generally require large amounts of compute to be effective. As an alternative, we propose a +more sample-efficient pretraining task called replaced token detection. Instead of masking the input, our approach +corrupts it by replacing some tokens with plausible alternatives sampled from a small generator network. Then, instead +of training a model that predicts the original identities of the corrupted tokens, we train a discriminative model that +predicts whether each token in the corrupted input was replaced by a generator sample or not. Thorough experiments +demonstrate this new pretraining task is more efficient than MLM because the task is defined over all input tokens +rather than just the small subset that was masked out. As a result, the contextual representations learned by our +approach substantially outperform the ones learned by BERT given the same model size, data, and compute. The gains are +particularly strong for small models; for example, we train a model on one GPU for 4 days that outperforms GPT (trained +using 30x more compute) on the GLUE natural language understanding benchmark. Our approach also works well at scale, +where it performs comparably to RoBERTa and XLNet while using less than 1/4 of their compute and outperforms them when +using the same amount of compute.* + +This model was contributed by [lysandre](https://huggingface.co/lysandre). The original code can be found [here](https://github.com/google-research/electra). + +## Usage tips + +- ELECTRA is the pretraining approach, therefore there is nearly no changes done to the underlying model: BERT. The + only change is the separation of the embedding size and the hidden size: the embedding size is generally smaller, + while the hidden size is larger. An additional projection layer (linear) is used to project the embeddings from their + embedding size to the hidden size. In the case where the embedding size is the same as the hidden size, no projection + layer is used. +- ELECTRA is a transformer model pretrained with the use of another (small) masked language model. The inputs are corrupted by that language model, which takes an input text that is randomly masked and outputs a text in which ELECTRA has to predict which token is an original and which one has been replaced. Like for GAN training, the small language model is trained for a few steps (but with the original texts as objective, not to fool the ELECTRA model like in a traditional GAN setting) then the ELECTRA model is trained for a few steps. +- The ELECTRA checkpoints saved using [Google Research's implementation](https://github.com/google-research/electra) + contain both the generator and discriminator. The conversion script requires the user to name which model to export + into the correct architecture. Once converted to the HuggingFace format, these checkpoints may be loaded into all + available ELECTRA models, however. This means that the discriminator may be loaded in the + [`ElectraForMaskedLM`] model, and the generator may be loaded in the + [`ElectraForPreTraining`] model (the classification head will be randomly initialized as it + doesn't exist in the generator). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## ElectraConfig + +[[autodoc]] ElectraConfig + +## ElectraTokenizer + +[[autodoc]] ElectraTokenizer + +## ElectraTokenizerFast + +[[autodoc]] ElectraTokenizerFast + +## Electra specific outputs + +[[autodoc]] models.electra.modeling_electra.ElectraForPreTrainingOutput + +[[autodoc]] models.electra.modeling_tf_electra.TFElectraForPreTrainingOutput + + + + +## ElectraModel + +[[autodoc]] ElectraModel + - forward + +## ElectraForPreTraining + +[[autodoc]] ElectraForPreTraining + - forward + +## ElectraForCausalLM + +[[autodoc]] ElectraForCausalLM + - forward + +## ElectraForMaskedLM + +[[autodoc]] ElectraForMaskedLM + - forward + +## ElectraForSequenceClassification + +[[autodoc]] ElectraForSequenceClassification + - forward + +## ElectraForMultipleChoice + +[[autodoc]] ElectraForMultipleChoice + - forward + +## ElectraForTokenClassification + +[[autodoc]] ElectraForTokenClassification + - forward + +## ElectraForQuestionAnswering + +[[autodoc]] ElectraForQuestionAnswering + - forward + + + + +## TFElectraModel + +[[autodoc]] TFElectraModel + - call + +## TFElectraForPreTraining + +[[autodoc]] TFElectraForPreTraining + - call + +## TFElectraForMaskedLM + +[[autodoc]] TFElectraForMaskedLM + - call + +## TFElectraForSequenceClassification + +[[autodoc]] TFElectraForSequenceClassification + - call + +## TFElectraForMultipleChoice + +[[autodoc]] TFElectraForMultipleChoice + - call + +## TFElectraForTokenClassification + +[[autodoc]] TFElectraForTokenClassification + - call + +## TFElectraForQuestionAnswering + +[[autodoc]] TFElectraForQuestionAnswering + - call + + + + +## FlaxElectraModel + +[[autodoc]] FlaxElectraModel + - __call__ + +## FlaxElectraForPreTraining + +[[autodoc]] FlaxElectraForPreTraining + - __call__ + +## FlaxElectraForCausalLM + +[[autodoc]] FlaxElectraForCausalLM + - __call__ + +## FlaxElectraForMaskedLM + +[[autodoc]] FlaxElectraForMaskedLM + - __call__ + +## FlaxElectraForSequenceClassification + +[[autodoc]] FlaxElectraForSequenceClassification + - __call__ + +## FlaxElectraForMultipleChoice + +[[autodoc]] FlaxElectraForMultipleChoice + - __call__ + +## FlaxElectraForTokenClassification + +[[autodoc]] FlaxElectraForTokenClassification + - __call__ + +## FlaxElectraForQuestionAnswering + +[[autodoc]] FlaxElectraForQuestionAnswering + - __call__ + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/emu3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/emu3.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac7d0b0c4f1ae161a49dfe95d1269024f6ca7d7 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/emu3.md @@ -0,0 +1,185 @@ + + +# Emu3 + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Emu3 model was proposed in [Emu3: Next-Token Prediction is All You Need](https://arxiv.org/abs/2409.18869) by Xinlong Wang, Xiaosong Zhang, Zhengxiong Luo, Quan Sun, Yufeng Cui, Jinsheng Wang, Fan Zhang, Yueze Wang, Zhen Li, Qiying Yu, Yingli Zhao, Yulong Ao, Xuebin Min, Tao Li, Boya Wu, Bo Zhao, Bowen Zhang, Liangdong Wang, Guang Liu, Zheqi He, Xi Yang, Jingjing Liu, Yonghua Lin, Tiejun Huang, Zhongyuan Wang. + +Emu3 is a multimodal LLM that uses vector quantization to tokenize images into discrete tokens. Discretized image tokens are later fused with text token ids for image and text generation. The model can additionally generate images by predicting image token ids. + + +The abstract from the paper is the following: + +*While next-token prediction is considered a promising path towards artificial general intelligence, it has struggled to excel in multimodal tasks, which are still dominated by diffusion models (e.g., Stable Diffusion) and compositional approaches (e.g., CLIP combined with LLMs). In this paper, we introduce Emu3, a new suite of state-of-the-art multimodal models trained solely with next-token prediction. By tokenizing images, text, and videos into a discrete space, we train a single transformer from scratch on a mixture of multimodal sequences. Emu3 outperforms several well-established task-specific models in both generation and perception tasks, surpassing flagship models such as SDXL and LLaVA-1.6, while eliminating the need for diffusion or compositional architectures. Emu3 is also capable of generating high-fidelity video via predicting the next token in a video sequence. We simplify complex multimodal model designs by converging on a singular focus: tokens, unlocking great potential for scaling both during training and inference. Our results demonstrate that next-token prediction is a promising path towards building general multimodal intelligence beyond language. We open-source key techniques and models to support further research in this direction.* + +Tips: + +- We advise users to set `processor.tokenizer.padding_side = "left"` before batched generation as it leads to more accurate results. + +- Note that the model has been trained with a specific prompt format for chatting. Use `processor.apply_chat_template(my_conversation_dict)` to correctly format your prompts. + +- Emu3 has two different checkpoints for image-generation and text-generation, make sure to use the correct checkpoint when loading the model. To generate an image, it is advised to use `prefix_constraints` so that the generated tokens are sampled only from possible image tokens. See more below for usage examples. + +> [!TIP] +> Emu3 implementation in Transformers uses a special image token to indicate where to merge image embeddings. The special image token isn't new and uses one of the reserved tokens: `<|extra_0|>`. You have to add `` to your prompt in the place where the image should be embedded for correct generation. + + +This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/baaivision/Emu3). + + +## Usage example + +### Text generation inference + +Here's how to load the model and perform inference in half-precision (`torch.bfloat16`) to generate textual output from text or text and image inputs: + +```python +from transformers import Emu3Processor, Emu3ForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") +model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16, device_map="cuda") + +# prepare image and text prompt +url = 'http://images.cocodataset.org/val2017/000000039769.jpg' +image = Image.open(requests.get(url, stream=True).raw) +prompt = "What do you see in this image?" + +inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=50) +print(processor.decode(output[0], skip_special_tokens=True)) +``` + +### Image generation inference + +Emu3 can also generate images from textual input. Here is how you can do it: + +```python +processor = Emu3Processor.from_pretrained("BAAI/Emu3-Gen-hf") +model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Gen-hf", torch_dtype="bfloat16", device_map="auto", attn_implementation="flash_attention_2") + + +inputs = processor( + text=["a portrait of young girl. masterpiece, film grained, best quality.", "a dog running under the rain"], + padding=True, + return_tensors="pt", + return_for_image_generation=True, +) +inputs = inputs.to(device="cuda:0", dtype=torch.bfloat16) + +neg_prompt = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry." +neg_inputs = processor(text=[neg_prompt] * 2, return_tensors="pt").to(device="cuda:0") + +image_sizes = inputs.pop("image_sizes") +HEIGHT, WIDTH = image_sizes[0] +VISUAL_TOKENS = model.vocabulary_mapping.image_tokens + +def prefix_allowed_tokens_fn(batch_id, input_ids): + height, width = HEIGHT, WIDTH + visual_tokens = VISUAL_TOKENS + image_wrapper_token_id = torch.tensor([processor.tokenizer.image_wrapper_token_id], device=model.device) + eoi_token_id = torch.tensor([processor.tokenizer.eoi_token_id], device=model.device) + eos_token_id = torch.tensor([processor.tokenizer.eos_token_id], device=model.device) + pad_token_id = torch.tensor([processor.tokenizer.pad_token_id], device=model.device) + eof_token_id = torch.tensor([processor.tokenizer.eof_token_id], device=model.device) + eol_token_id = processor.tokenizer.encode("<|extra_200|>", return_tensors="pt")[0] + + position = torch.nonzero(input_ids == image_wrapper_token_id, as_tuple=True)[0][0] + offset = input_ids.shape[0] - position + if offset % (width + 1) == 0: + return (eol_token_id, ) + elif offset == (width + 1) * height + 1: + return (eof_token_id, ) + elif offset == (width + 1) * height + 2: + return (eoi_token_id, ) + elif offset == (width + 1) * height + 3: + return (eos_token_id, ) + elif offset > (width + 1) * height + 3: + return (pad_token_id, ) + else: + return visual_tokens + + +out = model.generate( + **inputs, + max_new_tokens=50_000, # make sure to have enough tokens for one image + prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, + return_dict_in_generate=True, + negative_prompt_ids=neg_inputs.input_ids, # indicate for Classifier-Free Guidance + negative_prompt_attention_mask=neg_inputs.attention_mask, +) + +image = model.decode_image_tokens(out.sequences[:, inputs.input_ids.shape[1]: ], height=HEIGHT, width=WIDTH) +images = processor.postprocess(list(image.float()), return_tensors="PIL.Image.Image") # internally we convert to np but it's not supported in bf16 precision +for i, image in enumerate(images['pixel_values']): + image.save(f"result{i}.png") + +``` + + +## Emu3Config + +[[autodoc]] Emu3Config + +## Emu3VQVAEConfig + +[[autodoc]] Emu3VQVAEConfig + +## Emu3TextConfig + +[[autodoc]] Emu3TextConfig + +## Emu3Processor + +[[autodoc]] Emu3Processor + +## Emu3ImageProcessor + +[[autodoc]] Emu3ImageProcessor + - preprocess + +## Emu3VQVAE + +[[autodoc]] Emu3VQVAE + - forward + +## Emu3TextModel + +[[autodoc]] Emu3TextModel + - forward + +## Emu3ForCausalLM + +[[autodoc]] Emu3ForCausalLM + - forward + +## Emu3ForConditionalGeneration + +[[autodoc]] Emu3ForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encodec.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encodec.md new file mode 100644 index 0000000000000000000000000000000000000000..893954d5cf867d54c2578960e7a3b4c71b56b6f0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encodec.md @@ -0,0 +1,69 @@ + + +# EnCodec + +
+PyTorch +
+ +## Overview + +The EnCodec neural codec model was proposed in [High Fidelity Neural Audio Compression](https://arxiv.org/abs/2210.13438) by Alexandre Défossez, Jade Copet, Gabriel Synnaeve, Yossi Adi. + +The abstract from the paper is the following: + +*We introduce a state-of-the-art real-time, high-fidelity, audio codec leveraging neural networks. It consists in a streaming encoder-decoder architecture with quantized latent space trained in an end-to-end fashion. We simplify and speed-up the training by using a single multiscale spectrogram adversary that efficiently reduces artifacts and produce high-quality samples. We introduce a novel loss balancer mechanism to stabilize training: the weight of a loss now defines the fraction of the overall gradient it should represent, thus decoupling the choice of this hyper-parameter from the typical scale of the loss. Finally, we study how lightweight Transformer models can be used to further compress the obtained representation by up to 40%, while staying faster than real time. We provide a detailed description of the key design choices of the proposed model including: training objective, architectural changes and a study of various perceptual loss functions. We present an extensive subjective evaluation (MUSHRA tests) together with an ablation study for a range of bandwidths and audio domains, including speech, noisy-reverberant speech, and music. Our approach is superior to the baselines methods across all evaluated settings, considering both 24 kHz monophonic and 48 kHz stereophonic audio.* + +This model was contributed by [Matthijs](https://huggingface.co/Matthijs), [Patrick Von Platen](https://huggingface.co/patrickvonplaten) and [Arthur Zucker](https://huggingface.co/ArthurZ). +The original code can be found [here](https://github.com/facebookresearch/encodec). + +## Usage example + +Here is a quick example of how to encode and decode an audio using this model: + +```python +>>> from datasets import load_dataset, Audio +>>> from transformers import EncodecModel, AutoProcessor +>>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +>>> model = EncodecModel.from_pretrained("facebook/encodec_24khz") +>>> processor = AutoProcessor.from_pretrained("facebook/encodec_24khz") +>>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=processor.sampling_rate)) +>>> audio_sample = librispeech_dummy[-1]["audio"]["array"] +>>> inputs = processor(raw_audio=audio_sample, sampling_rate=processor.sampling_rate, return_tensors="pt") + +>>> encoder_outputs = model.encode(inputs["input_values"], inputs["padding_mask"]) +>>> audio_values = model.decode(encoder_outputs.audio_codes, encoder_outputs.audio_scales, inputs["padding_mask"])[0] +>>> # or the equivalent with a forward pass +>>> audio_values = model(inputs["input_values"], inputs["padding_mask"]).audio_values +``` + +## EncodecConfig + +[[autodoc]] EncodecConfig + +## EncodecFeatureExtractor + +[[autodoc]] EncodecFeatureExtractor + - __call__ + +## EncodecModel + +[[autodoc]] EncodecModel + - decode + - encode + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encoder-decoder.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encoder-decoder.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a676fb33a6d6c60e006f60976a8fa8ee26e00e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/encoder-decoder.md @@ -0,0 +1,188 @@ + + +# Encoder Decoder Models + +
+PyTorch +TensorFlow +Flax +SDPA +
+ +## Overview + +The [`EncoderDecoderModel`] can be used to initialize a sequence-to-sequence model with any +pretrained autoencoding model as the encoder and any pretrained autoregressive model as the decoder. + +The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation tasks +was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by +Sascha Rothe, Shashi Narayan, Aliaksei Severyn. + +After such an [`EncoderDecoderModel`] has been trained/fine-tuned, it can be saved/loaded just like +any other models (see the examples for more information). + +An application of this architecture could be to leverage two pretrained [`BertModel`] as the encoder +and decoder for a summarization model as was shown in: [Text Summarization with Pretrained Encoders](https://arxiv.org/abs/1908.08345) by Yang Liu and Mirella Lapata. + +## Randomly initializing `EncoderDecoderModel` from model configurations. + +[`EncoderDecoderModel`] can be randomly initialized from an encoder and a decoder config. In the following example, we show how to do this using the default [`BertModel`] configuration for the encoder and the default [`BertForCausalLM`] configuration for the decoder. + +```python +>>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel + +>>> config_encoder = BertConfig() +>>> config_decoder = BertConfig() + +>>> config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder) +>>> model = EncoderDecoderModel(config=config) +``` + +## Initialising `EncoderDecoderModel` from a pretrained encoder and a pretrained decoder. + +[`EncoderDecoderModel`] can be initialized from a pretrained encoder checkpoint and a pretrained decoder checkpoint. Note that any pretrained auto-encoding model, *e.g.* BERT, can serve as the encoder and both pretrained auto-encoding models, *e.g.* BERT, pretrained causal language models, *e.g.* GPT2, as well as the pretrained decoder part of sequence-to-sequence models, *e.g.* decoder of BART, can be used as the decoder. +Depending on which architecture you choose as the decoder, the cross-attention layers might be randomly initialized. +Initializing [`EncoderDecoderModel`] from a pretrained encoder and decoder checkpoint requires the model to be fine-tuned on a downstream task, as has been shown in [the *Warm-starting-encoder-decoder blog post*](https://huggingface.co/blog/warm-starting-encoder-decoder). +To do so, the `EncoderDecoderModel` class provides a [`EncoderDecoderModel.from_encoder_decoder_pretrained`] method. + +```python +>>> from transformers import EncoderDecoderModel, BertTokenizer + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> model = EncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "google-bert/bert-base-uncased") +``` + +## Loading an existing `EncoderDecoderModel` checkpoint and perform inference. + +To load fine-tuned checkpoints of the `EncoderDecoderModel` class, [`EncoderDecoderModel`] provides the `from_pretrained(...)` method just like any other model architecture in Transformers. + +To perform inference, one uses the [`generate`] method, which allows to autoregressively generate text. This method supports various forms of decoding, such as greedy, beam search and multinomial sampling. + +```python +>>> from transformers import AutoTokenizer, EncoderDecoderModel + +>>> # load a fine-tuned seq2seq model and corresponding tokenizer +>>> model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert_cnn_daily_mail") +>>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/bert2bert_cnn_daily_mail") + +>>> # let's perform inference on a long piece of text +>>> ARTICLE_TO_SUMMARIZE = ( +... "PG&E stated it scheduled the blackouts in response to forecasts for high winds " +... "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were " +... "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow." +... ) +>>> input_ids = tokenizer(ARTICLE_TO_SUMMARIZE, return_tensors="pt").input_ids + +>>> # autoregressively generate summary (uses greedy decoding by default) +>>> generated_ids = model.generate(input_ids) +>>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +>>> print(generated_text) +nearly 800 thousand customers were affected by the shutoffs. the aim is to reduce the risk of wildfires. nearly 800, 000 customers were expected to be affected by high winds amid dry conditions. pg & e said it scheduled the blackouts to last through at least midday tomorrow. +``` + +## Loading a PyTorch checkpoint into `TFEncoderDecoderModel`. + +[`TFEncoderDecoderModel.from_pretrained`] currently doesn't support initializing the model from a +pytorch checkpoint. Passing `from_pt=True` to this method will throw an exception. If there are only pytorch +checkpoints for a particular encoder-decoder model, a workaround is: + +```python +>>> # a workaround to load from pytorch checkpoint +>>> from transformers import EncoderDecoderModel, TFEncoderDecoderModel + +>>> _model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16") + +>>> _model.encoder.save_pretrained("./encoder") +>>> _model.decoder.save_pretrained("./decoder") + +>>> model = TFEncoderDecoderModel.from_encoder_decoder_pretrained( +... "./encoder", "./decoder", encoder_from_pt=True, decoder_from_pt=True +... ) +>>> # This is only for copying some specific attributes of this particular model. +>>> model.config = _model.config +``` + +## Training + +Once the model is created, it can be fine-tuned similar to BART, T5 or any other encoder-decoder model. +As you can see, only 2 inputs are required for the model in order to compute a loss: `input_ids` (which are the +`input_ids` of the encoded input sequence) and `labels` (which are the `input_ids` of the encoded +target sequence). + +```python +>>> from transformers import BertTokenizer, EncoderDecoderModel + +>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") +>>> model = EncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "google-bert/bert-base-uncased") + +>>> model.config.decoder_start_token_id = tokenizer.cls_token_id +>>> model.config.pad_token_id = tokenizer.pad_token_id + +>>> input_ids = tokenizer( +... "The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side.During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft).Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France after the Millau Viaduct.", +... return_tensors="pt", +... ).input_ids + +>>> labels = tokenizer( +... "the eiffel tower surpassed the washington monument to become the tallest structure in the world. it was the first structure to reach a height of 300 metres in paris in 1930. it is now taller than the chrysler building by 5. 2 metres ( 17 ft ) and is the second tallest free - standing structure in paris.", +... return_tensors="pt", +... ).input_ids + +>>> # the forward function automatically creates the correct decoder_input_ids +>>> loss = model(input_ids=input_ids, labels=labels).loss +``` + +Detailed [colab](https://colab.research.google.com/drive/1WIk2bxglElfZewOHboPFNj8H44_VAyKE?usp=sharing#scrollTo=ZwQIEhKOrJpl) for training. + +This model was contributed by [thomwolf](https://github.com/thomwolf). This model's TensorFlow and Flax versions +were contributed by [ydshieh](https://github.com/ydshieh). + + +## EncoderDecoderConfig + +[[autodoc]] EncoderDecoderConfig + + + + +## EncoderDecoderModel + +[[autodoc]] EncoderDecoderModel + - forward + - from_encoder_decoder_pretrained + + + + +## TFEncoderDecoderModel + +[[autodoc]] TFEncoderDecoderModel + - call + - from_encoder_decoder_pretrained + + + + +## FlaxEncoderDecoderModel + +[[autodoc]] FlaxEncoderDecoderModel + - __call__ + - from_encoder_decoder_pretrained + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie.md new file mode 100644 index 0000000000000000000000000000000000000000..82f2a0d5ba817fc38f7db64b696e97980e760b3a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie.md @@ -0,0 +1,119 @@ + + +# ERNIE + +
+PyTorch +
+ +## Overview +ERNIE is a series of powerful models proposed by baidu, especially in Chinese tasks, +including [ERNIE1.0](https://arxiv.org/abs/1904.09223), [ERNIE2.0](https://ojs.aaai.org/index.php/AAAI/article/view/6428), +[ERNIE3.0](https://arxiv.org/abs/2107.02137), [ERNIE-Gram](https://arxiv.org/abs/2010.12148), [ERNIE-health](https://arxiv.org/abs/2110.07244), etc. + +These models are contributed by [nghuyong](https://huggingface.co/nghuyong) and the official code can be found in [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) (in PaddlePaddle). + +### Usage example +Take `ernie-1.0-base-zh` as an example: + +```Python +from transformers import AutoTokenizer, AutoModel +tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh") +model = AutoModel.from_pretrained("nghuyong/ernie-1.0-base-zh") +``` + +### Model checkpoints + +| Model Name | Language | Description | +|:-------------------:|:--------:|:-------------------------------:| +| ernie-1.0-base-zh | Chinese | Layer:12, Heads:12, Hidden:768 | +| ernie-2.0-base-en | English | Layer:12, Heads:12, Hidden:768 | +| ernie-2.0-large-en | English | Layer:24, Heads:16, Hidden:1024 | +| ernie-3.0-base-zh | Chinese | Layer:12, Heads:12, Hidden:768 | +| ernie-3.0-medium-zh | Chinese | Layer:6, Heads:12, Hidden:768 | +| ernie-3.0-mini-zh | Chinese | Layer:6, Heads:12, Hidden:384 | +| ernie-3.0-micro-zh | Chinese | Layer:4, Heads:12, Hidden:384 | +| ernie-3.0-nano-zh | Chinese | Layer:4, Heads:12, Hidden:312 | +| ernie-health-zh | Chinese | Layer:12, Heads:12, Hidden:768 | +| ernie-gram-zh | Chinese | Layer:12, Heads:12, Hidden:768 | + +You can find all the supported models from huggingface's model hub: [huggingface.co/nghuyong](https://huggingface.co/nghuyong), and model details from paddle's official +repo: [PaddleNLP](https://paddlenlp.readthedocs.io/zh/latest/model_zoo/transformers/ERNIE/contents.html) +and [ERNIE](https://github.com/PaddlePaddle/ERNIE/blob/repro). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## ErnieConfig + +[[autodoc]] ErnieConfig + - all + +## Ernie specific outputs + +[[autodoc]] models.ernie.modeling_ernie.ErnieForPreTrainingOutput + +## ErnieModel + +[[autodoc]] ErnieModel + - forward + +## ErnieForPreTraining + +[[autodoc]] ErnieForPreTraining + - forward + +## ErnieForCausalLM + +[[autodoc]] ErnieForCausalLM + - forward + +## ErnieForMaskedLM + +[[autodoc]] ErnieForMaskedLM + - forward + +## ErnieForNextSentencePrediction + +[[autodoc]] ErnieForNextSentencePrediction + - forward + +## ErnieForSequenceClassification + +[[autodoc]] ErnieForSequenceClassification + - forward + +## ErnieForMultipleChoice + +[[autodoc]] ErnieForMultipleChoice + - forward + +## ErnieForTokenClassification + +[[autodoc]] ErnieForTokenClassification + - forward + +## ErnieForQuestionAnswering + +[[autodoc]] ErnieForQuestionAnswering + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie_m.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie_m.md new file mode 100644 index 0000000000000000000000000000000000000000..3ce3b40c44638f3b0750dafba78396e63dac1fb4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ernie_m.md @@ -0,0 +1,102 @@ + + +# ErnieM + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The ErnieM model was proposed in [ERNIE-M: Enhanced Multilingual Representation by Aligning +Cross-lingual Semantics with Monolingual Corpora](https://arxiv.org/abs/2012.15674) by Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, +Hao Tian, Hua Wu, Haifeng Wang. + +The abstract from the paper is the following: + +*Recent studies have demonstrated that pre-trained cross-lingual models achieve impressive performance in downstream cross-lingual tasks. This improvement benefits from learning a large amount of monolingual and parallel corpora. Although it is generally acknowledged that parallel corpora are critical for improving the model performance, existing methods are often constrained by the size of parallel corpora, especially for lowresource languages. In this paper, we propose ERNIE-M, a new training method that encourages the model to align the representation of multiple languages with monolingual corpora, to overcome the constraint that the parallel corpus size places on the model performance. Our key insight is to integrate back-translation into the pre-training process. We generate pseudo-parallel sentence pairs on a monolingual corpus to enable the learning of semantic alignments between different languages, thereby enhancing the semantic modeling of cross-lingual models. Experimental results show that ERNIE-M outperforms existing cross-lingual models and delivers new state-of-the-art results in various cross-lingual downstream tasks.* +This model was contributed by [Susnato Dhar](https://huggingface.co/susnato). The original code can be found [here](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/paddlenlp/transformers/ernie_m). + + +## Usage tips + +- Ernie-M is a BERT-like model so it is a stacked Transformer Encoder. +- Instead of using MaskedLM for pretraining (like BERT) the authors used two novel techniques: `Cross-attention Masked Language Modeling` and `Back-translation Masked Language Modeling`. For now these two LMHead objectives are not implemented here. +- It is a multilingual language model. +- Next Sentence Prediction was not used in pretraining process. + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Multiple choice task guide](../tasks/multiple_choice) + +## ErnieMConfig + +[[autodoc]] ErnieMConfig + + +## ErnieMTokenizer + +[[autodoc]] ErnieMTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + + +## ErnieMModel + +[[autodoc]] ErnieMModel + - forward + +## ErnieMForSequenceClassification + +[[autodoc]] ErnieMForSequenceClassification + - forward + + +## ErnieMForMultipleChoice + +[[autodoc]] ErnieMForMultipleChoice + - forward + + +## ErnieMForTokenClassification + +[[autodoc]] ErnieMForTokenClassification + - forward + + +## ErnieMForQuestionAnswering + +[[autodoc]] ErnieMForQuestionAnswering + - forward + +## ErnieMForInformationExtraction + +[[autodoc]] ErnieMForInformationExtraction + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/esm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/esm.md new file mode 100644 index 0000000000000000000000000000000000000000..6061d8eea987fd7a9faaf79c07fd0017ab030fa0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/esm.md @@ -0,0 +1,167 @@ + + +# ESM + +
+PyTorch +TensorFlow +
+ +## Overview + +This page provides code and pre-trained weights for Transformer protein language models from Meta AI's Fundamental +AI Research Team, providing the state-of-the-art ESMFold and ESM-2, and the previously released ESM-1b and ESM-1v. +Transformer protein language models were introduced in the paper [Biological structure and function emerge from scaling +unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by +Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, +C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. +The first version of this paper was [preprinted in 2019](https://www.biorxiv.org/content/10.1101/622803v1?versioned=true). + +ESM-2 outperforms all tested single-sequence protein language models across a range of structure prediction tasks, +and enables atomic resolution structure prediction. +It was released with the paper [Language models of protein sequences at the scale of evolution enable accurate +structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, +Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido and Alexander Rives. + +Also introduced in this paper was ESMFold. It uses an ESM-2 stem with a head that can predict folded protein +structures with state-of-the-art accuracy. Unlike [AlphaFold2](https://www.nature.com/articles/s41586-021-03819-2), +it relies on the token embeddings from the large pre-trained protein language model stem and does not perform a multiple +sequence alignment (MSA) step at inference time, which means that ESMFold checkpoints are fully "standalone" - +they do not require a database of known protein sequences and structures with associated external query tools +to make predictions, and are much faster as a result. + + +The abstract from +"Biological structure and function emerge from scaling unsupervised learning to 250 +million protein sequences" is + + +*In the field of artificial intelligence, a combination of scale in data and model capacity enabled by unsupervised +learning has led to major advances in representation learning and statistical generation. In the life sciences, the +anticipated growth of sequencing promises unprecedented data on natural sequence diversity. Protein language modeling +at the scale of evolution is a logical step toward predictive and generative artificial intelligence for biology. To +this end, we use unsupervised learning to train a deep contextual language model on 86 billion amino acids across 250 +million protein sequences spanning evolutionary diversity. The resulting model contains information about biological +properties in its representations. The representations are learned from sequence data alone. The learned representation +space has a multiscale organization reflecting structure from the level of biochemical properties of amino acids to +remote homology of proteins. Information about secondary and tertiary structure is encoded in the representations and +can be identified by linear projections. Representation learning produces features that generalize across a range of +applications, enabling state-of-the-art supervised prediction of mutational effect and secondary structure and +improving state-of-the-art features for long-range contact prediction.* + + +The abstract from +"Language models of protein sequences at the scale of evolution enable accurate structure prediction" is + +*Large language models have recently been shown to develop emergent capabilities with scale, going beyond +simple pattern matching to perform higher level reasoning and generate lifelike images and text. While +language models trained on protein sequences have been studied at a smaller scale, little is known about +what they learn about biology as they are scaled up. In this work we train models up to 15 billion parameters, +the largest language models of proteins to be evaluated to date. We find that as models are scaled they learn +information enabling the prediction of the three-dimensional structure of a protein at the resolution of +individual atoms. We present ESMFold for high accuracy end-to-end atomic level structure prediction directly +from the individual sequence of a protein. ESMFold has similar accuracy to AlphaFold2 and RoseTTAFold for +sequences with low perplexity that are well understood by the language model. ESMFold inference is an +order of magnitude faster than AlphaFold2, enabling exploration of the structural space of metagenomic +proteins in practical timescales.* + +The original code can be found [here](https://github.com/facebookresearch/esm) and was +was developed by the Fundamental AI Research team at Meta AI. +ESM-1b, ESM-1v and ESM-2 were contributed to huggingface by [jasonliu](https://huggingface.co/jasonliu) +and [Matt](https://huggingface.co/Rocketknight1). + +ESMFold was contributed to huggingface by [Matt](https://huggingface.co/Rocketknight1) and +[Sylvain](https://huggingface.co/sgugger), with a big thank you to Nikita Smetanin, Roshan Rao and Tom Sercu for their +help throughout the process! + +## Usage tips + +- ESM models are trained with a masked language modeling (MLM) objective. +- The HuggingFace port of ESMFold uses portions of the [openfold](https://github.com/aqlaboratory/openfold) library. The `openfold` library is licensed under the Apache License 2.0. + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Masked language modeling task guide](../tasks/masked_language_modeling) + +## EsmConfig + +[[autodoc]] EsmConfig + - all + +## EsmTokenizer + +[[autodoc]] EsmTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + + + + +## EsmModel + +[[autodoc]] EsmModel + - forward + +## EsmForMaskedLM + +[[autodoc]] EsmForMaskedLM + - forward + +## EsmForSequenceClassification + +[[autodoc]] EsmForSequenceClassification + - forward + +## EsmForTokenClassification + +[[autodoc]] EsmForTokenClassification + - forward + +## EsmForProteinFolding + +[[autodoc]] EsmForProteinFolding + - forward + + + + +## TFEsmModel + +[[autodoc]] TFEsmModel + - call + +## TFEsmForMaskedLM + +[[autodoc]] TFEsmForMaskedLM + - call + +## TFEsmForSequenceClassification + +[[autodoc]] TFEsmForSequenceClassification + - call + +## TFEsmForTokenClassification + +[[autodoc]] TFEsmForTokenClassification + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon.md new file mode 100644 index 0000000000000000000000000000000000000000..1197d208a2ab96241447c6e0b95f6efad0c0e959 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon.md @@ -0,0 +1,90 @@ + + +# Falcon + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +Falcon is a class of causal decoder-only models built by [TII](https://www.tii.ae/). The largest Falcon checkpoints +have been trained on >=1T tokens of text, with a particular emphasis on the [RefinedWeb](https://arxiv.org/abs/2306.01116) +corpus. They are made available under the Apache 2.0 license. + + +Falcon's architecture is modern and optimized for inference, with multi-query attention and support for efficient +attention variants like `FlashAttention`. Both 'base' models trained only as causal language models as well as +'instruct' models that have received further fine-tuning are available. + + +Falcon models are (as of 2023) some of the largest and most powerful open-source language models, +and consistently rank highly in the [OpenLLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). + +## Converting custom checkpoints + + + +Falcon models were initially added to the Hugging Face Hub as custom code checkpoints. However, Falcon is now fully +supported in the Transformers library. If you fine-tuned a model from a custom code checkpoint, we recommend converting +your checkpoint to the new in-library format, as this should give significant improvements to stability and +performance, especially for generation, as well as removing the need to use `trust_remote_code=True`! + + + +You can convert custom code checkpoints to full Transformers checkpoints using the `convert_custom_code_checkpoint.py` +script located in the +[Falcon model directory](https://github.com/huggingface/transformers/tree/main/src/transformers/models/falcon) +of the Transformers library. To use this script, simply call it with +`python convert_custom_code_checkpoint.py --checkpoint_dir my_model`. This will convert your checkpoint in-place, and +you can immediately load it from the directory afterwards with e.g. `from_pretrained()`. If your model hasn't been +uploaded to the Hub, we recommend making a backup before attempting the conversion, just in case! + + +## FalconConfig + +[[autodoc]] FalconConfig + - all + +## FalconModel + +[[autodoc]] FalconModel + - forward + +## FalconForCausalLM + +[[autodoc]] FalconForCausalLM + - forward + +## FalconForSequenceClassification + +[[autodoc]] FalconForSequenceClassification + - forward + +## FalconForTokenClassification + +[[autodoc]] FalconForTokenClassification + - forward + +## FalconForQuestionAnswering + +[[autodoc]] FalconForQuestionAnswering + - forward + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon3.md new file mode 100644 index 0000000000000000000000000000000000000000..276548be77ad7e9a5e991fc62242999fc1c464f8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon3.md @@ -0,0 +1,35 @@ + + +# Falcon3 + +
+PyTorch +Flax +
+ +## Overview + +Falcon3 represents a natural evolution from previous releases, emphasizing expanding the models' science, math, and code capabilities. This iteration includes five base models: Falcon3-1B-Base, Falcon3-3B-Base, Falcon3-Mamba-7B-Base, Falcon3-7B-Base, and Falcon3-10B-Base. In developing these models, we incorporated several key innovations aimed at improving the models' performances while reducing training costs: + +One pre-training: We conducted a single large-scale pretraining run on the 7B model, using 2048 H100 GPU chips, leveraging 14 trillion tokens featuring web, code, STEM, and curated high-quality and multilingual data. +Depth up-scaling for improved reasoning: Building on recent studies on the effects of model depth, we upscaled the 7B model to a 10B parameters model by duplicating the redundant layers and continuing pre-training with 2TT of high-quality data. This yielded Falcon3-10B-Base which achieves state-of-the-art zero-shot and few-shot performance for models under 13B parameters. +Knowledge distillation for better tiny models: To provide compact and efficient alternatives, we developed Falcon3-1B-Base and Falcon3-3B-Base by leveraging pruning and knowledge distillation techniques, using less than 100GT of curated high-quality data, thereby redefining pre-training efficiency. + +## Resources +- [Blog post](https://huggingface.co/blog/falcon3) +- [Models on Huggingface](https://huggingface.co/collections/tiiuae/falcon3-67605ae03578be86e4e87026) diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon_mamba.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon_mamba.md new file mode 100644 index 0000000000000000000000000000000000000000..fb6debfef921e44780f7d2e6e31e66a2be6cf14a --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/falcon_mamba.md @@ -0,0 +1,120 @@ + + +# FalconMamba + +
+PyTorch +
+ +## Overview + +The FalconMamba model was proposed by TII UAE (Technology Innovation Institute) in their release. + +The abstract from the paper is the following: + +*We present FalconMamba, a new base large language model based on the novel Mamba architecture. FalconMamba is trained on 5.8 trillion tokens with carefully selected data mixtures. As a pure Mamba-based model, FalconMamba surpasses leading open-weight models based on Transformers, such as Mistral 7B, Llama3 8B, and Falcon2 11B. It is on par with Gemma 7B and outperforms models with different architecture designs, such as RecurrentGemma 9B. Currently, FalconMamba is the best-performing Mamba model in the literature at this scale, surpassing both existing Mamba and hybrid Mamba-Transformer models. +Due to its architecture, FalconMamba is significantly faster at inference and requires substantially less memory for long sequence generation. Despite recent studies suggesting that hybrid Mamba-Transformer models outperform pure architecture designs, we argue and demonstrate that the pure Mamba design can achieve similar, even superior results compared to the hybrid design. We make the weights of our implementation of FalconMamba publicly available under a permissive license.* + +Tips: + +- FalconMamba is mostly based on Mamba architecture, the same [tips and best practices](./mamba) would be relevant here. + +The model has been trained on approximtely 6T tokens consisting a mixture of many data sources such as RefineWeb, Cosmopedia and Math data. + +For more details about the training procedure and the architecture, have a look at [the technical paper of FalconMamba]() (coming soon). + +# Usage + +Below we demonstrate how to use the model: + +```python +from transformers import FalconMambaForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-mamba-7b") +model = FalconMambaForCausalLM.from_pretrained("tiiuae/falcon-mamba-7b") + +input_ids = tokenizer("Hey how are you doing?", return_tensors= "pt")["input_ids"] + +out = model.generate(input_ids, max_new_tokens=10) +print(tokenizer.batch_decode(out)) +``` + +The architecture is also compatible with `torch.compile` for faster generation: + +```python +from transformers import FalconMambaForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-mamba-7b") +model = FalconMambaForCausalLM.from_pretrained("tiiuae/falcon-mamba-7b", torch_dtype=torch.bfloat16).to(0) +model = torch.compile(model) + +input_ids = tokenizer("Hey how are you doing?", return_tensors= "pt")["input_ids"] + +out = model.generate(input_ids, max_new_tokens=10) +print(tokenizer.batch_decode(out)) +``` + +If you have access to a GPU that is compatible with `bitsandbytes`, you can also quantize the model in 4-bit precision: + +```python +from transformers import FalconMambaForCausalLM, AutoTokenizer, BitsAndBytesConfig +import torch + +tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-mamba-7b") +quantization_config = BitsAndBytesConfig(load_in_4bit=True) +model = FalconMambaForCausalLM.from_pretrained("tiiuae/falcon-mamba-7b", quantization_config=quantization_config) + +input_ids = tokenizer("Hey how are you doing?", return_tensors= "pt")["input_ids"] + +out = model.generate(input_ids, max_new_tokens=10) +print(tokenizer.batch_decode(out)) +``` + +You can also play with the instruction fine-tuned model: + +```python +from transformers import FalconMambaForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-mamba-7b-instruct") +model = FalconMambaForCausalLM.from_pretrained("tiiuae/falcon-mamba-7b-instruct") + +# We use the tokenizer's chat template to format each message - see https://huggingface.co/docs/transformers/main/en/chat_templating +messages = [ + {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, +] +input_ids = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True).input_ids + +outputs = model.generate(input_ids) +print(tokenizer.decode(outputs[0])) +``` + +## FalconMambaConfig + +[[autodoc]] FalconMambaConfig + +## FalconMambaModel + +[[autodoc]] FalconMambaModel + - forward + +## FalconMambaLMHeadModel + +[[autodoc]] FalconMambaForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fastspeech2_conformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fastspeech2_conformer.md new file mode 100644 index 0000000000000000000000000000000000000000..aeb055ceae40dffbdb3cc002b3a391e89aae89b4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fastspeech2_conformer.md @@ -0,0 +1,138 @@ + + +# FastSpeech2Conformer + +
+PyTorch +
+ +## Overview + +The FastSpeech2Conformer model was proposed with the paper [Recent Developments On Espnet Toolkit Boosted By Conformer](https://arxiv.org/abs/2010.13956) by Pengcheng Guo, Florian Boyer, Xuankai Chang, Tomoki Hayashi, Yosuke Higuchi, Hirofumi Inaguma, Naoyuki Kamo, Chenda Li, Daniel Garcia-Romero, Jiatong Shi, Jing Shi, Shinji Watanabe, Kun Wei, Wangyou Zhang, and Yuekai Zhang. + +The abstract from the original FastSpeech2 paper is the following: + +*Non-autoregressive text to speech (TTS) models such as FastSpeech (Ren et al., 2019) can synthesize speech significantly faster than previous autoregressive models with comparable quality. The training of FastSpeech model relies on an autoregressive teacher model for duration prediction (to provide more information as input) and knowledge distillation (to simplify the data distribution in output), which can ease the one-to-many mapping problem (i.e., multiple speech variations correspond to the same text) in TTS. However, FastSpeech has several disadvantages: 1) the teacher-student distillation pipeline is complicated and time-consuming, 2) the duration extracted from the teacher model is not accurate enough, and the target mel-spectrograms distilled from teacher model suffer from information loss due to data simplification, both of which limit the voice quality. In this paper, we propose FastSpeech 2, which addresses the issues in FastSpeech and better solves the one-to-many mapping problem in TTS by 1) directly training the model with ground-truth target instead of the simplified output from teacher, and 2) introducing more variation information of speech (e.g., pitch, energy and more accurate duration) as conditional inputs. Specifically, we extract duration, pitch and energy from speech waveform and directly take them as conditional inputs in training and use predicted values in inference. We further design FastSpeech 2s, which is the first attempt to directly generate speech waveform from text in parallel, enjoying the benefit of fully end-to-end inference. Experimental results show that 1) FastSpeech 2 achieves a 3x training speed-up over FastSpeech, and FastSpeech 2s enjoys even faster inference speed; 2) FastSpeech 2 and 2s outperform FastSpeech in voice quality, and FastSpeech 2 can even surpass autoregressive models. Audio samples are available at https://speechresearch.github.io/fastspeech2/.* + +This model was contributed by [Connor Henderson](https://huggingface.co/connor-henderson). The original code can be found [here](https://github.com/espnet/espnet/blob/master/espnet2/tts/fastspeech2/fastspeech2.py). + + +## 🤗 Model Architecture +FastSpeech2's general structure with a Mel-spectrogram decoder was implemented, and the traditional transformer blocks were replaced with conformer blocks as done in the ESPnet library. + +#### FastSpeech2 Model Architecture +![FastSpeech2 Model Architecture](https://www.microsoft.com/en-us/research/uploads/prod/2021/04/fastspeech2-1.png) + +#### Conformer Blocks +![Conformer Blocks](https://www.researchgate.net/profile/Hirofumi-Inaguma-2/publication/344911155/figure/fig2/AS:951455406108673@1603856054097/An-overview-of-Conformer-block.png) + +#### Convolution Module +![Convolution Module](https://d3i71xaburhd42.cloudfront.net/8809d0732f6147d4ad9218c8f9b20227c837a746/2-Figure1-1.png) + +## 🤗 Transformers Usage + +You can run FastSpeech2Conformer locally with the 🤗 Transformers library. + +1. First install the 🤗 [Transformers library](https://github.com/huggingface/transformers), g2p-en: + +```bash +pip install --upgrade pip +pip install --upgrade transformers g2p-en +``` + +2. Run inference via the Transformers modelling code with the model and hifigan separately + +```python + +from transformers import FastSpeech2ConformerTokenizer, FastSpeech2ConformerModel, FastSpeech2ConformerHifiGan +import soundfile as sf + +tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer") +inputs = tokenizer("Hello, my dog is cute.", return_tensors="pt") +input_ids = inputs["input_ids"] + +model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer") +output_dict = model(input_ids, return_dict=True) +spectrogram = output_dict["spectrogram"] + +hifigan = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan") +waveform = hifigan(spectrogram) + +sf.write("speech.wav", waveform.squeeze().detach().numpy(), samplerate=22050) +``` + +3. Run inference via the Transformers modelling code with the model and hifigan combined + +```python +from transformers import FastSpeech2ConformerTokenizer, FastSpeech2ConformerWithHifiGan +import soundfile as sf + +tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer") +inputs = tokenizer("Hello, my dog is cute.", return_tensors="pt") +input_ids = inputs["input_ids"] + +model = FastSpeech2ConformerWithHifiGan.from_pretrained("espnet/fastspeech2_conformer_with_hifigan") +output_dict = model(input_ids, return_dict=True) +waveform = output_dict["waveform"] + +sf.write("speech.wav", waveform.squeeze().detach().numpy(), samplerate=22050) +``` + +4. Run inference with a pipeline and specify which vocoder to use +```python +from transformers import pipeline, FastSpeech2ConformerHifiGan +import soundfile as sf + +vocoder = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan") +synthesiser = pipeline(model="espnet/fastspeech2_conformer", vocoder=vocoder) + +speech = synthesiser("Hello, my dog is cooler than you!") + +sf.write("speech.wav", speech["audio"].squeeze(), samplerate=speech["sampling_rate"]) +``` + + +## FastSpeech2ConformerConfig + +[[autodoc]] FastSpeech2ConformerConfig + +## FastSpeech2ConformerHifiGanConfig + +[[autodoc]] FastSpeech2ConformerHifiGanConfig + +## FastSpeech2ConformerWithHifiGanConfig + +[[autodoc]] FastSpeech2ConformerWithHifiGanConfig + +## FastSpeech2ConformerTokenizer + +[[autodoc]] FastSpeech2ConformerTokenizer + - __call__ + - save_vocabulary + - decode + - batch_decode + +## FastSpeech2ConformerModel + +[[autodoc]] FastSpeech2ConformerModel + - forward + +## FastSpeech2ConformerHifiGan + +[[autodoc]] FastSpeech2ConformerHifiGan + - forward + +## FastSpeech2ConformerWithHifiGan + +[[autodoc]] FastSpeech2ConformerWithHifiGan + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-t5.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-t5.md new file mode 100644 index 0000000000000000000000000000000000000000..0e3b9ba0738fc99679235c4eb75f62981d6b2fe4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-t5.md @@ -0,0 +1,64 @@ + + +# FLAN-T5 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +FLAN-T5 was released in the paper [Scaling Instruction-Finetuned Language Models](https://arxiv.org/pdf/2210.11416.pdf) - it is an enhanced version of T5 that has been finetuned in a mixture of tasks. + +One can directly use FLAN-T5 weights without finetuning the model: + +```python +>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small") +>>> tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small") + +>>> inputs = tokenizer("A step by step recipe to make bolognese pasta:", return_tensors="pt") +>>> outputs = model.generate(**inputs) +>>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['Pour a cup of bolognese into a large bowl and add the pasta'] +``` + +FLAN-T5 includes the same improvements as T5 version 1.1 (see [here](https://huggingface.co/docs/transformers/model_doc/t5v1.1) for the full details of the model's improvements.) + +Google has released the following variants: + +- [google/flan-t5-small](https://huggingface.co/google/flan-t5-small) + +- [google/flan-t5-base](https://huggingface.co/google/flan-t5-base) + +- [google/flan-t5-large](https://huggingface.co/google/flan-t5-large) + +- [google/flan-t5-xl](https://huggingface.co/google/flan-t5-xl) + +- [google/flan-t5-xxl](https://huggingface.co/google/flan-t5-xxl). + +The original checkpoints can be found [here](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints). + + + +Refer to [T5's documentation page](t5) for all API reference, code examples and notebooks. For more details regarding training and evaluation of the FLAN-T5, refer to the model card. + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-ul2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-ul2.md new file mode 100644 index 0000000000000000000000000000000000000000..3b946b909b09ee9d023ffe33f80256aca11c53d3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flan-ul2.md @@ -0,0 +1,61 @@ + + +# FLAN-UL2 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +Flan-UL2 is an encoder decoder model based on the T5 architecture. It uses the same configuration as the [UL2](ul2) model released earlier last year. +It was fine tuned using the "Flan" prompt tuning and dataset collection. Similar to `Flan-T5`, one can directly use FLAN-UL2 weights without finetuning the model: + +According to the original blog here are the notable improvements: + +- The original UL2 model was only trained with receptive field of 512, which made it non-ideal for N-shot prompting where N is large. +- The Flan-UL2 checkpoint uses a receptive field of 2048 which makes it more usable for few-shot in-context learning. +- The original UL2 model also had mode switch tokens that was rather mandatory to get good performance. However, they were a little cumbersome as this requires often some changes during inference or finetuning. In this update/change, we continue training UL2 20B for an additional 100k steps (with small batch) to forget “mode tokens” before applying Flan instruction tuning. This Flan-UL2 checkpoint does not require mode tokens anymore. +Google has released the following variants: + +The original checkpoints can be found [here](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-ul2-checkpoints). + + +## Running on low resource devices + +The model is pretty heavy (~40GB in half precision) so if you just want to run the model, make sure you load your model in 8bit, and use `device_map="auto"` to make sure you don't have any OOM issue! + +```python +>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-ul2", load_in_8bit=True, device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("google/flan-ul2") + +>>> inputs = tokenizer("A step by step recipe to make bolognese pasta:", return_tensors="pt") +>>> outputs = model.generate(**inputs) +>>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['In a large skillet, brown the ground beef and onion over medium heat. Add the garlic'] +``` + + + +Refer to [T5's documentation page](t5) for API reference, tips, code examples and notebooks. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flaubert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flaubert.md new file mode 100644 index 0000000000000000000000000000000000000000..59ab44ebff0387446030c57699e8b3f454b8b3ef --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flaubert.md @@ -0,0 +1,140 @@ + + +# FlauBERT + +
+PyTorch +TensorFlow +
+ +## Overview + +The FlauBERT model was proposed in the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) by Hang Le et al. It's a transformer model pretrained using a masked language +modeling (MLM) objective (like BERT). + +The abstract from the paper is the following: + +*Language models have become a key step to achieve state-of-the art results in many different Natural Language +Processing (NLP) tasks. Leveraging the huge amount of unlabeled texts nowadays available, they provide an efficient way +to pre-train continuous word representations that can be fine-tuned for a downstream task, along with their +contextualization at the sentence level. This has been widely demonstrated for English using contextualized +representations (Dai and Le, 2015; Peters et al., 2018; Howard and Ruder, 2018; Radford et al., 2018; Devlin et al., +2019; Yang et al., 2019b). In this paper, we introduce and share FlauBERT, a model learned on a very large and +heterogeneous French corpus. Models of different sizes are trained using the new CNRS (French National Centre for +Scientific Research) Jean Zay supercomputer. We apply our French language models to diverse NLP tasks (text +classification, paraphrasing, natural language inference, parsing, word sense disambiguation) and show that most of the +time they outperform other pretraining approaches. Different versions of FlauBERT as well as a unified evaluation +protocol for the downstream tasks, called FLUE (French Language Understanding Evaluation), are shared to the research +community for further reproducible experiments in French NLP.* + +This model was contributed by [formiel](https://huggingface.co/formiel). The original code can be found [here](https://github.com/getalp/Flaubert). + +Tips: +- Like RoBERTa, without the sentence ordering prediction (so just trained on the MLM objective). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## FlaubertConfig + +[[autodoc]] FlaubertConfig + +## FlaubertTokenizer + +[[autodoc]] FlaubertTokenizer + + + + +## FlaubertModel + +[[autodoc]] FlaubertModel + - forward + +## FlaubertWithLMHeadModel + +[[autodoc]] FlaubertWithLMHeadModel + - forward + +## FlaubertForSequenceClassification + +[[autodoc]] FlaubertForSequenceClassification + - forward + +## FlaubertForMultipleChoice + +[[autodoc]] FlaubertForMultipleChoice + - forward + +## FlaubertForTokenClassification + +[[autodoc]] FlaubertForTokenClassification + - forward + +## FlaubertForQuestionAnsweringSimple + +[[autodoc]] FlaubertForQuestionAnsweringSimple + - forward + +## FlaubertForQuestionAnswering + +[[autodoc]] FlaubertForQuestionAnswering + - forward + + + + +## TFFlaubertModel + +[[autodoc]] TFFlaubertModel + - call + +## TFFlaubertWithLMHeadModel + +[[autodoc]] TFFlaubertWithLMHeadModel + - call + +## TFFlaubertForSequenceClassification + +[[autodoc]] TFFlaubertForSequenceClassification + - call + +## TFFlaubertForMultipleChoice + +[[autodoc]] TFFlaubertForMultipleChoice + - call + +## TFFlaubertForTokenClassification + +[[autodoc]] TFFlaubertForTokenClassification + - call + +## TFFlaubertForQuestionAnsweringSimple + +[[autodoc]] TFFlaubertForQuestionAnsweringSimple + - call + + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flava.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flava.md new file mode 100644 index 0000000000000000000000000000000000000000..b32f93fc8bcb1b2b79b5cd269bac1ef5279340da --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/flava.md @@ -0,0 +1,107 @@ + + +# FLAVA + +
+PyTorch +
+ +## Overview + +The FLAVA model was proposed in [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela and is accepted at CVPR 2022. + +The paper aims at creating a single unified foundation model which can work across vision, language +as well as vision-and-language multimodal tasks. + +The abstract from the paper is the following: + +*State-of-the-art vision and vision-and-language models rely on large-scale visio-linguistic pretraining for obtaining good performance on a variety +of downstream tasks. Generally, such models are often either cross-modal (contrastive) or multi-modal +(with earlier fusion) but not both; and they often only target specific modalities or tasks. A promising +direction would be to use a single holistic universal model, as a "foundation", that targets all modalities +at once -- a true vision and language foundation model should be good at vision tasks, language tasks, and +cross- and multi-modal vision and language tasks. We introduce FLAVA as such a model and demonstrate +impressive performance on a wide range of 35 tasks spanning these target modalities.* + +This model was contributed by [aps](https://huggingface.co/aps). The original code can be found [here](https://github.com/facebookresearch/multimodal/tree/main/examples/flava). + +## FlavaConfig + +[[autodoc]] FlavaConfig + +## FlavaTextConfig + +[[autodoc]] FlavaTextConfig + +## FlavaImageConfig + +[[autodoc]] FlavaImageConfig + +## FlavaMultimodalConfig + +[[autodoc]] FlavaMultimodalConfig + +## FlavaImageCodebookConfig + +[[autodoc]] FlavaImageCodebookConfig + +## FlavaProcessor + +[[autodoc]] FlavaProcessor + +## FlavaFeatureExtractor + +[[autodoc]] FlavaFeatureExtractor + +## FlavaImageProcessor + +[[autodoc]] FlavaImageProcessor + - preprocess + +## FlavaForPreTraining + +[[autodoc]] FlavaForPreTraining + - forward + +## FlavaModel + +[[autodoc]] FlavaModel + - forward + - get_text_features + - get_image_features + +## FlavaImageCodebook + +[[autodoc]] FlavaImageCodebook + - forward + - get_codebook_indices + - get_codebook_probs + +## FlavaTextModel + +[[autodoc]] FlavaTextModel + - forward + +## FlavaImageModel + +[[autodoc]] FlavaImageModel + - forward + +## FlavaMultimodalModel + +[[autodoc]] FlavaMultimodalModel + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fnet.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fnet.md new file mode 100644 index 0000000000000000000000000000000000000000..fcf75e21caed25f830d3dd1d5c98d36627c6522f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fnet.md @@ -0,0 +1,114 @@ + + +# FNet + +
+PyTorch +
+ +## Overview + +The FNet model was proposed in [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by +James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon. The model replaces the self-attention layer in a BERT +model with a fourier transform which returns only the real parts of the transform. The model is significantly faster +than the BERT model because it has fewer parameters and is more memory efficient. The model achieves about 92-97% +accuracy of BERT counterparts on GLUE benchmark, and trains much faster than the BERT model. The abstract from the +paper is the following: + +*We show that Transformer encoder architectures can be sped up, with limited accuracy costs, by replacing the +self-attention sublayers with simple linear transformations that "mix" input tokens. These linear mixers, along with +standard nonlinearities in feed-forward layers, prove competent at modeling semantic relationships in several text +classification tasks. Most surprisingly, we find that replacing the self-attention sublayer in a Transformer encoder +with a standard, unparameterized Fourier Transform achieves 92-97% of the accuracy of BERT counterparts on the GLUE +benchmark, but trains 80% faster on GPUs and 70% faster on TPUs at standard 512 input lengths. At longer input lengths, +our FNet model is significantly faster: when compared to the "efficient" Transformers on the Long Range Arena +benchmark, FNet matches the accuracy of the most accurate models, while outpacing the fastest models across all +sequence lengths on GPUs (and across relatively shorter lengths on TPUs). Finally, FNet has a light memory footprint +and is particularly efficient at smaller model sizes; for a fixed speed and accuracy budget, small FNet models +outperform Transformer counterparts.* + +This model was contributed by [gchhablani](https://huggingface.co/gchhablani). The original code can be found [here](https://github.com/google-research/google-research/tree/master/f_net). + +## Usage tips + +The model was trained without an attention mask as it is based on Fourier Transform. The model was trained with +maximum sequence length 512 which includes pad tokens. Hence, it is highly recommended to use the same maximum +sequence length for fine-tuning and inference. + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## FNetConfig + +[[autodoc]] FNetConfig + +## FNetTokenizer + +[[autodoc]] FNetTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## FNetTokenizerFast + +[[autodoc]] FNetTokenizerFast + +## FNetModel + +[[autodoc]] FNetModel + - forward + +## FNetForPreTraining + +[[autodoc]] FNetForPreTraining + - forward + +## FNetForMaskedLM + +[[autodoc]] FNetForMaskedLM + - forward + +## FNetForNextSentencePrediction + +[[autodoc]] FNetForNextSentencePrediction + - forward + +## FNetForSequenceClassification + +[[autodoc]] FNetForSequenceClassification + - forward + +## FNetForMultipleChoice + +[[autodoc]] FNetForMultipleChoice + - forward + +## FNetForTokenClassification + +[[autodoc]] FNetForTokenClassification + - forward + +## FNetForQuestionAnswering + +[[autodoc]] FNetForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/focalnet.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/focalnet.md new file mode 100644 index 0000000000000000000000000000000000000000..5312cae4ff675e936bd282f9663b64f681fbd994 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/focalnet.md @@ -0,0 +1,54 @@ + + +# FocalNet + +
+PyTorch +
+ +## Overview + +The FocalNet model was proposed in [Focal Modulation Networks](https://arxiv.org/abs/2203.11926) by Jianwei Yang, Chunyuan Li, Xiyang Dai, Lu Yuan, Jianfeng Gao. +FocalNets completely replace self-attention (used in models like [ViT](vit) and [Swin](swin)) by a focal modulation mechanism for modeling token interactions in vision. +The authors claim that FocalNets outperform self-attention based models with similar computational costs on the tasks of image classification, object detection, and segmentation. + +The abstract from the paper is the following: + +*We propose focal modulation networks (FocalNets in short), where self-attention (SA) is completely replaced by a focal modulation mechanism for modeling token interactions in vision. Focal modulation comprises three components: (i) hierarchical contextualization, implemented using a stack of depth-wise convolutional layers, to encode visual contexts from short to long ranges, (ii) gated aggregation to selectively gather contexts for each query token based on its +content, and (iii) element-wise modulation or affine transformation to inject the aggregated context into the query. Extensive experiments show FocalNets outperform the state-of-the-art SA counterparts (e.g., Swin and Focal Transformers) with similar computational costs on the tasks of image classification, object detection, and segmentation. Specifically, FocalNets with tiny and base size achieve 82.3% and 83.9% top-1 accuracy on ImageNet-1K. After pretrained on ImageNet-22K in 224 resolution, it attains 86.5% and 87.3% top-1 accuracy when finetuned with resolution 224 and 384, respectively. When transferred to downstream tasks, FocalNets exhibit clear superiority. For object detection with Mask R-CNN, FocalNet base trained with 1\times outperforms the Swin counterpart by 2.1 points and already surpasses Swin trained with 3\times schedule (49.0 v.s. 48.5). For semantic segmentation with UPerNet, FocalNet base at single-scale outperforms Swin by 2.4, and beats Swin at multi-scale (50.5 v.s. 49.7). Using large FocalNet and Mask2former, we achieve 58.5 mIoU for ADE20K semantic segmentation, and 57.9 PQ for COCO Panoptic Segmentation. Using huge FocalNet and DINO, we achieved 64.3 and 64.4 mAP on COCO minival and test-dev, respectively, establishing new SoTA on top of much larger attention-based models like Swinv2-G and BEIT-3.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/microsoft/FocalNet). + +## FocalNetConfig + +[[autodoc]] FocalNetConfig + +## FocalNetModel + +[[autodoc]] FocalNetModel + - forward + +## FocalNetForMaskedImageModeling + +[[autodoc]] FocalNetForMaskedImageModeling + - forward + +## FocalNetForImageClassification + +[[autodoc]] FocalNetForImageClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fsmt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fsmt.md new file mode 100644 index 0000000000000000000000000000000000000000..9419dce71edf38d4a287fb429c2525b95abe9dbe --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fsmt.md @@ -0,0 +1,64 @@ + + +# FSMT + +## Overview + +FSMT (FairSeq MachineTranslation) models were introduced in [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616) by Nathan Ng, Kyra Yee, Alexei Baevski, Myle Ott, Michael Auli, Sergey Edunov. + +The abstract of the paper is the following: + +*This paper describes Facebook FAIR's submission to the WMT19 shared news translation task. We participate in two +language pairs and four language directions, English <-> German and English <-> Russian. Following our submission from +last year, our baseline systems are large BPE-based transformer models trained with the Fairseq sequence modeling +toolkit which rely on sampled back-translations. This year we experiment with different bitext data filtering schemes, +as well as with adding filtered back-translated data. We also ensemble and fine-tune our models on domain-specific +data, then decode using noisy channel model reranking. Our submissions are ranked first in all four directions of the +human evaluation campaign. On En->De, our system significantly outperforms other systems as well as human translations. +This system improves upon our WMT'18 submission by 4.5 BLEU points.* + +This model was contributed by [stas](https://huggingface.co/stas). The original code can be found +[here](https://github.com/pytorch/fairseq/tree/master/examples/wmt19). + +## Implementation Notes + +- FSMT uses source and target vocabulary pairs that aren't combined into one. It doesn't share embeddings tokens + either. Its tokenizer is very similar to [`XLMTokenizer`] and the main model is derived from + [`BartModel`]. + + +## FSMTConfig + +[[autodoc]] FSMTConfig + +## FSMTTokenizer + +[[autodoc]] FSMTTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## FSMTModel + +[[autodoc]] FSMTModel + - forward + +## FSMTForConditionalGeneration + +[[autodoc]] FSMTForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/funnel.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/funnel.md new file mode 100644 index 0000000000000000000000000000000000000000..96050a153df2aaf8a3f62a669aeb66fc31ec4b86 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/funnel.md @@ -0,0 +1,180 @@ + + +# Funnel Transformer + +
+PyTorch +TensorFlow +
+ +## Overview + +The Funnel Transformer model was proposed in the paper [Funnel-Transformer: Filtering out Sequential Redundancy for +Efficient Language Processing](https://arxiv.org/abs/2006.03236). It is a bidirectional transformer model, like +BERT, but with a pooling operation after each block of layers, a bit like in traditional convolutional neural networks +(CNN) in computer vision. + +The abstract from the paper is the following: + +*With the success of language pretraining, it is highly desirable to develop more efficient architectures of good +scalability that can exploit the abundant unlabeled data at a lower cost. To improve the efficiency, we examine the +much-overlooked redundancy in maintaining a full-length token-level presentation, especially for tasks that only +require a single-vector presentation of the sequence. With this intuition, we propose Funnel-Transformer which +gradually compresses the sequence of hidden states to a shorter one and hence reduces the computation cost. More +importantly, by re-investing the saved FLOPs from length reduction in constructing a deeper or wider model, we further +improve the model capacity. In addition, to perform token-level predictions as required by common pretraining +objectives, Funnel-Transformer is able to recover a deep representation for each token from the reduced hidden sequence +via a decoder. Empirically, with comparable or fewer FLOPs, Funnel-Transformer outperforms the standard Transformer on +a wide variety of sequence-level prediction tasks, including text classification, language understanding, and reading +comprehension.* + +This model was contributed by [sgugger](https://huggingface.co/sgugger). The original code can be found [here](https://github.com/laiguokun/Funnel-Transformer). + +## Usage tips + +- Since Funnel Transformer uses pooling, the sequence length of the hidden states changes after each block of layers. This way, their length is divided by 2, which speeds up the computation of the next hidden states. + The base model therefore has a final sequence length that is a quarter of the original one. This model can be used + directly for tasks that just require a sentence summary (like sequence classification or multiple choice). For other + tasks, the full model is used; this full model has a decoder that upsamples the final hidden states to the same + sequence length as the input. +- For tasks such as classification, this is not a problem, but for tasks like masked language modeling or token classification, we need a hidden state with the same sequence length as the original input. In those cases, the final hidden states are upsampled to the input sequence length and go through two additional layers. That's why there are two versions of each checkpoint. The version suffixed with “-base” contains only the three blocks, while the version without that suffix contains the three blocks and the upsampling head with its additional layers. +- The Funnel Transformer checkpoints are all available with a full version and a base version. The first ones should be + used for [`FunnelModel`], [`FunnelForPreTraining`], + [`FunnelForMaskedLM`], [`FunnelForTokenClassification`] and + [`FunnelForQuestionAnswering`]. The second ones should be used for + [`FunnelBaseModel`], [`FunnelForSequenceClassification`] and + [`FunnelForMultipleChoice`]. + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + + +## FunnelConfig + +[[autodoc]] FunnelConfig + +## FunnelTokenizer + +[[autodoc]] FunnelTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## FunnelTokenizerFast + +[[autodoc]] FunnelTokenizerFast + +## Funnel specific outputs + +[[autodoc]] models.funnel.modeling_funnel.FunnelForPreTrainingOutput + +[[autodoc]] models.funnel.modeling_tf_funnel.TFFunnelForPreTrainingOutput + + + + +## FunnelBaseModel + +[[autodoc]] FunnelBaseModel + - forward + +## FunnelModel + +[[autodoc]] FunnelModel + - forward + +## FunnelModelForPreTraining + +[[autodoc]] FunnelForPreTraining + - forward + +## FunnelForMaskedLM + +[[autodoc]] FunnelForMaskedLM + - forward + +## FunnelForSequenceClassification + +[[autodoc]] FunnelForSequenceClassification + - forward + +## FunnelForMultipleChoice + +[[autodoc]] FunnelForMultipleChoice + - forward + +## FunnelForTokenClassification + +[[autodoc]] FunnelForTokenClassification + - forward + +## FunnelForQuestionAnswering + +[[autodoc]] FunnelForQuestionAnswering + - forward + + + + +## TFFunnelBaseModel + +[[autodoc]] TFFunnelBaseModel + - call + +## TFFunnelModel + +[[autodoc]] TFFunnelModel + - call + +## TFFunnelModelForPreTraining + +[[autodoc]] TFFunnelForPreTraining + - call + +## TFFunnelForMaskedLM + +[[autodoc]] TFFunnelForMaskedLM + - call + +## TFFunnelForSequenceClassification + +[[autodoc]] TFFunnelForSequenceClassification + - call + +## TFFunnelForMultipleChoice + +[[autodoc]] TFFunnelForMultipleChoice + - call + +## TFFunnelForTokenClassification + +[[autodoc]] TFFunnelForTokenClassification + - call + +## TFFunnelForQuestionAnswering + +[[autodoc]] TFFunnelForQuestionAnswering + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fuyu.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fuyu.md new file mode 100644 index 0000000000000000000000000000000000000000..c0ea89ad19fb508cca1be90415441d973f019d67 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/fuyu.md @@ -0,0 +1,119 @@ + + +# Fuyu + +
+PyTorch +
+ +## Overview + +The Fuyu model was created by [ADEPT](https://www.adept.ai/blog/fuyu-8b), and authored by Rohan Bavishi, Erich Elsen, Curtis Hawthorne, Maxwell Nye, Augustus Odena, Arushi Somani, Sağnak Taşırlar. + +The authors introduced Fuyu-8B, a decoder-only multimodal model based on the classic transformers architecture, with query and key normalization. A linear encoder is added to create multimodal embeddings from image inputs. + +By treating image tokens like text tokens and using a special image-newline character, the model knows when an image line ends. Image positional embeddings are removed. This avoids the need for different training phases for various image resolutions. With 8 billion parameters and licensed under CC-BY-NC, Fuyu-8B is notable for its ability to handle both text and images, its impressive context size of 16K, and its overall performance. + + + +The `Fuyu` models were trained using `bfloat16`, but the original inference uses `float16` The checkpoints uploaded on the hub use `torch_dtype = 'float16'` which will be +used by the `AutoModel` API to cast the checkpoints from `torch.float32` to `torch.float16`. + +The `dtype` of the online weights is mostly irrelevant, unless you are using `torch_dtype="auto"` when initializing a model using `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`. The reason is that the model will first be downloaded ( using the `dtype` of the checkpoints online) then it will be cast to the default `dtype` of `torch` (becomes `torch.float32`). Users should specify the `torch_dtype` they want, and if they don't it will be `torch.float32`. + +Finetuning the model in `float16` is not recommended and known to produce `nan`, as such the model should be fine-tuned in `bfloat16`. + + + + +Tips: + +- To convert the model, you need to clone the original repository using `git clone https://github.com/persimmon-ai-labs/adept-inference`, then get the checkpoints: + +```bash +git clone https://github.com/persimmon-ai-labs/adept-inference +wget path/to/fuyu-8b-model-weights.tar +tar -xvf fuyu-8b-model-weights.tar +python src/transformers/models/fuyu/convert_fuyu_weights_to_hf.py --input_dir /path/to/downloaded/fuyu/weights/ --output_dir /output/path \ + --pt_model_path /path/to/fuyu_8b_release/iter_0001251/mp_rank_00/model_optim_rng.pt + --ada_lib_path /path/to/adept-inference +``` + +For the chat model: +```bash +wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_chat_model_release.tar +tar -xvf 8b_base_model_release.tar +``` +Then, model can be loaded via: + +```py +from transformers import FuyuConfig, FuyuForCausalLM +model_config = FuyuConfig() +model = FuyuForCausalLM(model_config).from_pretrained('/output/path') +``` + +Inputs need to be passed through a specific Processor to have the correct formats. +A processor requires an image_processor and a tokenizer. Hence, inputs can be loaded via: + +```py +from PIL import Image +from transformers import AutoTokenizer +from transformers.models.fuyu.processing_fuyu import FuyuProcessor +from transformers.models.fuyu.image_processing_fuyu import FuyuImageProcessor + + +tokenizer = AutoTokenizer.from_pretrained('adept-hf-collab/fuyu-8b') +image_processor = FuyuImageProcessor() + + +processor = FuyuProcessor(image_processor=image_processor, tokenizer=tokenizer) +text_prompt = "Generate a coco-style caption.\\n" + +bus_image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png" +bus_image_pil = Image.open(io.BytesIO(requests.get(bus_image_url).content)) +inputs_to_model = processor(images=bus_image_pil, text=text_prompt) + + +``` + +This model was contributed by [Molbap](https://huggingface.co/Molbap). +The original code can be found [here](https://github.com/persimmon-ai-labs/adept-inference). + +- Fuyu uses a `sentencepiece` based tokenizer, with a `Unigram` model. It supports bytefallback, which is only available in `tokenizers==0.14.0` for the fast tokenizer. +The `LlamaTokenizer` is used as it is a standard wrapper around sentencepiece. + +- The authors suggest to use the following prompt for image captioning: `f"Generate a coco-style caption.\\n"` + + +## FuyuConfig + +[[autodoc]] FuyuConfig + +## FuyuForCausalLM + +[[autodoc]] FuyuForCausalLM + - forward + +## FuyuImageProcessor + +[[autodoc]] FuyuImageProcessor + - __call__ + +## FuyuProcessor + +[[autodoc]] FuyuProcessor + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma.md new file mode 100644 index 0000000000000000000000000000000000000000..144bcf33886b17816fa87b6526ebb0079411d0e3 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma.md @@ -0,0 +1,84 @@ + + +# Gemma + +
+PyTorch +Flax +FlashAttention +SDPA +
+ +## Overview + +The Gemma model was proposed in [Gemma: Open Models Based on Gemini Technology and Research](https://blog.google/technology/developers/gemma-open-models/) by Gemma Team, Google. +Gemma models are trained on 6T tokens, and released with 2 versions, 2b and 7b. + +The abstract from the paper is the following: + +*This work introduces Gemma, a new family of open language models demonstrating strong performance across academic benchmarks for language understanding, reasoning, and safety. We release two sizes of models (2 billion and 7 billion parameters), and provide both pretrained and fine-tuned checkpoints. Gemma outperforms similarly sized open models on 11 out of 18 text-based tasks, and we present comprehensive evaluations of safety and responsibility aspects of the models, alongside a detailed description of our model development. We believe the responsible release of LLMs is critical for improving the safety of frontier models, and for enabling the next wave of LLM innovations* + +Tips: + +- The original checkpoints can be converted using the conversion script `src/transformers/models/gemma/convert_gemma_weights_to_hf.py` + +This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ), [Younes Belkada](https://huggingface.co/ybelkada), [Sanchit Gandhi](https://huggingface.co/sanchit-gandhi), [Pedro Cuenca](https://huggingface.co/pcuenq). + + +## GemmaConfig + +[[autodoc]] GemmaConfig + +## GemmaTokenizer + +[[autodoc]] GemmaTokenizer + + +## GemmaTokenizerFast + +[[autodoc]] GemmaTokenizerFast + +## GemmaModel + +[[autodoc]] GemmaModel + - forward + +## GemmaForCausalLM + +[[autodoc]] GemmaForCausalLM + - forward + +## GemmaForSequenceClassification + +[[autodoc]] GemmaForSequenceClassification + - forward + +## GemmaForTokenClassification + +[[autodoc]] GemmaForTokenClassification + - forward + +## FlaxGemmaModel + +[[autodoc]] FlaxGemmaModel + - __call__ + +## FlaxGemmaForCausalLM + +[[autodoc]] FlaxGemmaForCausalLM + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma2.md new file mode 100644 index 0000000000000000000000000000000000000000..9cf8ff7af102adcc2383a7ceaa835cd81afebcb2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma2.md @@ -0,0 +1,70 @@ + + + +# Gemma2 + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Gemma2 model was proposed in [Gemma2: Open Models Based on Gemini Technology and Research](https://blog.google/technology/developers/google-gemma-2/) by Gemma2 Team, Google. +Two Gemma2 models are released, with parameters sizes of 9 billion (9B) and 27 billion (27B). + +The abstract from the blog post is the following: + +*Now we’re officially releasing Gemma 2 to researchers and developers globally. Available in both 9 billion (9B) and 27 billion (27B) parameter sizes, Gemma 2 is higher-performing and more efficient at inference than the first generation, with significant safety advancements built in. In fact, at 27B, it offers competitive alternatives to models more than twice its size, delivering the kind of performance that was only possible with proprietary models as recently as December.* + +Tips: + +- The original checkpoints can be converted using the conversion script `src/transformers/models/Gemma2/convert_Gemma2_weights_to_hf.py` + + + +- Gemma2 uses sliding window attention every second layer, which makes it unsuitable for typical kv caching with [`~DynamicCache`] or tuples of tensors. To enable caching in Gemma2 forward call, you must initialize a [`~HybridCache`] instance and pass it as `past_key_values` to the forward call. Note, that you also have to prepare `cache_position` if the `past_key_values` already contains previous keys and values. + + + +This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ), [Pedro Cuenca](https://huggingface.co/pcuenq) and [Tom Arsen](). + + +## Gemma2Config + +[[autodoc]] Gemma2Config + +## Gemma2Model + +[[autodoc]] Gemma2Model + - forward + +## Gemma2ForCausalLM + +[[autodoc]] Gemma2ForCausalLM + - forward + +## Gemma2ForSequenceClassification + +[[autodoc]] Gemma2ForSequenceClassification + - forward + +## Gemma2ForTokenClassification + +[[autodoc]] Gemma2ForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma3.md new file mode 100644 index 0000000000000000000000000000000000000000..0f466bb55bf2646fba23ba75f7cba4dfa2f810ac --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gemma3.md @@ -0,0 +1,203 @@ + + + +# Gemma3 + +## Overview + +The Gemma 3 model was proposed in the [Gemma 3 Techncial Report](https://goo.gle/Gemma3Report) by Google. It is a vision-language model composed by a [SigLIP](siglip) vision encoder and a [Gemma 2](gemma_2) language decoder, linked by a multimodal linear projection. It cuts an image into a fixed number of tokens, in the same way as SigLIP, as long as the image does not exceed certain aspect ratio. For images that exceed the given aspect ratio, it crops the image into multiple smaller patches and concatenates them with the base image embedding. One particularity is that the model uses bidirectional attention on all the image tokens. In addition, the model interleaves sliding window local attention with full causal attention in the language backbone, where each sixth layer is a full causal attention layer. + +This model was contributed by [Ryan Mullins](https://huggingface.co/RyanMullins), [Raushan Turganbay](https://huggingface.co/RaushanTurganbay) [Arthur Zucker](https://huggingface.co/ArthurZ), and [Pedro Cuenca](https://huggingface.co/pcuenq). + + +## Usage tips + + +- For image+text and image-only inputs use `Gemma3ForConditionalGeneration`. +- For text-only inputs use `Gemma3ForCausalLM` for generation to avoid loading the vision tower. +- Each sample can contain multiple images, and the number of images can vary between samples. However, make sure to pass correctly batched images to the processor, where each batch is a list of one or more images. +- The text passed to the processor should have a `` token wherever an image should be inserted. +- The processor has its own `apply_chat_template` method to convert chat messages to model inputs. See the examples below for more details on how to use it. + + +### Image cropping for high resolution images + +The model supports cropping images into smaller patches when the image aspect ratio exceeds a certain value. By default the images are not cropped and only the base image is forwarded to the model. Users can set `do_pan_and_scan=True` to obtain several crops per image along with the base image to improve the quality in DocVQA or similar tasks requiring higher resolution images. + +Pan and scan is an inference time optimization to handle images with skewed aspect ratios. When enabled, it improves performance on tasks related to document understanding, infographics, OCR, etc. + +```python + +processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it", padding_side="left") + +url = "https://media.istockphoto.com/id/1192867753/photo/cow-in-berchida-beach-siniscola.jpg?s=612x612&w=0&k=20&c=v0hjjniwsMNfJSuKWZuIn8pssmD5h5bSN1peBd1CmH4=" +messages = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "You are a helpful assistant."} + ] + }, + { + "role": "user", "content": [ + {"type": "image", "url": url}, + {"type": "text", "text": "What is shown in this image?"}, + ] + }, +] +inputs = processor.apply_chat_template( + messages, + tokenize=True, + return_dict=True, + return_tensors="pt", + add_generation_prompt=True, + do_pan_and_scan=True, +).to(model.device) + +``` + + +## Usage Example + +### Single-image Inference + +```python +from transformers import AutoProcessor, Gemma3ForConditionalGeneration + +model_id = "google/gemma-3-4b-it" +model = Gemma3ForConditionalGeneration.from_pretrained(model_id, device_map="auto") +processor = AutoProcessor.from_pretrained(model_id, padding_side="left") + +url = "https://media.istockphoto.com/id/1192867753/photo/cow-in-berchida-beach-siniscola.jpg?s=612x612&w=0&k=20&c=v0hjjniwsMNfJSuKWZuIn8pssmD5h5bSN1peBd1CmH4=" +messages = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "You are a helpful assistant."} + ] + }, + { + "role": "user", "content": [ + {"type": "image", "url": url}, + {"type": "text", "text": "What is shown in this image?"}, + ] + }, +] +inputs = processor.apply_chat_template( + messages, + tokenize=True, + return_dict=True, + return_tensors="pt", + add_generation_prompt=True, +).to(model.device) + +output = model.generate(**inputs, max_new_tokens=50) +print(processor.decode(output[0], skip_special_tokens=True)[inputs.input_ids.shape[1]: ]) +``` + +### Multi-image Inference + +```python +model_id = "google/gemma-3-4b-it" +model = Gemma3ForConditionalGeneration.from_pretrained(model_id, device_map="auto") +processor = AutoProcessor.from_pretrained(model_id, padding_side="left") + +url_cow = "https://media.istockphoto.com/id/1192867753/photo/cow-in-berchida-beach-siniscola.jpg?s=612x612&w=0&k=20&c=v0hjjniwsMNfJSuKWZuIn8pssmD5h5bSN1peBd1CmH4=" +url_stop = "https://www.ilankelman.org/stopsigns/australia.jpg" +messages = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "You are a helpful assistant."} + ] + }, + { + "role": "user", "content": [ + {"type": "image", "url": url_cow}, + {"type": "image", "url": url_stop}, + {"type": "text", "text": "Are these two images identical?"}, + ] + }, +] +inputs = processor.apply_chat_template( + messages, + tokenize=True, + return_dict=True, + return_tensors="pt", + add_generation_prompt=True, +).to(model.device) + +output = model.generate(**inputs, max_new_tokens=50) +print(processor.decode(output[0], skip_special_tokens=True)[inputs.input_ids.shape[1]: ]) + +``` + +### Text-only inference + +You can use the VLMs for text-only generation by omitting images in your input. However, you can also load the models in text-only mode as shown below. This will skip loading the vision tower and will save resources when you just need the LLM capabilities. +```python +from transformers import AutoTokenizer, Gemma3ForCausalLM + +model_id = "google/gemma-3-1b-it" + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = Gemma3ForCausalLM.from_pretrained(model_id, device_map="auto") + +input_ids = tokenizer("Write me a poem about Machine Learning.", return_tensors="pt").to(model.device) + +outputs = model.generate(**input_ids, max_new_tokens=100) +text = tokenizer.batch_decode(outputs, skip_special_tokens=True) + +print(text) + +``` + + +## Gemma3ImageProcessor + +[[autodoc]] Gemma3ImageProcessor + +## Gemma3ImageProcessorFast + +[[autodoc]] Gemma3ImageProcessorFast + +## Gemma3Processor + +[[autodoc]] Gemma3Processor + +## Gemma3TextConfig + +[[autodoc]] Gemma3TextConfig + +## Gemma3Config + +[[autodoc]] Gemma3Config + +## Gemma3TextModel + +[[autodoc]] Gemma3TextModel + - forward + +## Gemma3ForCausalLM + +[[autodoc]] Gemma3ForCausalLM + - forward + +## Gemma3ForConditionalGeneration + +[[autodoc]] Gemma3ForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/git.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/git.md new file mode 100644 index 0000000000000000000000000000000000000000..825b73c5c59b5092900a08b62116cb234a935e9c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/git.md @@ -0,0 +1,83 @@ + + +# GIT + +
+PyTorch +
+ +## Overview + +The GIT model was proposed in [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100) by +Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang. GIT is a decoder-only Transformer +that leverages [CLIP](clip)'s vision encoder to condition the model on vision inputs besides text. The model obtains state-of-the-art results on +image captioning and visual question answering benchmarks. + +The abstract from the paper is the following: + +*In this paper, we design and train a Generative Image-to-text Transformer, GIT, to unify vision-language tasks such as image/video captioning and question answering. While generative models provide a consistent network architecture between pre-training and fine-tuning, existing work typically contains complex structures (uni/multi-modal encoder/decoder) and depends on external modules such as object detectors/taggers and optical character recognition (OCR). In GIT, we simplify the architecture as one image encoder and one text decoder under a single language modeling task. We also scale up the pre-training data and the model size to boost the model performance. Without bells and whistles, our GIT establishes new state of the arts on 12 challenging benchmarks with a large margin. For instance, our model surpasses the human performance for the first time on TextCaps (138.2 vs. 125.5 in CIDEr). Furthermore, we present a new scheme of generation-based image classification and scene text recognition, achieving decent performance on standard benchmarks.* + + + + GIT architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/microsoft/GenerativeImage2Text). + +## Usage tips + +- GIT is implemented in a very similar way to GPT-2, the only difference being that the model is also conditioned on `pixel_values`. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GIT. + +- Demo notebooks regarding inference + fine-tuning GIT on custom data can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/GIT). +- See also: [Causal language modeling task guide](../tasks/language_modeling) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. +The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## GitVisionConfig + +[[autodoc]] GitVisionConfig + +## GitVisionModel + +[[autodoc]] GitVisionModel + - forward + +## GitConfig + +[[autodoc]] GitConfig + - all + +## GitProcessor + +[[autodoc]] GitProcessor + - __call__ + +## GitModel + +[[autodoc]] GitModel + - forward + +## GitForCausalLM + +[[autodoc]] GitForCausalLM + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glm.md new file mode 100644 index 0000000000000000000000000000000000000000..cfcd549d1493f430ef26ed1789b2e8f3f8dc8a25 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glm.md @@ -0,0 +1,105 @@ + + +# GLM + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The GLM Model was proposed +in [ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools](https://arxiv.org/html/2406.12793v1) +by GLM Team, THUDM & ZhipuAI. + +The abstract from the paper is the following: + +*We introduce ChatGLM, an evolving family of large language models that we have been developing over time. This report +primarily focuses on the GLM-4 language series, which includes GLM-4, GLM-4-Air, and GLM-4-9B. They represent our most +capable models that are trained with all the insights and lessons gained from the preceding three generations of +ChatGLM. To date, the GLM-4 models are pre-trained on ten trillions of tokens mostly in Chinese and English, along with +a small set of corpus from 24 languages, and aligned primarily for Chinese and English usage. The high-quality alignment +is achieved via a multi-stage post-training process, which involves supervised fine-tuning and learning from human +feedback. Evaluations show that GLM-4 1) closely rivals or outperforms GPT-4 in terms of general metrics such as MMLU, +GSM8K, MATH, BBH, GPQA, and HumanEval, 2) gets close to GPT-4-Turbo in instruction following as measured by IFEval, 3) +matches GPT-4 Turbo (128K) and Claude 3 for long context tasks, and 4) outperforms GPT-4 in Chinese alignments as +measured by AlignBench. The GLM-4 All Tools model is further aligned to understand user intent and autonomously decide +when and which tool(s) to use—including web browser, Python interpreter, text-to-image model, and user-defined +functions—to effectively complete complex tasks. In practical applications, it matches and even surpasses GPT-4 All +Tools in tasks like accessing online information via web browsing and solving math problems using Python interpreter. +Over the course, we have open-sourced a series of models, including ChatGLM-6B (three generations), GLM-4-9B (128K, 1M), +GLM-4V-9B, WebGLM, and CodeGeeX, attracting over 10 million downloads on Hugging face in the year 2023 alone.* + +Tips: + +- This model was contributed by [THUDM](https://huggingface.co/THUDM). The most recent code can be + found [here](https://github.com/thudm/GLM-4). + + +## Usage tips + +`GLM-4` can be found on the [Huggingface Hub](https://huggingface.co/collections/THUDM/glm-4-665fcf188c414b03c2f7e3b7) + +In the following, we demonstrate how to use `glm-4-9b-chat` for the inference. Note that we have used the ChatML format for dialog, in this demo we show how to leverage `apply_chat_template` for this purpose. + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer +>>> device = "cuda" # the device to load the model onto + +>>> model = AutoModelForCausalLM.from_pretrained("THUDM/glm-4-9b-chat", device_map="auto", trust_remote_code=True) +>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/glm-4-9b-chat") + +>>> prompt = "Give me a short introduction to large language model." + +>>> messages = [{"role": "user", "content": prompt}] + +>>> text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + +>>> model_inputs = tokenizer([text], return_tensors="pt").to(device) + +>>> generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512, do_sample=True) + +>>> generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)] + +>>> response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + +## GlmConfig + +[[autodoc]] GlmConfig + +## GlmModel + +[[autodoc]] GlmModel + - forward + +## GlmForCausalLM + +[[autodoc]] GlmForCausalLM + - forward + +## GlmForSequenceClassification + +[[autodoc]] GlmForSequenceClassification + - forward + +## GlmForTokenClassification + +[[autodoc]] GlmForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glpn.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glpn.md new file mode 100644 index 0000000000000000000000000000000000000000..95ecc36bf5b75b7c5c5b5cc100e39f3737836492 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/glpn.md @@ -0,0 +1,76 @@ + + +# GLPN + +
+PyTorch +
+ + + +This is a recently introduced model so the API hasn't been tested extensively. There may be some bugs or slight +breaking changes to fix it in the future. If you see something strange, file a [Github Issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=&template=bug-report.md&title). + + + +## Overview + +The GLPN model was proposed in [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim. +GLPN combines [SegFormer](segformer)'s hierarchical mix-Transformer with a lightweight decoder for monocular depth estimation. The proposed decoder shows better performance than the previously proposed decoders, with considerably +less computational complexity. + +The abstract from the paper is the following: + +*Depth estimation from a single image is an important task that can be applied to various fields in computer vision, and has grown rapidly with the development of convolutional neural networks. In this paper, we propose a novel structure and training strategy for monocular depth estimation to further improve the prediction accuracy of the network. We deploy a hierarchical transformer encoder to capture and convey the global context, and design a lightweight yet powerful decoder to generate an estimated depth map while considering local connectivity. By constructing connected paths between multi-scale local features and the global decoding stream with our proposed selective feature fusion module, the network can integrate both representations and recover fine details. In addition, the proposed decoder shows better performance than the previously proposed decoders, with considerably less computational complexity. Furthermore, we improve the depth-specific augmentation method by utilizing an important observation in depth estimation to enhance the model. Our network achieves state-of-the-art performance over the challenging depth dataset NYU Depth V2. Extensive experiments have been conducted to validate and show the effectiveness of the proposed approach. Finally, our model shows better generalisation ability and robustness than other comparative models.* + + + + Summary of the approach. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/vinvino02/GLPDepth). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GLPN. + +- Demo notebooks for [`GLPNForDepthEstimation`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/GLPN). +- [Monocular depth estimation task guide](../tasks/monocular_depth_estimation) + +## GLPNConfig + +[[autodoc]] GLPNConfig + +## GLPNFeatureExtractor + +[[autodoc]] GLPNFeatureExtractor + - __call__ + +## GLPNImageProcessor + +[[autodoc]] GLPNImageProcessor + - preprocess + +## GLPNModel + +[[autodoc]] GLPNModel + - forward + +## GLPNForDepthEstimation + +[[autodoc]] GLPNForDepthEstimation + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/got_ocr2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/got_ocr2.md new file mode 100644 index 0000000000000000000000000000000000000000..bb14cdbcf8477cdb926a9ce8549492d6a6ec2c0f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/got_ocr2.md @@ -0,0 +1,284 @@ + + +# GOT-OCR2 + +
+PyTorch +
+ +## Overview + +The GOT-OCR2 model was proposed in [General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model](https://arxiv.org/abs/2409.01704) by Haoran Wei, Chenglong Liu, Jinyue Chen, Jia Wang, Lingyu Kong, Yanming Xu, Zheng Ge, Liang Zhao, Jianjian Sun, Yuang Peng, Chunrui Han, Xiangyu Zhang. + +The abstract from the paper is the following: + +*Traditional OCR systems (OCR-1.0) are increasingly unable to meet people’snusage due to the growing demand for intelligent processing of man-made opticalncharacters. In this paper, we collectively refer to all artificial optical signals (e.g., plain texts, math/molecular formulas, tables, charts, sheet music, and even geometric shapes) as "characters" and propose the General OCR Theory along with an excellent model, namely GOT, to promote the arrival of OCR-2.0. The GOT, with 580M parameters, is a unified, elegant, and end-to-end model, consisting of a high-compression encoder and a long-contexts decoder. As an OCR-2.0 model, GOT can handle all the above "characters" under various OCR tasks. On the input side, the model supports commonly used scene- and document-style images in slice and whole-page styles. On the output side, GOT can generate plain or formatted results (markdown/tikz/smiles/kern) via an easy prompt. Besides, the model enjoys interactive OCR features, i.e., region-level recognition guided by coordinates or colors. Furthermore, we also adapt dynamic resolution and multipage OCR technologies to GOT for better practicality. In experiments, we provide sufficient results to prove the superiority of our model.* + + + + GOT-OCR2 training stages. Taken from the original paper. + + +Tips: + +GOT-OCR2 works on a wide range of tasks, including plain document OCR, scene text OCR, formatted document OCR, and even OCR for tables, charts, mathematical formulas, geometric shapes, molecular formulas and sheet music. While this implementation of the model will only output plain text, the outputs can be further processed to render the desired format, with packages like `pdftex`, `mathpix`, `matplotlib`, `tikz`, `verovio` or `pyecharts`. +The model can also be used for interactive OCR, where the user can specify the region to be recognized by providing the coordinates or the color of the region's bounding box. + +This model was contributed by [yonigozlan](https://huggingface.co/yonigozlan). +The original code can be found [here](https://github.com/Ucas-HaoranWei/GOT-OCR2.0). + +## Usage example + +### Plain text inference + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg" +>>> inputs = processor(image, return_tensors="pt", device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +"R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM\nName/Phone Ext. : (...)" +``` + +### Plain text inference batched + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png" +>>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg" + +>>> inputs = processor([image1, image2], return_tensors="pt", device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4, +... ) + +>>> processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True) +["Reducing the number", "R&D QUALITY"] +``` + +### Formatted text inference + +GOT-OCR2 can also generate formatted text, such as markdown or LaTeX. Here is an example of how to generate formatted text: + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/latex.png" +>>> inputs = processor(image, return_tensors="pt", format=True, device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +"\\author{\nHanwen Jiang* \\(\\quad\\) Arjun Karpur \\({ }^{\\dagger} \\quad\\) Bingyi Cao \\({ }^{\\dagger} \\quad\\) (...)" +``` + +### Inference on multiple pages + +Although it might be reasonable in most cases to use a “for loop” for multi-page processing, some text data with formatting across several pages make it necessary to process all pages at once. GOT introduces a multi-page OCR (without “for loop”) feature, where multiple pages can be processed by the model at once, whith the output being one continuous text. +Here is an example of how to process multiple pages at once: + + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page1.png" +>>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page2.png" +>>> inputs = processor([image1, image2], return_tensors="pt", multi_page=True, format=True, device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +"\\title{\nGeneral OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model\n}\n\\author{\nHaoran Wei (...)" +``` + +### Inference on cropped patches + +GOT supports a 1024×1024 input resolution, which is sufficient for most OCR tasks, such as scene OCR or processing A4-sized PDF pages. However, certain scenarios, like horizontally stitched two-page PDFs commonly found in academic papers or images with unusual aspect ratios, can lead to accuracy issues when processed as a single image. To address this, GOT can dynamically crop an image into patches, process them all at once, and merge the results for better accuracy with such inputs. +Here is an example of how to process cropped patches: + +```python +>>> import torch +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", torch_dtype=torch.bfloat16, device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/one_column.png" +>>> inputs = processor(image, return_tensors="pt", format=True, crop_to_patches=True, max_patches=3, device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +"on developing architectural improvements to make learnable matching methods generalize.\nMotivated by the above observations, (...)" +``` + +### Inference on a specific region + +GOT supports interactive OCR, where the user can specify the region to be recognized by providing the coordinates or the color of the region's bounding box. Here is an example of how to process a specific region: + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png" +>>> inputs = processor(image, return_tensors="pt", color="green", device=device).to(device) # or box=[x1, y1, x2, y2] for coordinates (image pixels) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +"You should keep in mind what features from the module should be used, especially \nwhen you’re planning to sell a template." +``` + +### Inference on general OCR data example: sheet music + +Although this implementation of the model will only output plain text, the outputs can be further processed to render the desired format, with packages like `pdftex`, `mathpix`, `matplotlib`, `tikz`, `verovio` or `pyecharts`. +Here is an example of how to process sheet music: + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch +>>> import verovio + +>>> device = "cuda" if torch.cuda.is_available() else "cpu" +>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device) +>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True) + +>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/sheet_music.png" +>>> inputs = processor(image, return_tensors="pt", format=True, device=device).to(device) + +>>> generate_ids = model.generate( +... **inputs, +... do_sample=False, +... tokenizer=processor.tokenizer, +... stop_strings="<|im_end|>", +... max_new_tokens=4096, +... ) + +>>> outputs = processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) +>>> tk = verovio.toolkit() +>>> tk.loadData(outputs) +>>> tk.setOptions( +... { +... "pageWidth": 2100, +... "pageHeight": 800, +... "footer": "none", +... "barLineWidth": 0.5, +... "beamMaxSlope": 15, +... "staffLineWidth": 0.2, +... "spacingStaff": 6, +... } +... ) +>>> tk.getPageCount() +>>> svg = tk.renderToSVG() +>>> svg = svg.replace('overflow="inherit"', 'overflow="visible"') +>>> with open("output.svg", "w") as f: +>>> f.write(svg) +``` + + +## GotOcr2Config + +[[autodoc]] GotOcr2Config + +## GotOcr2VisionConfig + +[[autodoc]] GotOcr2VisionConfig + +## GotOcr2ImageProcessor + +[[autodoc]] GotOcr2ImageProcessor + +## GotOcr2ImageProcessorFast + +[[autodoc]] GotOcr2ImageProcessorFast + +## GotOcr2Processor + +[[autodoc]] GotOcr2Processor + +## GotOcr2ForConditionalGeneration + +[[autodoc]] GotOcr2ForConditionalGeneration + - forward + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt-sw3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt-sw3.md new file mode 100644 index 0000000000000000000000000000000000000000..20daa3537af0f37c48b95385dc288a1629a6814d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt-sw3.md @@ -0,0 +1,76 @@ + + +# GPT-Sw3 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The GPT-Sw3 model was first proposed in +[Lessons Learned from GPT-SW3: Building the First Large-Scale Generative Language Model for Swedish](http://www.lrec-conf.org/proceedings/lrec2022/pdf/2022.lrec-1.376.pdf) +by Ariel Ekgren, Amaru Cuba Gyllensten, Evangelia Gogoulou, Alice Heiman, Severine Verlinden, Joey Öhman, +Fredrik Carlsson, Magnus Sahlgren. + +Since that first paper the authors have extended their work and trained new models on their new 1.2TB corpora named The Nordic Pile. + +GPT-Sw3 is a collection of large decoder-only pretrained transformer language models that were developed by AI Sweden +in collaboration with RISE and the WASP WARA for Media and Language. GPT-Sw3 has been trained on a dataset containing +320B tokens in Swedish, Norwegian, Danish, Icelandic, English, and programming code. The model was pretrained using a +causal language modeling (CLM) objective utilizing the NeMo Megatron GPT implementation. + +This model was contributed by [AI Sweden Models](https://huggingface.co/AI-Sweden-Models). + +## Usage example + +```python +>>> from transformers import AutoTokenizer, AutoModelForCausalLM + +>>> tokenizer = AutoTokenizer.from_pretrained("AI-Sweden-Models/gpt-sw3-356m") +>>> model = AutoModelForCausalLM.from_pretrained("AI-Sweden-Models/gpt-sw3-356m") + +>>> input_ids = tokenizer("Träd är fina för att", return_tensors="pt")["input_ids"] + +>>> generated_token_ids = model.generate(inputs=input_ids, max_new_tokens=10, do_sample=True)[0] + +>>> print(tokenizer.decode(generated_token_ids)) +Träd är fina för att de är färgstarka. Men ibland är det fint +``` + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Causal language modeling task guide](../tasks/language_modeling) + + + +The implementation uses the `GPT2Model` coupled with our `GPTSw3Tokenizer`. Refer to [GPT2Model documentation](gpt2) +for API reference and examples. + +Note that sentencepiece is required to use our tokenizer and can be installed with `pip install transformers[sentencepiece]` or `pip install sentencepiece` + + + +## GPTSw3Tokenizer + +[[autodoc]] GPTSw3Tokenizer + - save_vocabulary diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt2.md new file mode 100644 index 0000000000000000000000000000000000000000..89a0429cca411061f47f94d23cea71bc64977410 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt2.md @@ -0,0 +1,306 @@ + + +# OpenAI GPT2 + +
+ +Models + + +Spaces + +
+ +## Overview + +OpenAI GPT-2 model was proposed in [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) by Alec +Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever from [OpenAI](https://huggingface.co/openai). It's a causal (unidirectional) +transformer pretrained using language modeling on a very large corpus of ~40 GB of text data. + +The abstract from the paper is the following: + +*GPT-2 is a large transformer-based language model with 1.5 billion parameters, trained on a dataset[1] of 8 million +web pages. GPT-2 is trained with a simple objective: predict the next word, given all of the previous words within some +text. The diversity of the dataset causes this simple goal to contain naturally occurring demonstrations of many tasks +across diverse domains. GPT-2 is a direct scale-up of GPT, with more than 10X the parameters and trained on more than +10X the amount of data.* + +[Write With Transformer](https://transformer.huggingface.co/doc/gpt2-large) is a webapp created and hosted by +Hugging Face showcasing the generative capabilities of several models. GPT-2 is one of them and is available in five +different sizes: small, medium, large, xl and a distilled version of the small checkpoint: *distilgpt-2*. + +This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://openai.com/blog/better-language-models/). + +## Usage tips + +- GPT-2 is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. +- GPT-2 was trained with a causal language modeling (CLM) objective and is therefore powerful at predicting the next + token in a sequence. Leveraging this feature allows GPT-2 to generate syntactically coherent text as it can be + observed in the *run_generation.py* example script. +- The model can take the *past_key_values* (for PyTorch) or *past* (for TF) as input, which is the previously computed + key/value attention pairs. Using this (*past_key_values* or *past*) value prevents the model from re-computing + pre-computed values in the context of text generation. For PyTorch, see *past_key_values* argument of the + [`GPT2Model.forward`] method, or for TF the *past* argument of the + [`TFGPT2Model.call`] method for more information on its usage. +- Enabling the *scale_attn_by_inverse_layer_idx* and *reorder_and_upcast_attn* flags will apply the training stability + improvements from [Mistral](https://github.com/stanford-crfm/mistral/) (for PyTorch only). + +## Usage example + +The `generate()` method can be used to generate text using GPT2 model. + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> model = AutoModelForCausalLM.from_pretrained("gpt2") +>>> tokenizer = AutoTokenizer.from_pretrained("gpt2") + +>>> prompt = "GPT2 is a model developed by OpenAI." + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens)[0] +``` + +## Using Flash Attention 2 + +Flash Attention 2 is a faster, optimized version of the attention scores computation which relies on `cuda` kernels. + +### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + +### Usage + +To load a model using Flash Attention 2, we can pass the argument `attn_implementation="flash_attention_2"` to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference: + +```python +>>> import torch +>>> from transformers import AutoModelForCausalLM, AutoTokenizer +>>> device = "cuda" # the device to load the model onto + +>>> model = AutoModelForCausalLM.from_pretrained("gpt2", torch_dtype=torch.float16, attn_implementation="flash_attention_2") +>>> tokenizer = AutoTokenizer.from_pretrained("gpt2") + +>>> prompt = "def hello_world():" + +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to(device) +>>> model.to(device) + +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +``` + + +### Expected speedups + +Below is an expected speedup diagram that compares pure inference time between the native implementation in transformers using `gpt2` checkpoint and the Flash Attention 2 version of the model using a sequence length of 512. + +
+ +
+ + +## Using Scaled Dot Product Attention (SDPA) +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +```python +from transformers import AutoModelForCausalLM +model = AutoModelForCausalLM.from_pretrained("gpt2", torch_dtype=torch.float16, attn_implementation="sdpa") +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (rtx3080ti-16GB, PyTorch 2.2.1, OS Ubuntu 22.04) using `float16` with +[gpt2-large](https://huggingface.co/openai-community/gpt2-large), we saw the +following speedups during training and inference. + +### Training +| Batch size | Seq len | Time per batch (Eager - s) | Time per batch (SDPA - s) | Speedup (%) | Eager peak mem (MB) | SDPA peak mem (MB) | Mem saving (%) | +|-----------:|--------:|----------------------------:|--------------------------:|------------:|--------------------:|-------------------:|------------------:| +| 1 | 128 | 0.039 | 0.032 | 23.042 | 3482.32 | 3494.62 | -0.352 | +| 1 | 256 | 0.073 | 0.059 | 25.15 | 3546.66 | 3552.6 | -0.167 | +| 1 | 512 | 0.155 | 0.118 | 30.96 | 4230.1 | 3665.59 | 15.4 | +| 1 | 1024 | 0.316 | 0.209 | 50.839 | 8682.26 | 4881.09 | 77.875 | +| 2 | 128 | 0.07 | 0.06 | 15.324 | 3557.8 | 3545.91 | 0.335 | +| 2 | 256 | 0.143 | 0.122 | 16.53 | 3901.5 | 3657.68 | 6.666 | +| 2 | 512 | 0.267 | 0.213 | 25.626 | 7062.21 | 4876.47 | 44.822 | +| 2 | 1024 | OOM | 0.404 | / | OOM | 8096.35 | SDPA does not OOM | +| 4 | 128 | 0.134 | 0.128 | 4.412 | 3675.79 | 3648.72 | 0.742 | +| 4 | 256 | 0.243 | 0.217 | 12.292 | 6129.76 | 4871.12 | 25.839 | +| 4 | 512 | 0.494 | 0.406 | 21.687 | 12466.6 | 8102.64 | 53.858 | +| 4 | 1024 | OOM | 0.795 | / | OOM | 14568.2 | SDPA does not OOM | + +### Inference +| Batch size | Seq len | Per token latency Eager (ms) | Per token latency SDPA (ms) | Speedup (%) | Mem Eager (MB) | Mem SDPA (MB) | Mem saved (%) | +|-----------:|--------:|-----------------------------:|----------------------------:|------------:|---------------:|--------------:|--------------:| +| 1 | 128 | 7.991 | 6.968 | 14.681 | 1685.2 | 1701.32 | -0.947 | +| 1 | 256 | 8.462 | 7.199 | 17.536 | 1745.49 | 1770.78 | -1.428 | +| 1 | 512 | 8.68 | 7.853 | 10.529 | 1907.69 | 1921.29 | -0.708 | +| 1 | 768 | 9.101 | 8.365 | 8.791 | 2032.93 | 2068.12 | -1.701 | +| 2 | 128 | 9.169 | 9.001 | 1.861 | 1803.84 | 1811.4 | -0.418 | +| 2 | 256 | 9.907 | 9.78 | 1.294 | 1907.72 | 1921.44 | -0.714 | +| 2 | 512 | 11.519 | 11.644 | -1.071 | 2176.86 | 2197.75 | -0.951 | +| 2 | 768 | 13.022 | 13.407 | -2.873 | 2464.3 | 2491.06 | -1.074 | +| 4 | 128 | 10.097 | 9.831 | 2.709 | 1942.25 | 1985.13 | -2.16 | +| 4 | 256 | 11.599 | 11.398 | 1.764 | 2177.28 | 2197.86 | -0.937 | +| 4 | 512 | 14.653 | 14.45 | 1.411 | 2753.16 | 2772.57 | -0.7 | +| 4 | 768 | 17.846 | 17.617 | 1.299 | 3327.04 | 3343.97 | -0.506 | + + + + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GPT2. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A blog on how to [Finetune a non-English GPT-2 Model with Hugging Face](https://www.philschmid.de/fine-tune-a-non-english-gpt-2-model-with-huggingface). +- A blog on [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) with GPT-2. +- A blog on [Training CodeParrot 🦜 from Scratch](https://huggingface.co/blog/codeparrot), a large GPT-2 model. +- A blog on [Faster Text Generation with TensorFlow and XLA](https://huggingface.co/blog/tf-xla-generate) with GPT-2. +- A blog on [How to train a Language Model with Megatron-LM](https://huggingface.co/blog/megatron-training) with a GPT-2 model. +- A notebook on how to [finetune GPT2 to generate lyrics in the style of your favorite artist](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb). 🌎 +- A notebook on how to [finetune GPT2 to generate tweets in the style of your favorite Twitter user](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb). 🌎 +- [Causal language modeling](https://huggingface.co/course/en/chapter7/6?fw=pt#training-a-causal-language-model-from-scratch) chapter of the 🤗 Hugging Face Course. +- [`GPT2LMHeadModel`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#gpt-2gpt-and-causal-language-modeling), [text generation example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation), and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFGPT2LMHeadModel`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_clmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxGPT2LMHeadModel`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#causal-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/causal_language_modeling_flax.ipynb). +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Causal language modeling task guide](../tasks/language_modeling) + +## GPT2Config + +[[autodoc]] GPT2Config + +## GPT2Tokenizer + +[[autodoc]] GPT2Tokenizer + - save_vocabulary + +## GPT2TokenizerFast + +[[autodoc]] GPT2TokenizerFast + +## GPT2 specific outputs + +[[autodoc]] models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput + +[[autodoc]] models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput + + + + +## GPT2Model + +[[autodoc]] GPT2Model + - forward + +## GPT2LMHeadModel + +[[autodoc]] GPT2LMHeadModel + - forward + +## GPT2DoubleHeadsModel + +[[autodoc]] GPT2DoubleHeadsModel + - forward + +## GPT2ForQuestionAnswering + +[[autodoc]] GPT2ForQuestionAnswering + - forward + +## GPT2ForSequenceClassification + +[[autodoc]] GPT2ForSequenceClassification + - forward + +## GPT2ForTokenClassification + +[[autodoc]] GPT2ForTokenClassification + - forward + + + + +## TFGPT2Model + +[[autodoc]] TFGPT2Model + - call + +## TFGPT2LMHeadModel + +[[autodoc]] TFGPT2LMHeadModel + - call + +## TFGPT2DoubleHeadsModel + +[[autodoc]] TFGPT2DoubleHeadsModel + - call + +## TFGPT2ForSequenceClassification + +[[autodoc]] TFGPT2ForSequenceClassification + - call + +## TFSequenceClassifierOutputWithPast + +[[autodoc]] modeling_tf_outputs.TFSequenceClassifierOutputWithPast + +## TFGPT2Tokenizer + +[[autodoc]] TFGPT2Tokenizer + + + + +## FlaxGPT2Model + +[[autodoc]] FlaxGPT2Model + - __call__ + +## FlaxGPT2LMHeadModel + +[[autodoc]] FlaxGPT2LMHeadModel + - __call__ + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_bigcode.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_bigcode.md new file mode 100644 index 0000000000000000000000000000000000000000..648fa6cb8d605491129c797ad3f20e0f0e3bff29 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_bigcode.md @@ -0,0 +1,112 @@ + + +# GPTBigCode + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The GPTBigCode model was proposed in [SantaCoder: don't reach for the stars!](https://arxiv.org/abs/2301.03988) by BigCode. The listed authors are: Loubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, Logesh Kumar Umapathi, Carolyn Jane Anderson, Yangtian Zi, Joel Lamy Poirier, Hailey Schoelkopf, Sergey Troshin, Dmitry Abulkhanov, Manuel Romero, Michael Lappert, Francesco De Toni, Bernardo García del Río, Qian Liu, Shamik Bose, Urvashi Bhattacharyya, Terry Yue Zhuo, Ian Yu, Paulo Villegas, Marco Zocca, Sourab Mangrulkar, David Lansky, Huu Nguyen, Danish Contractor, Luis Villa, Jia Li, Dzmitry Bahdanau, Yacine Jernite, Sean Hughes, Daniel Fried, Arjun Guha, Harm de Vries, Leandro von Werra. + +The abstract from the paper is the following: + +*The BigCode project is an open-scientific collaboration working on the responsible development of large language models for code. This tech report describes the progress of the collaboration until December 2022, outlining the current state of the Personally Identifiable Information (PII) redaction pipeline, the experiments conducted to de-risk the model architecture, and the experiments investigating better preprocessing methods for the training data. We train 1.1B parameter models on the Java, JavaScript, and Python subsets of The Stack and evaluate them on the MultiPL-E text-to-code benchmark. We find that more aggressive filtering of near-duplicates can further boost performance and, surprisingly, that selecting files from repositories with 5+ GitHub stars deteriorates performance significantly. Our best model outperforms previous open-source multilingual code generation models (InCoder-6.7B and CodeGen-Multi-2.7B) in both left-to-right generation and infilling on the Java, JavaScript, and Python portions of MultiPL-E, despite being a substantially smaller model. All models are released under an OpenRAIL license at [this https URL.](https://huggingface.co/bigcode)* + +The model is an optimized [GPT2 model](https://huggingface.co/docs/transformers/model_doc/gpt2) with support for Multi-Query Attention. + +## Implementation details + +The main differences compared to GPT2. +- Added support for Multi-Query Attention. +- Use `gelu_pytorch_tanh` instead of classic `gelu`. +- Avoid unnecessary synchronizations (this has since been added to GPT2 in #20061, but wasn't in the reference codebase). +- Use Linear layers instead of Conv1D (good speedup but makes the checkpoints incompatible). +- Merge `_attn` and `_upcast_and_reordered_attn`. Always merge the matmul with scaling. Rename `reorder_and_upcast_attn`->`attention_softmax_in_fp32` +- Cache the attention mask value to avoid recreating it every time. +- Use jit to fuse the attention fp32 casting, masking, softmax, and scaling. +- Combine the attention and causal masks into a single one, pre-computed for the whole model instead of every layer. +- Merge the key and value caches into one (this changes the format of layer_past/ present, does it risk creating problems?) +- Use the memory layout (self.num_heads, 3, self.head_dim) instead of `(3, self.num_heads, self.head_dim)` for the QKV tensor with MHA. (prevents an overhead with the merged key and values, but makes the checkpoints incompatible with the original openai-community/gpt2 model). + +You can read more about the optimizations in the [original pull request](https://github.com/huggingface/transformers/pull/22575) + +## Combining Starcoder and Flash Attention 2 + +First, make sure to install the latest version of Flash Attention 2 to include the sliding window attention feature. + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of flash-attn repository. Make also sure to load your model in half-precision (e.g. `torch.float16``) + +To load and run a model using Flash Attention 2, refer to the snippet below: + +```python +>>> import torch +>>> from transformers import AutoModelForCausalLM, AutoTokenizer +>>> device = "cuda" # the device to load the model onto + +>>> model = AutoModelForCausalLM.from_pretrained("bigcode/gpt_bigcode-santacoder", torch_dtype=torch.float16, attn_implementation="flash_attention_2") +>>> tokenizer = AutoTokenizer.from_pretrained("bigcode/gpt_bigcode-santacoder") + +>>> prompt = "def hello_world():" + +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to(device) +>>> model.to(device) + +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=30, do_sample=False) +>>> tokenizer.batch_decode(generated_ids)[0] +'def hello_world():\n print("hello world")\n\nif __name__ == "__main__":\n print("hello world")\n<|endoftext|>' +``` + +### Expected speedups + +Below is a expected speedup diagram that compares pure inference time between the native implementation in transformers using `bigcode/starcoder` checkpoint and the Flash Attention 2 version of the model using two different sequence lengths. + +
+ +
+ + +## GPTBigCodeConfig + +[[autodoc]] GPTBigCodeConfig + +## GPTBigCodeModel + +[[autodoc]] GPTBigCodeModel + - forward + +## GPTBigCodeForCausalLM + +[[autodoc]] GPTBigCodeForCausalLM + - forward + +## GPTBigCodeForSequenceClassification + +[[autodoc]] GPTBigCodeForSequenceClassification + - forward + +## GPTBigCodeForTokenClassification + +[[autodoc]] GPTBigCodeForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neo.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neo.md new file mode 100644 index 0000000000000000000000000000000000000000..f90e0d18498f52452521db3bb683ef07479d54ac --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neo.md @@ -0,0 +1,154 @@ + + +# GPT Neo + +
+PyTorch +Flax +FlashAttention +
+ +## Overview + +The GPTNeo model was released in the [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) repository by Sid +Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy. It is a GPT2 like causal language model trained on the +[Pile](https://pile.eleuther.ai/) dataset. + +The architecture is similar to GPT2 except that GPT Neo uses local attention in every other layer with a window size of +256 tokens. + +This model was contributed by [valhalla](https://huggingface.co/valhalla). + +## Usage example + +The `generate()` method can be used to generate text using GPT Neo model. + +```python +>>> from transformers import GPTNeoForCausalLM, GPT2Tokenizer + +>>> model = GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B") +>>> tokenizer = GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B") + +>>> prompt = ( +... "In a shocking finding, scientists discovered a herd of unicorns living in a remote, " +... "previously unexplored valley, in the Andes Mountains. Even more surprising to the " +... "researchers was the fact that the unicorns spoke perfect English." +... ) + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens)[0] +``` + +## Combining GPT-Neo and Flash Attention 2 + +First, make sure to install the latest version of Flash Attention 2 to include the sliding window attention feature, and make sure your hardware is compatible with Flash-Attention 2. More details are available [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one#flashattention-2) concerning the installation. + +Make sure as well to load your model in half-precision (e.g. `torch.float16`). + +To load and run a model using Flash Attention 2, refer to the snippet below: + +```python +>>> import torch +>>> from transformers import AutoModelForCausalLM, AutoTokenizer +>>> device = "cuda" # the device to load the model onto + +>>> model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-neo-2.7B", torch_dtype=torch.float16, attn_implementation="flash_attention_2") +>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-2.7B") + +>>> prompt = "def hello_world():" + +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to(device) +>>> model.to(device) + +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +"def hello_world():\n >>> run_script("hello.py")\n >>> exit(0)\n<|endoftext|>" +``` + +### Expected speedups + +Below is an expected speedup diagram that compares pure inference time between the native implementation in transformers using `EleutherAI/gpt-neo-2.7B` checkpoint and the Flash Attention 2 version of the model. +Note that for GPT-Neo it is not possible to train / run on very long context as the max [position embeddings](https://huggingface.co/EleutherAI/gpt-neo-2.7B/blob/main/config.json#L58 ) is limited to 2048 - but this is applicable to all gpt-neo models and not specific to FA-2 + +
+ +
+ + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Causal language modeling task guide](../tasks/language_modeling) + +## GPTNeoConfig + +[[autodoc]] GPTNeoConfig + + + + + +## GPTNeoModel + +[[autodoc]] GPTNeoModel + - forward + +## GPTNeoForCausalLM + +[[autodoc]] GPTNeoForCausalLM + - forward + +## GPTNeoForQuestionAnswering + +[[autodoc]] GPTNeoForQuestionAnswering + - forward + +## GPTNeoForSequenceClassification + +[[autodoc]] GPTNeoForSequenceClassification + - forward + +## GPTNeoForTokenClassification + +[[autodoc]] GPTNeoForTokenClassification + - forward + + + + +## FlaxGPTNeoModel + +[[autodoc]] FlaxGPTNeoModel + - __call__ + +## FlaxGPTNeoForCausalLM + +[[autodoc]] FlaxGPTNeoForCausalLM + - __call__ + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox.md new file mode 100644 index 0000000000000000000000000000000000000000..35f12bdb2128d88f83361a861894a8d35d04eb82 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox.md @@ -0,0 +1,200 @@ + + +# GPT-NeoX + +
+PyTorch +SDPA +
+ +## Overview + +We introduce GPT-NeoX-20B, a 20 billion parameter autoregressive language model trained on the Pile, whose weights will +be made freely and openly available to the public through a permissive license. It is, to the best of our knowledge, +the largest dense autoregressive model that has publicly available weights at the time of submission. In this work, +we describe GPT-NeoX-20B's architecture and training and evaluate its performance on a range of language-understanding, +mathematics, and knowledge-based tasks. We find that GPT-NeoX-20B is a particularly powerful few-shot reasoner and +gains far more in performance when evaluated five-shot than similarly sized GPT-3 and FairSeq models. We open-source +the training and evaluation code, as well as the model weights, at [https://github.com/EleutherAI/gpt-neox](https://github.com/EleutherAI/gpt-neox). + +Development of the model was led by Sid Black, Stella Biderman and Eric Hallahan, and the model was trained with +generous the support of [CoreWeave](https://www.coreweave.com/). + +GPT-NeoX-20B was trained with fp16, thus it is recommended to initialize the model as follows: + +```python +model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b").half().cuda() +``` + +GPT-NeoX-20B also has a different tokenizer from the one used in GPT-J-6B and GPT-Neo. The new tokenizer allocates +additional tokens to whitespace characters, making the model more suitable for certain tasks like code generation. + +## Usage example + +The `generate()` method can be used to generate text using GPT Neo model. + +```python +>>> from transformers import GPTNeoXForCausalLM, GPTNeoXTokenizerFast + +>>> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b") +>>> tokenizer = GPTNeoXTokenizerFast.from_pretrained("EleutherAI/gpt-neox-20b") + +>>> prompt = "GPTNeoX20B is a 20B-parameter autoregressive Transformer model developed by EleutherAI." + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens)[0] +``` + +## Using Flash Attention 2 + +Flash Attention 2 is an faster, optimized version of the model. + +### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + +### Usage + +To load a model using Flash Attention 2, we can pass the argument `attn_implementation="flash_attention_2"` to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference: + +```python +>>> from transformers import GPTNeoXForCausalLM, GPTNeoXTokenizerFast + +model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) +... +``` + + +### Expected speedups + +Below is an expected speedup diagram that compares pure inference time between the native implementation in transformers using `stockmark/gpt-neox-japanese-1.4b` checkpoint and the Flash Attention 2 version of the model using a sequence length of 2048. + +
+ +
+ + +## Using Scaled Dot Product Attention (SDPA) +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +```python +from transformers import GPTNeoXForCausalLM +model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", torch_dtype=torch.float16, attn_implementation="sdpa") +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). + +On a local benchmark (rtx3080ti-16GB, PyTorch 2.2.1, OS Ubuntu 22.04) using `float16` with +[pythia-410m-deduped](https://huggingface.co/EleutherAI/pythia-410m-deduped), we saw the +following speedups during training and inference. + +### Training +| Batch size | Seq len | Time per batch (Eager - s) | Time per batch (SDPA - s) | Speedup (%) | Eager peak mem (MB) | SDPA peak mem (MB) | Mem saving (%) | +|-----------:|-----------:|---------------------------:|-----------------------------:|------------:|--------------------:|-------------------:|------------------:| +| 1 | 128 | 0.024 | 0.019 | 28.945 | 1789.95 | 1789.95 | 0 | +| 1 | 256 | 0.039 | 0.031 | 23.18 | 1845.83 | 1844.84 | 0.053 | +| 1 | 512 | 0.08 | 0.055 | 45.524 | 2278.38 | 1953.76 | 16.615 | +| 1 | 1024 | 0.19 | 0.102 | 86.777 | 4772.36 | 2408.35 | 98.159 | +| 1 | 2048 | 0.565 | 0.204 | 177.098 | 13484.1 | 3882.01 | 247.348 | +| 2 | 128 | 0.037 | 0.032 | 15.121 | 1843.86 | 1844.78 | -0.05 | +| 2 | 256 | 0.067 | 0.055 | 21.706 | 1999.72 | 1951.67 | 2.462 | +| 2 | 512 | 0.144 | 0.096 | 50.046 | 3613.16 | 2406.77 | 50.125 | +| 2 | 1024 | 0.366 | 0.193 | 89.666 | 8707.55 | 3878.86 | 124.487 | +| 2 | 2048 | OOM | 0.379 | / | OOM | 6825.13 | SDPA does not OOM | +| 4 | 128 | 0.06 | 0.054 | 11.539 | 1947.6 | 1952.06 | -0.228 | +| 4 | 256 | 0.119 | 0.093 | 28.072 | 3008.39 | 2405.99 | 25.038 | +| 4 | 512 | 0.275 | 0.187 | 47.145 | 6290.58 | 3877.29 | 62.242 | +| 4 | 1024 | OOM | 0.36 | / | OOM | 6821.98 | SDPA does not OOM | +| 4 | 2048 | OOM | 0.731 | / | OOM | 12705.1 | SDPA does not OOM | + +### Inference +| Batch size | Seq len | Per token latency Eager (ms) | Per token latency SDPA (ms) | Speedup (%) | Mem Eager (MB) | Mem SDPA (MB) | Mem saved (%) | +|--------------:|-------------:|--------------------------------:|-------------------------------:|---------------:|------------------:|----------------:|-----------------:| +| 1 | 128 | 6.569 | 5.858 | 12.14 | 974.831 | 974.826 | 0 | +| 1 | 256 | 7.009 | 5.863 | 19.542 | 1029.01 | 1028.08 | 0.09 | +| 1 | 512 | 7.157 | 5.965 | 19.983 | 1137.54 | 1137.52 | 0.001 | +| 1 | 1024 | 7.523 | 6.506 | 15.637 | 1329.3 | 1329.26 | 0.003 | +| 1 | 2048 | 9.271 | 9.205 | 0.713 | 1752.47 | 1734.51 | 1.036 | +| 2 | 128 | 7.239 | 5.959 | 21.493 | 1044.8 | 1028.37 | 1.597 | +| 2 | 256 | 7.228 | 6.036 | 19.757 | 1167.32 | 1137.73 | 2.601 | +| 2 | 512 | 7.538 | 6.693 | 12.628 | 1352.93 | 1329.55 | 1.758 | +| 2 | 1024 | 8.916 | 8.632 | 3.291 | 1752.56 | 1734.62 | 1.034 | +| 2 | 2048 | 12.628 | 12.606 | 0.181 | 2558.72 | 2545.8 | 0.508 | +| 4 | 128 | 7.278 | 6.046 | 20.373 | 1168.41 | 1137.79 | 2.691 | +| 4 | 256 | 7.614 | 6.588 | 15.574 | 1353.1 | 1329.79 | 1.753 | +| 4 | 512 | 8.798 | 8.144 | 8.028 | 1752.76 | 1734.85 | 1.032 | +| 4 | 1024 | 11.765 | 11.303 | 4.09 | 2558.96 | 2546.04 | 0.508 | +| 4 | 2048 | 19.568 | 17.735 | 10.33 | 4175.5 | 4165.26 | 0.246 | + + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) + +## GPTNeoXConfig + +[[autodoc]] GPTNeoXConfig + +## GPTNeoXTokenizerFast + +[[autodoc]] GPTNeoXTokenizerFast + +## GPTNeoXModel + +[[autodoc]] GPTNeoXModel + - forward + +## GPTNeoXForCausalLM + +[[autodoc]] GPTNeoXForCausalLM + - forward + +## GPTNeoXForQuestionAnswering + +[[autodoc]] GPTNeoXForQuestionAnswering + - forward + +## GPTNeoXForSequenceClassification + +[[autodoc]] GPTNeoXForSequenceClassification + - forward + +## GPTNeoXForTokenClassification + +[[autodoc]] GPTNeoXForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox_japanese.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox_japanese.md new file mode 100644 index 0000000000000000000000000000000000000000..cedfafa133e459fc79722780a43b385e26879d64 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gpt_neox_japanese.md @@ -0,0 +1,79 @@ + + +# GPT-NeoX-Japanese + +
+PyTorch +FlashAttention +
+ +## Overview + +We introduce GPT-NeoX-Japanese, which is an autoregressive language model for Japanese, trained on top of [https://github.com/EleutherAI/gpt-neox](https://github.com/EleutherAI/gpt-neox). +Japanese is a unique language with its large vocabulary and a combination of hiragana, katakana, and kanji writing scripts. +To address this distinct structure of the Japanese language, we use a [special sub-word tokenizer](https://github.com/tanreinama/Japanese-BPEEncoder_V2). We are very grateful to *tanreinama* for open-sourcing this incredibly helpful tokenizer. +Following the recommendations from Google's research on [PaLM](https://ai.googleblog.com/2022/04/pathways-language-model-palm-scaling-to.html), we have removed bias parameters from transformer blocks, achieving better model performance. Please refer [this article](https://medium.com/ml-abeja/training-a-better-gpt-2-93b157662ae4) in detail. + +Development of the model was led by [Shinya Otani](https://github.com/SO0529), [Takayoshi Makabe](https://github.com/spider-man-tm), [Anuj Arora](https://github.com/Anuj040), and [Kyo Hattori](https://github.com/go5paopao) from [ABEJA, Inc.](https://www.abejainc.com/). For more information on this model-building activity, please refer [here (ja)](https://tech-blog.abeja.asia/entry/abeja-gpt-project-202207). + +### Usage example + +The `generate()` method can be used to generate text using GPT NeoX Japanese model. + +```python +>>> from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseTokenizer + +>>> model = GPTNeoXJapaneseForCausalLM.from_pretrained("abeja/gpt-neox-japanese-2.7b") +>>> tokenizer = GPTNeoXJapaneseTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b") + +>>> prompt = "人とAIが協調するためには、" + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)[0] + +>>> print(gen_text) +人とAIが協調するためには、AIと人が共存し、AIを正しく理解する必要があります。 +``` + +## Resources + +- [Causal language modeling task guide](../tasks/language_modeling) + +## GPTNeoXJapaneseConfig + +[[autodoc]] GPTNeoXJapaneseConfig + +## GPTNeoXJapaneseTokenizer + +[[autodoc]] GPTNeoXJapaneseTokenizer + +## GPTNeoXJapaneseModel + +[[autodoc]] GPTNeoXJapaneseModel + - forward + +## GPTNeoXJapaneseForCausalLM + +[[autodoc]] GPTNeoXJapaneseForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptj.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptj.md new file mode 100644 index 0000000000000000000000000000000000000000..8e852d931aae0a6e96622fae2d5e455d24f2d0c9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptj.md @@ -0,0 +1,208 @@ + + +# GPT-J + +
+PyTorch +TensorFlow +Flax +FlashAttention +
+ +## Overview + +The GPT-J model was released in the [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) repository by Ben Wang and Aran Komatsuzaki. It is a GPT-2-like +causal language model trained on [the Pile](https://pile.eleuther.ai/) dataset. + +This model was contributed by [Stella Biderman](https://huggingface.co/stellaathena). + +## Usage tips + +- To load [GPT-J](https://huggingface.co/EleutherAI/gpt-j-6B) in float32 one would need at least 2x model size + RAM: 1x for initial weights and another 1x to load the checkpoint. So for GPT-J it would take at least 48GB + RAM to just load the model. To reduce the RAM usage there are a few options. The `torch_dtype` argument can be + used to initialize the model in half-precision on a CUDA device only. There is also a fp16 branch which stores the fp16 weights, + which could be used to further minimize the RAM usage: + +```python +>>> from transformers import GPTJForCausalLM +>>> import torch + +>>> device = "cuda" +>>> model = GPTJForCausalLM.from_pretrained( +... "EleutherAI/gpt-j-6B", +... revision="float16", +... torch_dtype=torch.float16, +... ).to(device) +``` + +- The model should fit on 16GB GPU for inference. For training/fine-tuning it would take much more GPU RAM. Adam + optimizer for example makes four copies of the model: model, gradients, average and squared average of the gradients. + So it would need at least 4x model size GPU memory, even with mixed precision as gradient updates are in fp32. This + is not including the activations and data batches, which would again require some more GPU RAM. So one should explore + solutions such as DeepSpeed, to train/fine-tune the model. Another option is to use the original codebase to + train/fine-tune the model on TPU and then convert the model to Transformers format for inference. Instructions for + that could be found [here](https://github.com/kingoflolz/mesh-transformer-jax/blob/master/howto_finetune.md) + +- Although the embedding matrix has a size of 50400, only 50257 entries are used by the GPT-2 tokenizer. These extra + tokens are added for the sake of efficiency on TPUs. To avoid the mismatch between embedding matrix size and vocab + size, the tokenizer for [GPT-J](https://huggingface.co/EleutherAI/gpt-j-6B) contains 143 extra tokens + `<|extratoken_1|>... <|extratoken_143|>`, so the `vocab_size` of tokenizer also becomes 50400. + +## Usage examples + +The [`~generation.GenerationMixin.generate`] method can be used to generate text using GPT-J +model. + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-j-6B") +>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B") + +>>> prompt = ( +... "In a shocking finding, scientists discovered a herd of unicorns living in a remote, " +... "previously unexplored valley, in the Andes Mountains. Even more surprising to the " +... "researchers was the fact that the unicorns spoke perfect English." +... ) + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens)[0] +``` + +...or in float16 precision: + +```python +>>> from transformers import GPTJForCausalLM, AutoTokenizer +>>> import torch + +>>> device = "cuda" +>>> model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", torch_dtype=torch.float16).to(device) +>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B") + +>>> prompt = ( +... "In a shocking finding, scientists discovered a herd of unicorns living in a remote, " +... "previously unexplored valley, in the Andes Mountains. Even more surprising to the " +... "researchers was the fact that the unicorns spoke perfect English." +... ) + +>>> input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device) + +>>> gen_tokens = model.generate( +... input_ids, +... do_sample=True, +... temperature=0.9, +... max_length=100, +... ) +>>> gen_text = tokenizer.batch_decode(gen_tokens)[0] +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GPT-J. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- Description of [GPT-J](https://huggingface.co/EleutherAI/gpt-j-6B). +- A blog on how to [Deploy GPT-J 6B for inference using Hugging Face Transformers and Amazon SageMaker](https://huggingface.co/blog/gptj-sagemaker). +- A blog on how to [Accelerate GPT-J inference with DeepSpeed-Inference on GPUs](https://www.philschmid.de/gptj-deepspeed-inference). +- A blog post introducing [GPT-J-6B: 6B JAX-Based Transformer](https://arankomatsuzaki.wordpress.com/2021/06/04/gpt-j/). 🌎 +- A notebook for [GPT-J-6B Inference Demo](https://colab.research.google.com/github/kingoflolz/mesh-transformer-jax/blob/master/colab_demo.ipynb). 🌎 +- Another notebook demonstrating [Inference with GPT-J-6B](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/GPT-J-6B/Inference_with_GPT_J_6B.ipynb). +- [Causal language modeling](https://huggingface.co/course/en/chapter7/6?fw=pt#training-a-causal-language-model-from-scratch) chapter of the 🤗 Hugging Face Course. +- [`GPTJForCausalLM`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#gpt-2gpt-and-causal-language-modeling), [text generation example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation), and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). +- [`TFGPTJForCausalLM`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_clmpy) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb). +- [`FlaxGPTJForCausalLM`] is supported by this [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#causal-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/causal_language_modeling_flax.ipynb). + +**Documentation resources** +- [Text classification task guide](../tasks/sequence_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) + +## GPTJConfig + +[[autodoc]] GPTJConfig + - all + + + + +## GPTJModel + +[[autodoc]] GPTJModel + - forward + +## GPTJForCausalLM + +[[autodoc]] GPTJForCausalLM + - forward + +## GPTJForSequenceClassification + +[[autodoc]] GPTJForSequenceClassification + - forward + +## GPTJForQuestionAnswering + +[[autodoc]] GPTJForQuestionAnswering + - forward + + + + +## TFGPTJModel + +[[autodoc]] TFGPTJModel + - call + +## TFGPTJForCausalLM + +[[autodoc]] TFGPTJForCausalLM + - call + +## TFGPTJForSequenceClassification + +[[autodoc]] TFGPTJForSequenceClassification + - call + +## TFGPTJForQuestionAnswering + +[[autodoc]] TFGPTJForQuestionAnswering + - call + + + + +## FlaxGPTJModel + +[[autodoc]] FlaxGPTJModel + - __call__ + +## FlaxGPTJForCausalLM + +[[autodoc]] FlaxGPTJForCausalLM + - __call__ + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptsan-japanese.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptsan-japanese.md new file mode 100644 index 0000000000000000000000000000000000000000..929e7330ceea261eabc8f94ccac8af35f66a4672 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/gptsan-japanese.md @@ -0,0 +1,133 @@ + + +# GPTSAN-japanese + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The GPTSAN-japanese model was released in the repository by Toshiyuki Sakamoto (tanreinama). + +GPTSAN is a Japanese language model using Switch Transformer. It has the same structure as the model introduced as Prefix LM +in the T5 paper, and support both Text Generation and Masked Language Modeling tasks. These basic tasks similarly can +fine-tune for translation or summarization. + +### Usage example + +The `generate()` method can be used to generate text using GPTSAN-Japanese model. + +```python +>>> from transformers import AutoModel, AutoTokenizer +>>> import torch + +>>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese") +>>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").cuda() +>>> x_tok = tokenizer("は、", prefix_text="織田信長", return_tensors="pt") +>>> torch.manual_seed(0) +>>> gen_tok = model.generate(x_tok.input_ids.cuda(), token_type_ids=x_tok.token_type_ids.cuda(), max_new_tokens=20) +>>> tokenizer.decode(gen_tok[0]) +'織田信長は、2004年に『戦国BASARA』のために、豊臣秀吉' +``` + +## GPTSAN Features + +GPTSAN has some unique features. It has a model structure of Prefix-LM. It works as a shifted Masked Language Model for Prefix Input tokens. Un-prefixed inputs behave like normal generative models. +The Spout vector is a GPTSAN specific input. Spout is pre-trained with random inputs, but you can specify a class of text or an arbitrary vector during fine-tuning. This allows you to indicate the tendency of the generated text. +GPTSAN has a sparse Feed Forward based on Switch-Transformer. You can also add other layers and train them partially. See the original GPTSAN repository for details. + +### Prefix-LM Model + +GPTSAN has the structure of the model named Prefix-LM in the `T5` paper. (The original GPTSAN repository calls it `hybrid`) +In GPTSAN, the `Prefix` part of Prefix-LM, that is, the input position that can be referenced by both tokens, can be specified with any length. +Arbitrary lengths can also be specified differently for each batch. +This length applies to the text entered in `prefix_text` for the tokenizer. +The tokenizer returns the mask of the `Prefix` part of Prefix-LM as `token_type_ids`. +The model treats the part where `token_type_ids` is 1 as a `Prefix` part, that is, the input can refer to both tokens before and after. + +## Usage tips + +Specifying the Prefix part is done with a mask passed to self-attention. +When token_type_ids=None or all zero, it is equivalent to regular causal mask + +for example: + +>>> x_token = tokenizer("アイウエ") +input_ids: | SOT | SEG | ア | イ | ウ | エ | +token_type_ids: | 1 | 0 | 0 | 0 | 0 | 0 | +prefix_lm_mask: +SOT | 1 0 0 0 0 0 | +SEG | 1 1 0 0 0 0 | +ア | 1 1 1 0 0 0 | +イ | 1 1 1 1 0 0 | +ウ | 1 1 1 1 1 0 | +エ | 1 1 1 1 1 1 | + +>>> x_token = tokenizer("", prefix_text="アイウエ") +input_ids: | SOT | ア | イ | ウ | エ | SEG | +token_type_ids: | 1 | 1 | 1 | 1 | 1 | 0 | +prefix_lm_mask: +SOT | 1 1 1 1 1 0 | +ア | 1 1 1 1 1 0 | +イ | 1 1 1 1 1 0 | +ウ | 1 1 1 1 1 0 | +エ | 1 1 1 1 1 0 | +SEG | 1 1 1 1 1 1 | + +>>> x_token = tokenizer("ウエ", prefix_text="アイ") +input_ids: | SOT | ア | イ | SEG | ウ | エ | +token_type_ids: | 1 | 1 | 1 | 0 | 0 | 0 | +prefix_lm_mask: +SOT | 1 1 1 0 0 0 | +ア | 1 1 1 0 0 0 | +イ | 1 1 1 0 0 0 | +SEG | 1 1 1 1 0 0 | +ウ | 1 1 1 1 1 0 | +エ | 1 1 1 1 1 1 | + +### Spout Vector + +A Spout Vector is a special vector for controlling text generation. +This vector is treated as the first embedding in self-attention to bring extraneous attention to the generated tokens. +In the pre-trained model published from `Tanrei/GPTSAN-japanese`, the Spout Vector is a 128-dimensional vector that passes through 8 fully connected layers in the model and is projected into the space acting as external attention. +The Spout Vector projected by the fully connected layer is split to be passed to all self-attentions. + +## GPTSanJapaneseConfig + +[[autodoc]] GPTSanJapaneseConfig + +## GPTSanJapaneseTokenizer + +[[autodoc]] GPTSanJapaneseTokenizer + +## GPTSanJapaneseModel + +[[autodoc]] GPTSanJapaneseModel + +## GPTSanJapaneseForConditionalGeneration + +[[autodoc]] GPTSanJapaneseForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granite.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granite.md new file mode 100644 index 0000000000000000000000000000000000000000..0326bc5ad24a33b2a60520dcf8ee59186565cbf6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granite.md @@ -0,0 +1,80 @@ + + +# Granite + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Granite model was proposed in [Power Scheduler: A Batch Size and Token Number Agnostic Learning Rate Scheduler](https://arxiv.org/abs/2408.13359) by Yikang Shen, Matthew Stallone, Mayank Mishra, Gaoyuan Zhang, Shawn Tan, Aditya Prasad, Adriana Meza Soria, David D. Cox and Rameswar Panda. + +PowerLM-3B is a 3B state-of-the-art small language model trained with the Power learning rate scheduler. It is trained on a wide range of open-source and synthetic datasets with permissive licenses. PowerLM-3B has shown promising results compared to other models in the size categories across various benchmarks, including natural language multi-choices, code generation, and math reasoning. + +The abstract from the paper is the following: + +*Finding the optimal learning rate for language model pretraining is a challenging task. +This is not only because there is a complicated correlation between learning rate, batch size, number of training tokens, model size, and other hyperparameters but also because it is prohibitively expensive to perform a hyperparameter search for large language models with Billions or Trillions of parameters. Recent studies propose using small proxy models and small corpus to perform hyperparameter searches and transposing the optimal parameters to large models and large corpus. While the zero-shot transferability is theoretically and empirically proven for model size related hyperparameters, like depth and width, the zero-shot transfer from small corpus to large corpus is underexplored. +In this paper, we study the correlation between optimal learning rate, batch size, and number of training tokens for the recently proposed WSD scheduler. After thousands of small experiments, we found a power-law relationship between variables and demonstrated its transferability across model sizes. Based on the observation, we propose a new learning rate scheduler, Power scheduler, that is agnostic about the number of training tokens and batch size. The experiment shows that combining the Power scheduler with Maximum Update Parameterization (\mup) can consistently achieve impressive performance with one set of hyperparameters regardless of the number of training tokens, batch size, model size, and even model architecture. Our 3B dense and MoE models trained with the Power scheduler achieve comparable performance as state-of-the-art small language models. +We [open source](https://huggingface.co/collections/ibm/power-lm-66be64ae647ddf11b9808000) these pretrained models.* + +Tips: + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_path = "ibm/PowerLM-3b" +tokenizer = AutoTokenizer.from_pretrained(model_path) + +# drop device_map if running on CPU +model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto") +model.eval() + +# change input text as desired +prompt = "Write a code to find the maximum value in a list of numbers." + +# tokenize the text +input_tokens = tokenizer(prompt, return_tensors="pt") +# generate output tokens +output = model.generate(**input_tokens, max_new_tokens=100) +# decode output tokens into text +output = tokenizer.batch_decode(output) +# loop over the batch to print, in this example the batch size is 1 +for i in output: + print(i) +``` + +This model was contributed by [mayank-mishra](https://huggingface.co/mayank-mishra). + + +## GraniteConfig + +[[autodoc]] GraniteConfig + +## GraniteModel + +[[autodoc]] GraniteModel + - forward + +## GraniteForCausalLM + +[[autodoc]] GraniteForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoe.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoe.md new file mode 100644 index 0000000000000000000000000000000000000000..56ba5d936c9d4fd6205ee5ed616f3b7d374236a5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoe.md @@ -0,0 +1,80 @@ + + +# GraniteMoe + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The GraniteMoe model was proposed in [Power Scheduler: A Batch Size and Token Number Agnostic Learning Rate Scheduler](https://arxiv.org/abs/2408.13359) by Yikang Shen, Matthew Stallone, Mayank Mishra, Gaoyuan Zhang, Shawn Tan, Aditya Prasad, Adriana Meza Soria, David D. Cox and Rameswar Panda. + +PowerMoE-3B is a 3B sparse Mixture-of-Experts (sMoE) language model trained with the Power learning rate scheduler. It sparsely activates 800M parameters for each token. It is trained on a mix of open-source and proprietary datasets. PowerMoE-3B has shown promising results compared to other dense models with 2x activate parameters across various benchmarks, including natural language multi-choices, code generation, and math reasoning. + +The abstract from the paper is the following: + +*Finding the optimal learning rate for language model pretraining is a challenging task. +This is not only because there is a complicated correlation between learning rate, batch size, number of training tokens, model size, and other hyperparameters but also because it is prohibitively expensive to perform a hyperparameter search for large language models with Billions or Trillions of parameters. Recent studies propose using small proxy models and small corpus to perform hyperparameter searches and transposing the optimal parameters to large models and large corpus. While the zero-shot transferability is theoretically and empirically proven for model size related hyperparameters, like depth and width, the zero-shot transfer from small corpus to large corpus is underexplored. +In this paper, we study the correlation between optimal learning rate, batch size, and number of training tokens for the recently proposed WSD scheduler. After thousands of small experiments, we found a power-law relationship between variables and demonstrated its transferability across model sizes. Based on the observation, we propose a new learning rate scheduler, Power scheduler, that is agnostic about the number of training tokens and batch size. The experiment shows that combining the Power scheduler with Maximum Update Parameterization (\mup) can consistently achieve impressive performance with one set of hyperparameters regardless of the number of training tokens, batch size, model size, and even model architecture. Our 3B dense and MoE models trained with the Power scheduler achieve comparable performance as state-of-the-art small language models. +We [open source](https://huggingface.co/collections/ibm/power-lm-66be64ae647ddf11b9808000) these pretrained models.* + +Tips: + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_path = "ibm/PowerMoE-3b" +tokenizer = AutoTokenizer.from_pretrained(model_path) + +# drop device_map if running on CPU +model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto") +model.eval() + +# change input text as desired +prompt = "Write a code to find the maximum value in a list of numbers." + +# tokenize the text +input_tokens = tokenizer(prompt, return_tensors="pt") +# generate output tokens +output = model.generate(**input_tokens, max_new_tokens=100) +# decode output tokens into text +output = tokenizer.batch_decode(output) +# loop over the batch to print, in this example the batch size is 1 +for i in output: + print(i) +``` + +This model was contributed by [mayank-mishra](https://huggingface.co/mayank-mishra). + + +## GraniteMoeConfig + +[[autodoc]] GraniteMoeConfig + +## GraniteMoeModel + +[[autodoc]] GraniteMoeModel + - forward + +## GraniteMoeForCausalLM + +[[autodoc]] GraniteMoeForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoeshared.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoeshared.md new file mode 100644 index 0000000000000000000000000000000000000000..38eb7daf8c92ae78a0ff4b5526ffa428ba7e72f5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitemoeshared.md @@ -0,0 +1,66 @@ + + +# GraniteMoeShared + +## Overview + + +The GraniteMoe model was proposed in [Power Scheduler: A Batch Size and Token Number Agnostic Learning Rate Scheduler](https://arxiv.org/abs/2408.13359) by Yikang Shen, Matthew Stallone, Mayank Mishra, Gaoyuan Zhang, Shawn Tan, Aditya Prasad, Adriana Meza Soria, David D. Cox and Rameswar Panda. + +Additionally this class GraniteMoeSharedModel adds shared experts for Moe. + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_path = "ibm-research/moe-7b-1b-active-shared-experts" +tokenizer = AutoTokenizer.from_pretrained(model_path) + +# drop device_map if running on CPU +model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto") +model.eval() + +# change input text as desired +prompt = "Write a code to find the maximum value in a list of numbers." + +# tokenize the text +input_tokens = tokenizer(prompt, return_tensors="pt") +# generate output tokens +output = model.generate(**input_tokens, max_new_tokens=100) +# decode output tokens into text +output = tokenizer.batch_decode(output) +# loop over the batch to print, in this example the batch size is 1 +for i in output: + print(i) +``` + +This HF implementation is contributed by [Mayank Mishra](https://huggingface.co/mayank-mishra), [Shawn Tan](https://huggingface.co/shawntan) and [Sukriti Sharma](https://huggingface.co/SukritiSharma). + + +## GraniteMoeSharedConfig + +[[autodoc]] GraniteMoeSharedConfig + +## GraniteMoeSharedModel + +[[autodoc]] GraniteMoeSharedModel + - forward + +## GraniteMoeSharedForCausalLM + +[[autodoc]] GraniteMoeSharedForCausalLM + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitevision.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitevision.md new file mode 100644 index 0000000000000000000000000000000000000000..e11c806ae6722b8d454c60936f09974a53a38826 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/granitevision.md @@ -0,0 +1,85 @@ + + +# Granite Vision + +## Overview + +The Granite Vision model is a variant of [LLaVA-NeXT](llava_next), leveraging a [Granite](granite) language model alongside a [SigLIP](SigLIP) visual encoder. It utilizes multiple concatenated vision hidden states as its image features, similar to [VipLlava](vipllava). It also uses a larger set of image grid pinpoints than the original LlaVa-NeXT models to support additional aspect ratios. + +Tips: +- This model is loaded into Transformers as an instance of LlaVA-Next. The usage and tips from [LLaVA-NeXT](llava_next) apply to this model as well. + +- You can apply the chat template on the tokenizer / processor in the same way as well. Example chat format: +```bash +"<|user|>\nWhat’s shown in this image?\n<|assistant|>\nThis image shows a red stop sign.<|end_of_text|><|user|>\nDescribe the image in more details.\n<|assistant|>\n" +``` + +Sample inference: +```python +from transformers import LlavaNextProcessor, LlavaNextForConditionalGeneration + +model_path = "ibm-granite/granite-vision-3.1-2b-preview" +processor = LlavaNextProcessor.from_pretrained(model_path) + +model = LlavaNextForConditionalGeneration.from_pretrained(model_path).to("cuda") + +# prepare image and text prompt, using the appropriate prompt template +url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true" + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "url": url}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt" +).to("cuda") + + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=100) + +print(processor.decode(output[0], skip_special_tokens=True)) +``` + +This model was contributed by [Alexander Brooks](https://huggingface.co/abrooks9944). + +## LlavaNextConfig + +[[autodoc]] LlavaNextConfig + +## LlavaNextImageProcessor + +[[autodoc]] LlavaNextImageProcessor + - preprocess + +## LlavaNextProcessor + +[[autodoc]] LlavaNextProcessor + +## LlavaNextForConditionalGeneration + +[[autodoc]] LlavaNextForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/graphormer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/graphormer.md new file mode 100644 index 0000000000000000000000000000000000000000..0d88134d4b7e608976e6f47dc1cb770afa16c8a8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/graphormer.md @@ -0,0 +1,59 @@ + + +# Graphormer + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The Graphormer model was proposed in [Do Transformers Really Perform Bad for Graph Representation?](https://arxiv.org/abs/2106.05234) by +Chengxuan Ying, Tianle Cai, Shengjie Luo, Shuxin Zheng, Guolin Ke, Di He, Yanming Shen and Tie-Yan Liu. It is a Graph Transformer model, modified to allow computations on graphs instead of text sequences by generating embeddings and features of interest during preprocessing and collation, then using a modified attention. + +The abstract from the paper is the following: + +*The Transformer architecture has become a dominant choice in many domains, such as natural language processing and computer vision. Yet, it has not achieved competitive performance on popular leaderboards of graph-level prediction compared to mainstream GNN variants. Therefore, it remains a mystery how Transformers could perform well for graph representation learning. In this paper, we solve this mystery by presenting Graphormer, which is built upon the standard Transformer architecture, and could attain excellent results on a broad range of graph representation learning tasks, especially on the recent OGB Large-Scale Challenge. Our key insight to utilizing Transformer in the graph is the necessity of effectively encoding the structural information of a graph into the model. To this end, we propose several simple yet effective structural encoding methods to help Graphormer better model graph-structured data. Besides, we mathematically characterize the expressive power of Graphormer and exhibit that with our ways of encoding the structural information of graphs, many popular GNN variants could be covered as the special cases of Graphormer.* + +This model was contributed by [clefourrier](https://huggingface.co/clefourrier). The original code can be found [here](https://github.com/microsoft/Graphormer). + +## Usage tips + +This model will not work well on large graphs (more than 100 nodes/edges), as it will make the memory explode. +You can reduce the batch size, increase your RAM, or decrease the `UNREACHABLE_NODE_DISTANCE` parameter in algos_graphormer.pyx, but it will be hard to go above 700 nodes/edges. + +This model does not use a tokenizer, but instead a special collator during training. + +## GraphormerConfig + +[[autodoc]] GraphormerConfig + +## GraphormerModel + +[[autodoc]] GraphormerModel + - forward + +## GraphormerForGraphClassification + +[[autodoc]] GraphormerForGraphClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/grounding-dino.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/grounding-dino.md new file mode 100644 index 0000000000000000000000000000000000000000..75f8a2fa32f77f869c26a23fcc938f609f7b6afc --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/grounding-dino.md @@ -0,0 +1,124 @@ + + +# Grounding DINO + +
+PyTorch +
+ +## Overview + +The Grounding DINO model was proposed in [Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection](https://arxiv.org/abs/2303.05499) by Shilong Liu, Zhaoyang Zeng, Tianhe Ren, Feng Li, Hao Zhang, Jie Yang, Chunyuan Li, Jianwei Yang, Hang Su, Jun Zhu, Lei Zhang. Grounding DINO extends a closed-set object detection model with a text encoder, enabling open-set object detection. The model achieves remarkable results, such as 52.5 AP on COCO zero-shot. + +The abstract from the paper is the following: + +*In this paper, we present an open-set object detector, called Grounding DINO, by marrying Transformer-based detector DINO with grounded pre-training, which can detect arbitrary objects with human inputs such as category names or referring expressions. The key solution of open-set object detection is introducing language to a closed-set detector for open-set concept generalization. To effectively fuse language and vision modalities, we conceptually divide a closed-set detector into three phases and propose a tight fusion solution, which includes a feature enhancer, a language-guided query selection, and a cross-modality decoder for cross-modality fusion. While previous works mainly evaluate open-set object detection on novel categories, we propose to also perform evaluations on referring expression comprehension for objects specified with attributes. Grounding DINO performs remarkably well on all three settings, including benchmarks on COCO, LVIS, ODinW, and RefCOCO/+/g. Grounding DINO achieves a 52.5 AP on the COCO detection zero-shot transfer benchmark, i.e., without any training data from COCO. It sets a new record on the ODinW zero-shot benchmark with a mean 26.1 AP.* + + + + Grounding DINO overview. Taken from the original paper. + +This model was contributed by [EduardoPacheco](https://huggingface.co/EduardoPacheco) and [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/IDEA-Research/GroundingDINO). + +## Usage tips + +- One can use [`GroundingDinoProcessor`] to prepare image-text pairs for the model. +- To separate classes in the text use a period e.g. "a cat. a dog." +- When using multiple classes (e.g. `"a cat. a dog."`), use `post_process_grounded_object_detection` from [`GroundingDinoProcessor`] to post process outputs. Since, the labels returned from `post_process_object_detection` represent the indices from the model dimension where prob > threshold. + +Here's how to use the model for zero-shot object detection: + +```python +>>> import requests + +>>> import torch +>>> from PIL import Image +>>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection + +>>> model_id = "IDEA-Research/grounding-dino-tiny" +>>> device = "cuda" + +>>> processor = AutoProcessor.from_pretrained(model_id) +>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device) + +>>> image_url = "http://images.cocodataset.org/val2017/000000039769.jpg" +>>> image = Image.open(requests.get(image_url, stream=True).raw) +>>> # Check for cats and remote controls +>>> text_labels = [["a cat", "a remote control"]] + +>>> inputs = processor(images=image, text=text_labels, return_tensors="pt").to(device) +>>> with torch.no_grad(): +... outputs = model(**inputs) + +>>> results = processor.post_process_grounded_object_detection( +... outputs, +... inputs.input_ids, +... box_threshold=0.4, +... text_threshold=0.3, +... target_sizes=[image.size[::-1]] +... ) + +# Retrieve the first image result +>>> result = results[0] +>>> for box, score, labels in zip(result["boxes"], result["scores"], result["labels"]): +... box = [round(x, 2) for x in box.tolist()] +... print(f"Detected {labels} with confidence {round(score.item(), 3)} at location {box}") +Detected a cat with confidence 0.468 at location [344.78, 22.9, 637.3, 373.62] +Detected a cat with confidence 0.426 at location [11.74, 51.55, 316.51, 473.22] +``` + +## Grounded SAM + +One can combine Grounding DINO with the [Segment Anything](sam) model for text-based mask generation as introduced in [Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks](https://arxiv.org/abs/2401.14159). You can refer to this [demo notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Grounding%20DINO/GroundingDINO_with_Segment_Anything.ipynb) 🌍 for details. + + + + Grounded SAM overview. Taken from the original repository. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Grounding DINO. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- Demo notebooks regarding inference with Grounding DINO as well as combining it with [SAM](sam) can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Grounding%20DINO). 🌎 + +## GroundingDinoImageProcessor + +[[autodoc]] GroundingDinoImageProcessor + - preprocess + - post_process_object_detection + +## GroundingDinoProcessor + +[[autodoc]] GroundingDinoProcessor + - post_process_grounded_object_detection + +## GroundingDinoConfig + +[[autodoc]] GroundingDinoConfig + +## GroundingDinoModel + +[[autodoc]] GroundingDinoModel + - forward + +## GroundingDinoForObjectDetection + +[[autodoc]] GroundingDinoForObjectDetection + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/groupvit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/groupvit.md new file mode 100644 index 0000000000000000000000000000000000000000..c77a51d8b1b78ea77190cb10892e298dcdd35d89 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/groupvit.md @@ -0,0 +1,101 @@ + + +# GroupViT + +
+PyTorch +TensorFlow +
+ +## Overview + +The GroupViT model was proposed in [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang. +Inspired by [CLIP](clip), GroupViT is a vision-language model that can perform zero-shot semantic segmentation on any given vocabulary categories. + +The abstract from the paper is the following: + +*Grouping and recognition are important components of visual scene understanding, e.g., for object detection and semantic segmentation. With end-to-end deep learning systems, grouping of image regions usually happens implicitly via top-down supervision from pixel-level recognition labels. Instead, in this paper, we propose to bring back the grouping mechanism into deep networks, which allows semantic segments to emerge automatically with only text supervision. We propose a hierarchical Grouping Vision Transformer (GroupViT), which goes beyond the regular grid structure representation and learns to group image regions into progressively larger arbitrary-shaped segments. We train GroupViT jointly with a text encoder on a large-scale image-text dataset via contrastive losses. With only text supervision and without any pixel-level annotations, GroupViT learns to group together semantic regions and successfully transfers to the task of semantic segmentation in a zero-shot manner, i.e., without any further fine-tuning. It achieves a zero-shot accuracy of 52.3% mIoU on the PASCAL VOC 2012 and 22.4% mIoU on PASCAL Context datasets, and performs competitively to state-of-the-art transfer-learning methods requiring greater levels of supervision.* + +This model was contributed by [xvjiarui](https://huggingface.co/xvjiarui). The TensorFlow version was contributed by [ariG23498](https://huggingface.co/ariG23498) with the help of [Yih-Dar SHIEH](https://huggingface.co/ydshieh), [Amy Roberts](https://huggingface.co/amyeroberts), and [Joao Gante](https://huggingface.co/joaogante). +The original code can be found [here](https://github.com/NVlabs/GroupViT). + +## Usage tips + +- You may specify `output_segmentation=True` in the forward of `GroupViTModel` to get the segmentation logits of input texts. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GroupViT. + +- The quickest way to get started with GroupViT is by checking the [example notebooks](https://github.com/xvjiarui/GroupViT/blob/main/demo/GroupViT_hf_inference_notebook.ipynb) (which showcase zero-shot segmentation inference). +- One can also check out the [HuggingFace Spaces demo](https://huggingface.co/spaces/xvjiarui/GroupViT) to play with GroupViT. + +## GroupViTConfig + +[[autodoc]] GroupViTConfig + - from_text_vision_configs + +## GroupViTTextConfig + +[[autodoc]] GroupViTTextConfig + +## GroupViTVisionConfig + +[[autodoc]] GroupViTVisionConfig + + + + +## GroupViTModel + +[[autodoc]] GroupViTModel + - forward + - get_text_features + - get_image_features + +## GroupViTTextModel + +[[autodoc]] GroupViTTextModel + - forward + +## GroupViTVisionModel + +[[autodoc]] GroupViTVisionModel + - forward + + + + +## TFGroupViTModel + +[[autodoc]] TFGroupViTModel + - call + - get_text_features + - get_image_features + +## TFGroupViTTextModel + +[[autodoc]] TFGroupViTTextModel + - call + +## TFGroupViTVisionModel + +[[autodoc]] TFGroupViTVisionModel + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/helium.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/helium.md new file mode 100644 index 0000000000000000000000000000000000000000..a9296eb110d5a0f476aad2adad215db99f0cc4df --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/helium.md @@ -0,0 +1,159 @@ + + +# Helium + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +Helium was proposed in [Announcing Helium-1 Preview](https://kyutai.org/2025/01/13/helium.html) by the Kyutai Team. + + +Helium-1 preview is a lightweight language model with 2B parameters, targeting edge and mobile devices. +It supports the following languages: English, French, German, Italian, Portuguese, Spanish. + +- **Developed by:** Kyutai +- **Model type:** Large Language Model +- **Language(s) (NLP):** English, French, German, Italian, Portuguese, Spanish +- **License:** CC-BY 4.0 + + + + +## Evaluation + + + +#### Testing Data + + + +The model was evaluated on MMLU, TriviaQA, NaturalQuestions, ARC Easy & Challenge, Open Book QA, Common Sense QA, +Physical Interaction QA, Social Interaction QA, HellaSwag, WinoGrande, Multilingual Knowledge QA, FLORES 200. + +#### Metrics + + + +We report accuracy on MMLU, ARC, OBQA, CSQA, PIQA, SIQA, HellaSwag, WinoGrande. +We report exact match on TriviaQA, NQ and MKQA. +We report BLEU on FLORES. + +### English Results + +| Benchmark | Helium-1 Preview | HF SmolLM2 (1.7B) | Gemma-2 (2.6B) | Llama-3.2 (3B) | Qwen2.5 (1.5B) | +|--------------|--------|--------|--------|--------|--------| +| | | | | | | +| MMLU | 51.2 | 50.4 | 53.1 | 56.6 | 61.0 | +| NQ | 17.3 | 15.1 | 17.7 | 22.0 | 13.1 | +| TQA | 47.9 | 45.4 | 49.9 | 53.6 | 35.9 | +| ARC E | 80.9 | 81.8 | 81.1 | 84.6 | 89.7 | +| ARC C | 62.7 | 64.7 | 66.0 | 69.0 | 77.2 | +| OBQA | 63.8 | 61.4 | 64.6 | 68.4 | 73.8 | +| CSQA | 65.6 | 59.0 | 64.4 | 65.4 | 72.4 | +| PIQA | 77.4 | 77.7 | 79.8 | 78.9 | 76.0 | +| SIQA | 64.4 | 57.5 | 61.9 | 63.8 | 68.7 | +| HS | 69.7 | 73.2 | 74.7 | 76.9 | 67.5 | +| WG | 66.5 | 65.6 | 71.2 | 72.0 | 64.8 | +| | | | | | | +| Average | 60.7 | 59.3 | 62.2 | 64.7 | 63.6 | + +#### Multilingual Results + +| Language | Benchmark | Helium-1 Preview | HF SmolLM2 (1.7B) | Gemma-2 (2.6B) | Llama-3.2 (3B) | Qwen2.5 (1.5B) | +|-----|--------------|--------|--------|--------|--------|--------| +| | | | | | | | +|German| MMLU | 45.6 | 35.3 | 45.0 | 47.5 | 49.5 | +|| ARC C | 56.7 | 38.4 | 54.7 | 58.3 | 60.2 | +|| HS | 53.5 | 33.9 | 53.4 | 53.7 | 42.8 | +|| MKQA | 16.1 | 7.1 | 18.9 | 20.2 | 10.4 | +| | | | | | | | +|Spanish| MMLU | 46.5 | 38.9 | 46.2 | 49.6 | 52.8 | +|| ARC C | 58.3 | 43.2 | 58.8 | 60.0 | 68.1 | +|| HS | 58.6 | 40.8 | 60.5 | 61.1 | 51.4 | +|| MKQA | 16.0 | 7.9 | 18.5 | 20.6 | 10.6 | + + +## Technical Specifications + +### Model Architecture and Objective + +| Hyperparameter | Value | +|--------------|--------| +| Layers | 24 | +| Heads | 20 | +| Model dimension | 2560 | +| MLP dimension | 7040 | +| Context size | 4096 | +| Theta RoPE | 100,000 | + +Tips: + +- This model was contributed by [Laurent Mazare](https://huggingface.co/lmz) + + +## Usage tips + +`Helium` can be found on the [Huggingface Hub](https://huggingface.co/models?other=helium) + +In the following, we demonstrate how to use `helium-1-preview` for the inference. + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer +>>> device = "cuda" # the device to load the model onto + +>>> model = AutoModelForCausalLM.from_pretrained("kyutai/helium-1-preview-2b", device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("kyutai/helium-1-preview-2b") + +>>> prompt = "Give me a short introduction to large language model." + +>>> model_inputs = tokenizer(prompt, return_tensors="pt").to(device) + +>>> generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512, do_sample=True) + +>>> generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)] + +>>> response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + +## HeliumConfig + +[[autodoc]] HeliumConfig + +## HeliumModel + +[[autodoc]] HeliumModel + - forward + +## HeliumForCausalLM + +[[autodoc]] HeliumForCausalLM + - forward + +## HeliumForSequenceClassification + +[[autodoc]] HeliumForSequenceClassification + - forward + +## HeliumForTokenClassification + +[[autodoc]] HeliumForTokenClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/herbert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/herbert.md new file mode 100644 index 0000000000000000000000000000000000000000..aa4f535ed274305456bebb7b9d24f0298b78c0a4 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/herbert.md @@ -0,0 +1,83 @@ + + +# HerBERT + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The HerBERT model was proposed in [KLEJ: Comprehensive Benchmark for Polish Language Understanding](https://www.aclweb.org/anthology/2020.acl-main.111.pdf) by Piotr Rybak, Robert Mroczkowski, Janusz Tracz, and +Ireneusz Gawlik. It is a BERT-based Language Model trained on Polish Corpora using only MLM objective with dynamic +masking of whole words. + +The abstract from the paper is the following: + +*In recent years, a series of Transformer-based models unlocked major improvements in general natural language +understanding (NLU) tasks. Such a fast pace of research would not be possible without general NLU benchmarks, which +allow for a fair comparison of the proposed methods. However, such benchmarks are available only for a handful of +languages. To alleviate this issue, we introduce a comprehensive multi-task benchmark for the Polish language +understanding, accompanied by an online leaderboard. It consists of a diverse set of tasks, adopted from existing +datasets for named entity recognition, question-answering, textual entailment, and others. We also introduce a new +sentiment analysis task for the e-commerce domain, named Allegro Reviews (AR). To ensure a common evaluation scheme and +promote models that generalize to different NLU tasks, the benchmark includes datasets from varying domains and +applications. Additionally, we release HerBERT, a Transformer-based model trained specifically for the Polish language, +which has the best average performance and obtains the best results for three out of nine tasks. Finally, we provide an +extensive evaluation, including several standard baselines and recently proposed, multilingual Transformer-based +models.* + +This model was contributed by [rmroczkowski](https://huggingface.co/rmroczkowski). The original code can be found +[here](https://github.com/allegro/HerBERT). + + +## Usage example + +```python +>>> from transformers import HerbertTokenizer, RobertaModel + +>>> tokenizer = HerbertTokenizer.from_pretrained("allegro/herbert-klej-cased-tokenizer-v1") +>>> model = RobertaModel.from_pretrained("allegro/herbert-klej-cased-v1") + +>>> encoded_input = tokenizer.encode("Kto ma lepszą sztukę, ma lepszy rząd – to jasne.", return_tensors="pt") +>>> outputs = model(encoded_input) + +>>> # HerBERT can also be loaded using AutoTokenizer and AutoModel: +>>> import torch +>>> from transformers import AutoModel, AutoTokenizer + +>>> tokenizer = AutoTokenizer.from_pretrained("allegro/herbert-klej-cased-tokenizer-v1") +>>> model = AutoModel.from_pretrained("allegro/herbert-klej-cased-v1") +``` + + + +Herbert implementation is the same as `BERT` except for the tokenization method. Refer to [BERT documentation](bert) +for API reference and examples. + + + +## HerbertTokenizer + +[[autodoc]] HerbertTokenizer + +## HerbertTokenizerFast + +[[autodoc]] HerbertTokenizerFast diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hiera.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hiera.md new file mode 100644 index 0000000000000000000000000000000000000000..a82eec950a513737dc0c3992d9e5703987761b35 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hiera.md @@ -0,0 +1,66 @@ + + +# Hiera + +
+PyTorch +
+ +## Overview + +Hiera was proposed in [Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles](https://arxiv.org/abs/2306.00989) by Chaitanya Ryali, Yuan-Ting Hu, Daniel Bolya, Chen Wei, Haoqi Fan, Po-Yao Huang, Vaibhav Aggarwal, Arkabandhu Chowdhury, Omid Poursaeed, Judy Hoffman, Jitendra Malik, Yanghao Li, Christoph Feichtenhofer + +The paper introduces "Hiera," a hierarchical Vision Transformer that simplifies the architecture of modern hierarchical vision transformers by removing unnecessary components without compromising on accuracy or efficiency. Unlike traditional transformers that add complex vision-specific components to improve supervised classification performance, Hiera demonstrates that such additions, often termed "bells-and-whistles," are not essential for high accuracy. By leveraging a strong visual pretext task (MAE) for pretraining, Hiera retains simplicity and achieves superior accuracy and speed both in inference and training across various image and video recognition tasks. The approach suggests that spatial biases required for vision tasks can be effectively learned through proper pretraining, eliminating the need for added architectural complexity. + +The abstract from the paper is the following: + +*Modern hierarchical vision transformers have added several vision-specific components in the pursuit of supervised classification performance. While these components lead to effective accuracies and attractive FLOP counts, the added complexity actually makes these transformers slower than their vanilla ViT counterparts. In this paper, we argue that this additional bulk is unnecessary. By pretraining with a strong visual pretext task (MAE), we can strip out all the bells-and-whistles from a state-of-the-art multi-stage vision transformer without losing accuracy. In the process, we create Hiera, an extremely simple hierarchical vision transformer that is more accurate than previous models while being significantly faster both at inference and during training. We evaluate Hiera on a variety of tasks for image and video recognition. Our code and models are available at https://github.com/facebookresearch/hiera.* + + + + Hiera architecture. Taken from the original paper. + +This model was a joint contribution by [EduardoPacheco](https://huggingface.co/EduardoPacheco) and [namangarg110](https://huggingface.co/namangarg110). The original code can be found [here] (https://github.com/facebookresearch/hiera). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Hiera. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- [`HieraForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +## HieraConfig + +[[autodoc]] HieraConfig + +## HieraModel + +[[autodoc]] HieraModel + - forward + +## HieraForPreTraining + +[[autodoc]] HieraForPreTraining + - forward + +## HieraForImageClassification + +[[autodoc]] HieraForImageClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hubert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hubert.md new file mode 100644 index 0000000000000000000000000000000000000000..432e127c78634fa55e617520b94ff1fa8d8e3aa2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/hubert.md @@ -0,0 +1,131 @@ + + +# Hubert + +
+PyTorch +TensorFlow +FlashAttention +SDPA +
+ +## Overview + +Hubert was proposed in [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan +Salakhutdinov, Abdelrahman Mohamed. + +The abstract from the paper is the following: + +*Self-supervised approaches for speech representation learning are challenged by three unique problems: (1) there are +multiple sound units in each input utterance, (2) there is no lexicon of input sound units during the pre-training +phase, and (3) sound units have variable lengths with no explicit segmentation. To deal with these three problems, we +propose the Hidden-Unit BERT (HuBERT) approach for self-supervised speech representation learning, which utilizes an +offline clustering step to provide aligned target labels for a BERT-like prediction loss. A key ingredient of our +approach is applying the prediction loss over the masked regions only, which forces the model to learn a combined +acoustic and language model over the continuous inputs. HuBERT relies primarily on the consistency of the unsupervised +clustering step rather than the intrinsic quality of the assigned cluster labels. Starting with a simple k-means +teacher of 100 clusters, and using two iterations of clustering, the HuBERT model either matches or improves upon the +state-of-the-art wav2vec 2.0 performance on the Librispeech (960h) and Libri-light (60,000h) benchmarks with 10min, 1h, +10h, 100h, and 960h fine-tuning subsets. Using a 1B parameter model, HuBERT shows up to 19% and 13% relative WER +reduction on the more challenging dev-other and test-other evaluation subsets.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). + +# Usage tips + +- Hubert is a speech model that accepts a float array corresponding to the raw waveform of the speech signal. +- Hubert model was fine-tuned using connectionist temporal classification (CTC) so the model output has to be decoded + using [`Wav2Vec2CTCTokenizer`]. + + +## Using Flash Attention 2 + +Flash Attention 2 is an faster, optimized version of the model. + +### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + +### Usage + +Below is an expected speedup diagram comparing the pure inference time between the native implementation in transformers of `facebook/hubert-large-ls960-ft`, the flash-attention-2 and the sdpa (scale-dot-product-attention) version. We show the average speedup obtained on the `librispeech_asr` `clean` validation split: + +```python +>>> from transformers import Wav2Vec2Model + +model = Wav2Vec2Model.from_pretrained("facebook/hubert-large-ls960-ft", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device) +... +``` + +### Expected speedups + +Below is an expected speedup diagram comparing the pure inference time between the native implementation in transformers of the `facebook/hubert-large-ls960-ft` model and the flash-attention-2 and sdpa (scale-dot-product-attention) versions. . We show the average speedup obtained on the `librispeech_asr` `clean` validation split: + + +
+ +
+ + +## Resources + +- [Audio classification task guide](../tasks/audio_classification) +- [Automatic speech recognition task guide](../tasks/asr) + +## HubertConfig + +[[autodoc]] HubertConfig + + + + +## HubertModel + +[[autodoc]] HubertModel + - forward + +## HubertForCTC + +[[autodoc]] HubertForCTC + - forward + +## HubertForSequenceClassification + +[[autodoc]] HubertForSequenceClassification + - forward + + + + +## TFHubertModel + +[[autodoc]] TFHubertModel + - call + +## TFHubertForCTC + +[[autodoc]] TFHubertForCTC + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ibert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ibert.md new file mode 100644 index 0000000000000000000000000000000000000000..8c43eeddaf5567067c7c7b0b2337a1248b058f59 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ibert.md @@ -0,0 +1,87 @@ + + +# I-BERT + +
+PyTorch +
+ +## Overview + +The I-BERT model was proposed in [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by +Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney and Kurt Keutzer. It's a quantized version of RoBERTa running +inference up to four times faster. + +The abstract from the paper is the following: + +*Transformer based models, like BERT and RoBERTa, have achieved state-of-the-art results in many Natural Language +Processing tasks. However, their memory footprint, inference latency, and power consumption are prohibitive for +efficient inference at the edge, and even at the data center. While quantization can be a viable solution for this, +previous work on quantizing Transformer based models use floating-point arithmetic during inference, which cannot +efficiently utilize integer-only logical units such as the recent Turing Tensor Cores, or traditional integer-only ARM +processors. In this work, we propose I-BERT, a novel quantization scheme for Transformer based models that quantizes +the entire inference with integer-only arithmetic. Based on lightweight integer-only approximation methods for +nonlinear operations, e.g., GELU, Softmax, and Layer Normalization, I-BERT performs an end-to-end integer-only BERT +inference without any floating point calculation. We evaluate our approach on GLUE downstream tasks using +RoBERTa-Base/Large. We show that for both cases, I-BERT achieves similar (and slightly higher) accuracy as compared to +the full-precision baseline. Furthermore, our preliminary implementation of I-BERT shows a speedup of 2.4 - 4.0x for +INT8 inference on a T4 GPU system as compared to FP32 inference. The framework has been developed in PyTorch and has +been open-sourced.* + +This model was contributed by [kssteven](https://huggingface.co/kssteven). The original code can be found [here](https://github.com/kssteven418/I-BERT). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/masked_language_modeling) + +## IBertConfig + +[[autodoc]] IBertConfig + +## IBertModel + +[[autodoc]] IBertModel + - forward + +## IBertForMaskedLM + +[[autodoc]] IBertForMaskedLM + - forward + +## IBertForSequenceClassification + +[[autodoc]] IBertForSequenceClassification + - forward + +## IBertForMultipleChoice + +[[autodoc]] IBertForMultipleChoice + - forward + +## IBertForTokenClassification + +[[autodoc]] IBertForTokenClassification + - forward + +## IBertForQuestionAnswering + +[[autodoc]] IBertForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics.md new file mode 100644 index 0000000000000000000000000000000000000000..2b8e471213d71e1f171da074c68f27bb73ebfcb8 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics.md @@ -0,0 +1,79 @@ + + +# IDEFICS + +
+PyTorch +TensorFlow +SDPA +
+ +## Overview + +The IDEFICS model was proposed in [OBELICS: An Open Web-Scale Filtered Dataset of Interleaved Image-Text Documents +](https://huggingface.co/papers/2306.16527 +) by Hugo Laurençon, Lucile Saulnier, Léo Tronchon, Stas Bekman, Amanpreet Singh, Anton Lozhkov, Thomas Wang, Siddharth Karamcheti, Alexander M. Rush, Douwe Kiela, Matthieu Cord, Victor Sanh + +The abstract from the paper is the following: + +*Large multimodal models trained on natural documents, which interleave images and text, outperform models trained on image-text pairs on various multimodal benchmarks that require reasoning over one or multiple images to generate a text. However, the datasets used to train these models have not been released, and the collection process has not been fully specified. We introduce the OBELICS dataset, an open web-scale filtered dataset of interleaved image-text documents comprising 141 million web pages extracted from Common Crawl, 353 million associated images, and 115 billion text tokens. We describe the dataset creation process, present comprehensive filtering rules, and provide an analysis of the dataset's content. To show the viability of OBELISC, we train an 80 billion parameters vision and language model on the dataset and obtain competitive performance on various multimodal benchmarks. We release the code to reproduce the dataset along with the dataset itself.* + +This model was contributed by [HuggingFaceM4](https://huggingface.co/HuggingFaceM4). The original code can be found [here](). (TODO: don't have a public link yet). + + + + +IDEFICS modeling code in Transformers is for finetuning and inferencing the pre-trained IDEFICS models. + +To train a new IDEFICS model from scratch use the m4 codebase (a link will be provided once it's made public) + + + + +## IdeficsConfig + +[[autodoc]] IdeficsConfig + +## IdeficsModel + +[[autodoc]] IdeficsModel + - forward + +## IdeficsForVisionText2Text + +[[autodoc]] IdeficsForVisionText2Text + - forward + +## TFIdeficsModel + +[[autodoc]] TFIdeficsModel + - call + +## TFIdeficsForVisionText2Text + +[[autodoc]] TFIdeficsForVisionText2Text + - call + +## IdeficsImageProcessor + +[[autodoc]] IdeficsImageProcessor + - preprocess + +## IdeficsProcessor + +[[autodoc]] IdeficsProcessor + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics2.md new file mode 100644 index 0000000000000000000000000000000000000000..8de2c92d560944491ac8ef0d96d2b64c20c3ac77 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics2.md @@ -0,0 +1,224 @@ + + +# Idefics2 + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Idefics2 model was proposed in [What matters when building vision-language models?](https://arxiv.org/abs/2405.02246) by Léo Tronchon, Hugo Laurencon, Victor Sanh. The accompanying blog post can be found [here](https://huggingface.co/blog/idefics2). + +Idefics2 is an open multimodal model that accepts arbitrary sequences of image and text inputs and produces text +outputs. The model can answer questions about images, describe visual content, create stories grounded on multiple +images, or simply behave as a pure language model without visual inputs. It improves upon IDEFICS-1, notably on +document understanding, OCR, or visual reasoning. Idefics2 is lightweight (8 billion parameters) and treats +images in their native aspect ratio and resolution, which allows for varying inference efficiency. + +The abstract from the paper is the following: + +*The growing interest in vision-language models (VLMs) has been driven by improvements in large language models and vision transformers. Despite the abundance of literature on this subject, we observe that critical decisions regarding the design of VLMs are often not justified. We argue that these unsupported decisions impede progress in the field by making it difficult to identify which choices improve model performance. To address this issue, we conduct extensive experiments around pre-trained models, architecture choice, data, and training methods. Our consolidation of findings includes the development of Idefics2, an efficient foundational VLM of 8 billion parameters. Idefics2 achieves state-of-the-art performance within its size category across various multimodal benchmarks, and is often on par with models four times its size. We release the model (base, instructed, and chat) along with the datasets created for its training.* + + + + Idefics2 architecture. Taken from the original paper. + +This model was contributed by [amyeroberts](https://huggingface.co/amyeroberts). +The original code can be found [here](https://huggingface.co/HuggingFaceM4/idefics2). + +## Usage tips + +- Each sample can contain multiple images, and the number of images can vary between samples. The processor will pad the inputs to the maximum number of images in a batch for input to the model. +- The processor has a `do_image_splitting` option. If `True`, each input image will be split into 4 sub-images, and concatenated with the original to form 5 images. This is useful for increasing model performance. Make sure `processor.image_processor.do_image_splitting` is set to `False` if the model was not trained with this option. +- `text` passed to the processor should have the `` tokens where the images should be inserted. And `` at the end of each utterance if the text is a chat message. +- The processor has its own `apply_chat_template` method to convert chat messages to text that can then be passed as `text` to the processor. + +Example of how to use the processor on chat messages: + +```python +import requests +from PIL import Image +from transformers import Idefics2Processor, Idefics2ForConditionalGeneration +import torch + +device = "cuda" if torch.cuda.is_available() else "cpu" + +url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg" +url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg" + +image_1 = Image.open(requests.get(url_1, stream=True).raw) +image_2 = Image.open(requests.get(url_2, stream=True).raw) +images = [image_1, image_2] + +messages = [{ + "role": "user", + "content": [ + {"type": "text", "text": "What’s the difference between these two images?"}, + {"type": "image"}, + {"type": "image"}, + ], +}] + +processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b") +model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b") +model.to(device) + +# at inference time, one needs to pass `add_generation_prompt=True` in order to make sure the model completes the prompt +text = processor.apply_chat_template(messages, add_generation_prompt=True) +print(text) +# 'User: What’s the difference between these two images?\nAssistant:' + +inputs = processor(images=images, text=text, return_tensors="pt").to(device) + +generated_text = model.generate(**inputs, max_new_tokens=500) +generated_text = processor.batch_decode(generated_text, skip_special_tokens=True)[0] +print("Generated text:", generated_text) +``` + +- During training, it's important to determine which tokens the model should not learn. For Idefics2, this typically comes down to the image and padding tokens. This means that one can create the labels as follows: + +```python +import requests +from PIL import Image +from transformers import Idefics2Processor, Idefics2ForConditionalGeneration +import torch + +url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg" +url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg" + +image_1 = Image.open(requests.get(url_1, stream=True).raw) +image_2 = Image.open(requests.get(url_2, stream=True).raw) +images = [image_1, image_2] + +messages = [{ + "role": "user", + "content": [ + {"type": "text", "text": "What’s the difference between these two images?"}, + {"type": "image"}, + {"type": "image"}, + ], +}, +{ + "role": "assistant", + "content": [ + {"type": "text", "text": "The difference is that one image is about dogs and the other one about cats."}, + ], +}] + +device = "cuda" if torch.cuda.is_available() else "cpu" + +processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b") +model = Idefics2ForConditionalGeneration.from_pretrained("HuggingFaceM4/idefics2-8b") +model.to(device) + +text = processor.apply_chat_template(messages, add_generation_prompt=False) +inputs = processor(images=images, text=text, return_tensors="pt").to(device) + +labels = inputs.input_ids.clone() +labels[labels == processor.tokenizer.pad_token_id] = -100 +labels[labels == model.config.image_token_id] = -100 + +inputs["labels"] = labels + +outputs = model(**inputs) +loss = outputs.loss +loss.backward() +``` + +Do note that when training Idefics2 on multi-turn conversations between a user and an assistant, one typically also sets all the tokens corresponding to the user messages to -100. + +## Model optimizations: Flash Attention + +The code snippets above showcase inference without any optimization tricks. However, one can drastically speed up the model by leveraging [Flash Attention](../perf_train_gpu_one#flash-attention-2), which is a faster implementation of the attention mechanism used inside the model. + +First, make sure to install the latest version of Flash Attention 2 to include the sliding window attention feature. + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of the [flash attention repository](https://github.com/Dao-AILab/flash-attention). Make also sure to load your model in half-precision (e.g. `torch.float16`) + +To load and run a model using Flash Attention-2, simply change the code snippet above with the following change: + +```diff +model = Idefics2ForConditionalGeneration.from_pretrained( + "HuggingFaceM4/idefics2-8b", ++ torch_dtype=torch.float16, ++ attn_implementation="flash_attention_2", +).to(device) +``` + +## Shrinking down Idefics2 using quantization + +As the Idefics2 model has 8 billion parameters, that would require about 16GB of GPU RAM in half precision (float16), since each parameter is stored in 2 bytes. However, one can shrink down the size of the model using [quantization](../quantization.md). If the model is quantized to 4 bits (or half a byte per parameter), that requires only about 3.5GB of RAM. + +Quantizing a model is as simple as passing a `quantization_config` to the model. One can change the code snippet above with the changes below. We'll leverage the BitsAndyBytes quantization (but refer to [this page](../quantization.md) for other quantization methods): + +```diff ++ from transformers import BitsAndBytesConfig + ++ quantization_config = BitsAndBytesConfig( ++ load_in_4bit=True, ++ bnb_4bit_quant_type="nf4", ++ bnb_4bit_use_double_quant=True, ++ bnb_4bit_compute_dtype=torch.float16 ++ ) +model = Idefics2ForConditionalGeneration.from_pretrained( + "HuggingFaceM4/idefics2-8b", ++ torch_dtype=torch.float16, ++ quantization_config=quantization_config, +).to(device) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Idefics2. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- A notebook on how to fine-tune Idefics2 on a custom dataset using the [Trainer](../main_classes/trainer.md) can be found [here](https://colab.research.google.com/drive/1NtcTgRbSBKN7pYD3Vdx1j9m8pt3fhFDB?usp=sharing). It supports both full fine-tuning as well as (quantized) LoRa. +- A script regarding how to fine-tune Idefics2 using the TRL library can be found [here](https://gist.github.com/edbeeching/228652fc6c2b29a1641be5a5778223cb). +- Demo notebook regarding fine-tuning Idefics2 for JSON extraction use cases can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Idefics2). 🌎 + +## Idefics2Config + +[[autodoc]] Idefics2Config + + +## Idefics2Model + +[[autodoc]] Idefics2Model + - forward + + +## Idefics2ForConditionalGeneration + +[[autodoc]] Idefics2ForConditionalGeneration + - forward + + +## Idefics2ImageProcessor +[[autodoc]] Idefics2ImageProcessor + - preprocess + + +## Idefics2Processor +[[autodoc]] Idefics2Processor + - __call__ \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics3.md new file mode 100644 index 0000000000000000000000000000000000000000..deab4423f80c08137316e73470474f20a0477bac --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/idefics3.md @@ -0,0 +1,86 @@ + + +# Idefics3 + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Idefics3 model was proposed in [Building and better understanding vision-language models: insights and future directions](https://huggingface.co/papers/2408.12637) by Hugo Laurençon, Andrés Marafioti, Victor Sanh, and Léo Tronchon. + +Idefics3 is an adaptation of the Idefics2 model with three main differences: + +- It uses Llama3 for the text model. +- It uses an updated processing logic for the images. +- It removes the perceiver. + +The abstract from the paper is the following: + +*The field of vision-language models (VLMs), which take images and texts as inputs and output texts, is rapidly evolving and has yet to reach consensus on several key aspects of the development pipeline, including data, architecture, and training methods. This paper can be seen as a tutorial for building a VLM. We begin by providing a comprehensive overview of the current state-of-the-art approaches, highlighting the strengths and weaknesses of each, addressing the major challenges in the field, and suggesting promising research directions for underexplored areas. We then walk through the practical steps to build Idefics3-8B, a powerful VLM that significantly outperforms its predecessor Idefics2-8B, while being trained efficiently, exclusively on open datasets, and using a straightforward pipeline. These steps include the creation of Docmatix, a dataset for improving document understanding capabilities, which is 240 times larger than previously available datasets. We release the model along with the datasets created for its training.* + +## Usage tips + +Input images are processed either by upsampling (if resizing is enabled) or at their original resolution. The resizing behavior depends on two parameters: do_resize and size. + +If `do_resize` is set to `True`, the model resizes images so that the longest edge is 4*364 pixels by default. +The default resizing behavior can be customized by passing a dictionary to the `size` parameter. For example, `{"longest_edge": 4 * 364}` is the default, but you can change it to a different value if needed. + +Here’s how to control resizing and set a custom size: +```python +image_processor = Idefics3ImageProcessor(do_resize=True, size={"longest_edge": 2 * 364}, max_image_size=364) +``` + +Additionally, the `max_image_size` parameter, which controls the size of each square patch the image is decomposed into, is set to 364 by default but can be adjusted as needed. After resizing (if applicable), the image processor decomposes the images into square patches based on the `max_image_size` parameter. + +This model was contributed by [amyeroberts](https://huggingface.co/amyeroberts) and [andimarafioti](https://huggingface.co/andito). + + +## Idefics3Config + +[[autodoc]] Idefics3Config + +## Idefics3VisionConfig + +[[autodoc]] Idefics3VisionConfig + +## Idefics3VisionTransformer + +[[autodoc]] Idefics3VisionTransformer + +## Idefics3Model + +[[autodoc]] Idefics3Model + - forward + +## Idefics3ForConditionalGeneration + +[[autodoc]] Idefics3ForConditionalGeneration + - forward + + +## Idefics3ImageProcessor +[[autodoc]] Idefics3ImageProcessor + - preprocess + + +## Idefics3Processor +[[autodoc]] Idefics3Processor + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ijepa.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ijepa.md new file mode 100644 index 0000000000000000000000000000000000000000..a92fdc83e8ac69f219b50c2c504980649bcc03c6 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/ijepa.md @@ -0,0 +1,97 @@ + + +# I-JEPA + +
+PyTorch +SDPA +
+ +## Overview + +The I-JEPA model was proposed in [Image-based Joint-Embedding Predictive Architecture](https://arxiv.org/abs/2301.08243) by Mahmoud Assran, Quentin Duval, Ishan Misra, Piotr Bojanowski, Pascal Vincent, Michael Rabbat, Yann LeCun, Nicolas Ballas. +I-JEPA is a self-supervised learning method that predicts the representations of one part of an image based on other parts of the same image. This approach focuses on learning semantic features without relying on pre-defined invariances from hand-crafted data transformations, which can bias specific tasks, or on filling in pixel-level details, which often leads to less meaningful representations. + +The abstract from the paper is the following: + +This paper demonstrates an approach for learning highly semantic image representations without relying on hand-crafted data-augmentations. We introduce the Image- based Joint-Embedding Predictive Architecture (I-JEPA), a non-generative approach for self-supervised learning from images. The idea behind I-JEPA is simple: from a single context block, predict the representations of various target blocks in the same image. A core design choice to guide I-JEPA towards producing semantic representations is the masking strategy; specifically, it is crucial to (a) sample tar- get blocks with sufficiently large scale (semantic), and to (b) use a sufficiently informative (spatially distributed) context block. Empirically, when combined with Vision Transform- ers, we find I-JEPA to be highly scalable. For instance, we train a ViT-Huge/14 on ImageNet using 16 A100 GPUs in under 72 hours to achieve strong downstream performance across a wide range of tasks, from linear classification to object counting and depth prediction. + + + + I-JEPA architecture. Taken from the original paper. + +This model was contributed by [jmtzt](https://huggingface.co/jmtzt). +The original code can be found [here](https://github.com/facebookresearch/ijepa). + +## How to use + +Here is how to use this model for image feature extraction: + +```python +import requests +import torch +from PIL import Image +from torch.nn.functional import cosine_similarity + +from transformers import AutoModel, AutoProcessor + +url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg" +url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg" +image_1 = Image.open(requests.get(url_1, stream=True).raw) +image_2 = Image.open(requests.get(url_2, stream=True).raw) + +model_id = "facebook/ijepa_vith14_1k" +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModel.from_pretrained(model_id) + +@torch.no_grad() +def infer(image): + inputs = processor(image, return_tensors="pt") + outputs = model(**inputs) + return outputs.last_hidden_state.mean(dim=1) + + +embed_1 = infer(image_1) +embed_2 = infer(image_2) + +similarity = cosine_similarity(embed_1, embed_2) +print(similarity) +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with I-JEPA. + + + +- [`IJepaForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +## IJepaConfig + +[[autodoc]] IJepaConfig + +## IJepaModel + +[[autodoc]] IJepaModel + - forward + +## IJepaForImageClassification + +[[autodoc]] IJepaForImageClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/imagegpt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/imagegpt.md new file mode 100644 index 0000000000000000000000000000000000000000..7fbec62d30bb2fd90be3fd33a36a1312fae33f0e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/imagegpt.md @@ -0,0 +1,119 @@ + + +# ImageGPT + +
+PyTorch +
+ +## Overview + +The ImageGPT model was proposed in [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt) by Mark +Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever. ImageGPT (iGPT) is a GPT-2-like +model trained to predict the next pixel value, allowing for both unconditional and conditional image generation. + +The abstract from the paper is the following: + +*Inspired by progress in unsupervised representation learning for natural language, we examine whether similar models +can learn useful representations for images. We train a sequence Transformer to auto-regressively predict pixels, +without incorporating knowledge of the 2D input structure. Despite training on low-resolution ImageNet without labels, +we find that a GPT-2 scale model learns strong image representations as measured by linear probing, fine-tuning, and +low-data classification. On CIFAR-10, we achieve 96.3% accuracy with a linear probe, outperforming a supervised Wide +ResNet, and 99.0% accuracy with full fine-tuning, matching the top supervised pre-trained models. We are also +competitive with self-supervised benchmarks on ImageNet when substituting pixels for a VQVAE encoding, achieving 69.0% +top-1 accuracy on a linear probe of our features.* + + + + Summary of the approach. Taken from the [original paper](https://cdn.openai.com/papers/Generative_Pretraining_from_Pixels_V2.pdf). + +This model was contributed by [nielsr](https://huggingface.co/nielsr), based on [this issue](https://github.com/openai/image-gpt/issues/7). The original code can be found +[here](https://github.com/openai/image-gpt). + +## Usage tips + +- ImageGPT is almost exactly the same as [GPT-2](gpt2), with the exception that a different activation + function is used (namely "quick gelu"), and the layer normalization layers don't mean center the inputs. ImageGPT + also doesn't have tied input- and output embeddings. +- As the time- and memory requirements of the attention mechanism of Transformers scales quadratically in the sequence + length, the authors pre-trained ImageGPT on smaller input resolutions, such as 32x32 and 64x64. However, feeding a + sequence of 32x32x3=3072 tokens from 0..255 into a Transformer is still prohibitively large. Therefore, the authors + applied k-means clustering to the (R,G,B) pixel values with k=512. This way, we only have a 32*32 = 1024-long + sequence, but now of integers in the range 0..511. So we are shrinking the sequence length at the cost of a bigger + embedding matrix. In other words, the vocabulary size of ImageGPT is 512, + 1 for a special "start of sentence" (SOS) + token, used at the beginning of every sequence. One can use [`ImageGPTImageProcessor`] to prepare + images for the model. +- Despite being pre-trained entirely unsupervised (i.e. without the use of any labels), ImageGPT produces fairly + performant image features useful for downstream tasks, such as image classification. The authors showed that the + features in the middle of the network are the most performant, and can be used as-is to train a linear model (such as + a sklearn logistic regression model for example). This is also referred to as "linear probing". Features can be + easily obtained by first forwarding the image through the model, then specifying `output_hidden_states=True`, and + then average-pool the hidden states at whatever layer you like. +- Alternatively, one can further fine-tune the entire model on a downstream dataset, similar to BERT. For this, you can + use [`ImageGPTForImageClassification`]. +- ImageGPT comes in different sizes: there's ImageGPT-small, ImageGPT-medium and ImageGPT-large. The authors did also + train an XL variant, which they didn't release. The differences in size are summarized in the following table: + +| **Model variant** | **Depths** | **Hidden sizes** | **Decoder hidden size** | **Params (M)** | **ImageNet-1k Top 1** | +|---|---|---|---|---|---| +| MiT-b0 | [2, 2, 2, 2] | [32, 64, 160, 256] | 256 | 3.7 | 70.5 | +| MiT-b1 | [2, 2, 2, 2] | [64, 128, 320, 512] | 256 | 14.0 | 78.7 | +| MiT-b2 | [3, 4, 6, 3] | [64, 128, 320, 512] | 768 | 25.4 | 81.6 | +| MiT-b3 | [3, 4, 18, 3] | [64, 128, 320, 512] | 768 | 45.2 | 83.1 | +| MiT-b4 | [3, 8, 27, 3] | [64, 128, 320, 512] | 768 | 62.6 | 83.6 | +| MiT-b5 | [3, 6, 40, 3] | [64, 128, 320, 512] | 768 | 82.0 | 83.8 | + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ImageGPT. + + + +- Demo notebooks for ImageGPT can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/ImageGPT). +- [`ImageGPTForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## ImageGPTConfig + +[[autodoc]] ImageGPTConfig + +## ImageGPTFeatureExtractor + +[[autodoc]] ImageGPTFeatureExtractor + - __call__ + +## ImageGPTImageProcessor + +[[autodoc]] ImageGPTImageProcessor + - preprocess + +## ImageGPTModel + +[[autodoc]] ImageGPTModel + - forward + +## ImageGPTForCausalImageModeling + +[[autodoc]] ImageGPTForCausalImageModeling + - forward + +## ImageGPTForImageClassification + +[[autodoc]] ImageGPTForImageClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/informer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/informer.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfc397db7770bdcd44af12edeec57e34bd68ddb --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/informer.md @@ -0,0 +1,54 @@ + + +# Informer + +
+PyTorch +
+ +## Overview + +The Informer model was proposed in [Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting](https://arxiv.org/abs/2012.07436) by Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, and Wancai Zhang. + +This method introduces a Probabilistic Attention mechanism to select the "active" queries rather than the "lazy" queries and provides a sparse Transformer thus mitigating the quadratic compute and memory requirements of vanilla attention. + +The abstract from the paper is the following: + +*Many real-world applications require the prediction of long sequence time-series, such as electricity consumption planning. Long sequence time-series forecasting (LSTF) demands a high prediction capacity of the model, which is the ability to capture precise long-range dependency coupling between output and input efficiently. Recent studies have shown the potential of Transformer to increase the prediction capacity. However, there are several severe issues with Transformer that prevent it from being directly applicable to LSTF, including quadratic time complexity, high memory usage, and inherent limitation of the encoder-decoder architecture. To address these issues, we design an efficient transformer-based model for LSTF, named Informer, with three distinctive characteristics: (i) a ProbSparse self-attention mechanism, which achieves O(L logL) in time complexity and memory usage, and has comparable performance on sequences' dependency alignment. (ii) the self-attention distilling highlights dominating attention by halving cascading layer input, and efficiently handles extreme long input sequences. (iii) the generative style decoder, while conceptually simple, predicts the long time-series sequences at one forward operation rather than a step-by-step way, which drastically improves the inference speed of long-sequence predictions. Extensive experiments on four large-scale datasets demonstrate that Informer significantly outperforms existing methods and provides a new solution to the LSTF problem.* + +This model was contributed by [elisim](https://huggingface.co/elisim) and [kashif](https://huggingface.co/kashif). +The original code can be found [here](https://github.com/zhouhaoyi/Informer2020). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- Check out the Informer blog-post in HuggingFace blog: [Multivariate Probabilistic Time Series Forecasting with Informer](https://huggingface.co/blog/informer) + +## InformerConfig + +[[autodoc]] InformerConfig + +## InformerModel + +[[autodoc]] InformerModel + - forward + +## InformerForPrediction + +[[autodoc]] InformerForPrediction + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblip.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblip.md new file mode 100644 index 0000000000000000000000000000000000000000..4f2feb015f1f8185b479ef6e6177f6e93f847f9e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblip.md @@ -0,0 +1,76 @@ + + +# InstructBLIP + +
+PyTorch +
+ +## Overview + +The InstructBLIP model was proposed in [InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning](https://arxiv.org/abs/2305.06500) by Wenliang Dai, Junnan Li, Dongxu Li, Anthony Meng Huat Tiong, Junqi Zhao, Weisheng Wang, Boyang Li, Pascale Fung, Steven Hoi. +InstructBLIP leverages the [BLIP-2](blip2) architecture for visual instruction tuning. + +The abstract from the paper is the following: + +*General-purpose language models that can solve various language-domain tasks have emerged driven by the pre-training and instruction-tuning pipeline. However, building general-purpose vision-language models is challenging due to the increased task discrepancy introduced by the additional visual input. Although vision-language pre-training has been widely studied, vision-language instruction tuning remains relatively less explored. In this paper, we conduct a systematic and comprehensive study on vision-language instruction tuning based on the pre-trained BLIP-2 models. We gather a wide variety of 26 publicly available datasets, transform them into instruction tuning format and categorize them into two clusters for held-in instruction tuning and held-out zero-shot evaluation. Additionally, we introduce instruction-aware visual feature extraction, a crucial method that enables the model to extract informative features tailored to the given instruction. The resulting InstructBLIP models achieve state-of-the-art zero-shot performance across all 13 held-out datasets, substantially outperforming BLIP-2 and the larger Flamingo. Our models also lead to state-of-the-art performance when finetuned on individual downstream tasks (e.g., 90.7% accuracy on ScienceQA IMG). Furthermore, we qualitatively demonstrate the advantages of InstructBLIP over concurrent multimodal models.* + + + + InstructBLIP architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/salesforce/LAVIS/tree/main/projects/instructblip). + +## Usage tips + +InstructBLIP uses the same architecture as [BLIP-2](blip2) with a tiny but important difference: it also feeds the text prompt (instruction) to the Q-Former. + +> [!NOTE] +> BLIP models after release v4.46 will raise warnings about adding `processor.num_query_tokens = {{num_query_tokens}}` and expand model embeddings layer to add special `` token. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. Adding these attributes means that BLIP will add the number of query tokens required per image and expand the text with as many `` placeholders as there will be query tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there wil be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.num_query_tokens` and model embeddings expansion can be done by following [this link](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042). + +## InstructBlipConfig + +[[autodoc]] InstructBlipConfig + - from_vision_qformer_text_configs + +## InstructBlipVisionConfig + +[[autodoc]] InstructBlipVisionConfig + +## InstructBlipQFormerConfig + +[[autodoc]] InstructBlipQFormerConfig + +## InstructBlipProcessor + +[[autodoc]] InstructBlipProcessor + + +## InstructBlipVisionModel + +[[autodoc]] InstructBlipVisionModel + - forward + +## InstructBlipQFormerModel + +[[autodoc]] InstructBlipQFormerModel + - forward + +## InstructBlipForConditionalGeneration + +[[autodoc]] InstructBlipForConditionalGeneration + - forward + - generate \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblipvideo.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblipvideo.md new file mode 100644 index 0000000000000000000000000000000000000000..c26562a8530862d5df2ab0674a467dba4866be5b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/instructblipvideo.md @@ -0,0 +1,80 @@ + + +# InstructBlipVideo + +
+PyTorch +
+ +## Overview + +The InstructBLIPVideo is an extension of the models proposed in [InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning](https://arxiv.org/abs/2305.06500) by Wenliang Dai, Junnan Li, Dongxu Li, Anthony Meng Huat Tiong, Junqi Zhao, Weisheng Wang, Boyang Li, Pascale Fung, Steven Hoi. +InstructBLIPVideo uses the same architecture as [InstructBLIP](instructblip) and works with the same checkpoints as [InstructBLIP](instructblip). The only difference is the ability to process videos. + +The abstract from the paper is the following: + +*General-purpose language models that can solve various language-domain tasks have emerged driven by the pre-training and instruction-tuning pipeline. However, building general-purpose vision-language models is challenging due to the increased task discrepancy introduced by the additional visual input. Although vision-language pre-training has been widely studied, vision-language instruction tuning remains relatively less explored. In this paper, we conduct a systematic and comprehensive study on vision-language instruction tuning based on the pre-trained BLIP-2 models. We gather a wide variety of 26 publicly available datasets, transform them into instruction tuning format and categorize them into two clusters for held-in instruction tuning and held-out zero-shot evaluation. Additionally, we introduce instruction-aware visual feature extraction, a crucial method that enables the model to extract informative features tailored to the given instruction. The resulting InstructBLIP models achieve state-of-the-art zero-shot performance across all 13 held-out datasets, substantially outperforming BLIP-2 and the larger Flamingo. Our models also lead to state-of-the-art performance when finetuned on individual downstream tasks (e.g., 90.7% accuracy on ScienceQA IMG). Furthermore, we qualitatively demonstrate the advantages of InstructBLIP over concurrent multimodal models.* + + + + InstructBLIPVideo architecture. Taken from the original paper. + +This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/salesforce/LAVIS/tree/main/projects/instructblip). + +## Usage tips + +- The model was trained by sampling 4 frames per video, so it's recommended to sample 4 frames + +> [!NOTE] +> BLIP models after release v4.46 will raise warnings about adding `processor.num_query_tokens = {{num_query_tokens}}` and expand model embeddings layer to add special `` token. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. Adding these attributes means that BLIP will add the number of query tokens required per image and expand the text with as many `` placeholders as there will be query tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there wil be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.num_query_tokens` and model embeddings expansion can be done by following [this link](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042). + +## InstructBlipVideoConfig + +[[autodoc]] InstructBlipVideoConfig + - from_vision_qformer_text_configs + +## InstructBlipVideoVisionConfig + +[[autodoc]] InstructBlipVideoVisionConfig + +## InstructBlipVideoQFormerConfig + +[[autodoc]] InstructBlipVideoQFormerConfig + +## InstructBlipVideoProcessor + +[[autodoc]] InstructBlipVideoProcessor + +## InstructBlipVideoImageProcessor + +[[autodoc]] InstructBlipVideoImageProcessor + - preprocess + +## InstructBlipVideoVisionModel + +[[autodoc]] InstructBlipVideoVisionModel + - forward + +## InstructBlipVideoQFormerModel + +[[autodoc]] InstructBlipVideoQFormerModel + - forward + +## InstructBlipVideoForConditionalGeneration + +[[autodoc]] InstructBlipVideoForConditionalGeneration + - forward + - generate \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jamba.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jamba.md new file mode 100644 index 0000000000000000000000000000000000000000..c8d66b163b5ad96078f4aa1ecd92bf22e6992dc0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jamba.md @@ -0,0 +1,128 @@ + + +# Jamba + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +Jamba is a state-of-the-art, hybrid SSM-Transformer LLM. It is the first production-scale Mamba implementation, which opens up interesting research and application opportunities. While this initial experimentation shows encouraging gains, we expect these to be further enhanced with future optimizations and explorations. + +For full details of this model please read the [release blog post](https://www.ai21.com/blog/announcing-jamba). + +### Model Details + +Jamba is a pretrained, mixture-of-experts (MoE) generative text model, with 12B active parameters and an overall of 52B parameters across all experts. It supports a 256K context length, and can fit up to 140K tokens on a single 80GB GPU. + +As depicted in the diagram below, Jamba's architecture features a blocks-and-layers approach that allows Jamba to successfully integrate Transformer and Mamba architectures altogether. Each Jamba block contains either an attention or a Mamba layer, followed by a multi-layer perceptron (MLP), producing an overall ratio of one Transformer layer out of every eight total layers. + + + +## Usage + +### Prerequisites + +Jamba requires you use `transformers` version 4.39.0 or higher: +```bash +pip install transformers>=4.39.0 +``` + +In order to run optimized Mamba implementations, you first need to install `mamba-ssm` and `causal-conv1d`: +```bash +pip install mamba-ssm causal-conv1d>=1.2.0 +``` +You also have to have the model on a CUDA device. + +You can run the model not using the optimized Mamba kernels, but it is **not** recommended as it will result in significantly lower latencies. In order to do that, you'll need to specify `use_mamba_kernels=False` when loading the model. + +### Run the model +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("ai21labs/Jamba-v0.1") +tokenizer = AutoTokenizer.from_pretrained("ai21labs/Jamba-v0.1") + +input_ids = tokenizer("In the recent Super Bowl LVIII,", return_tensors='pt').to(model.device)["input_ids"] + +outputs = model.generate(input_ids, max_new_tokens=216) + +print(tokenizer.batch_decode(outputs)) +# ["<|startoftext|>In the recent Super Bowl LVIII, the Kansas City Chiefs emerged victorious, defeating the San Francisco 49ers in a thrilling overtime showdown. The game was a nail-biter, with both teams showcasing their skills and determination.\n\nThe Chiefs, led by their star quarterback Patrick Mahomes, displayed their offensive prowess, while the 49ers, led by their strong defense, put up a tough fight. The game went into overtime, with the Chiefs ultimately securing the win with a touchdown.\n\nThe victory marked the Chiefs' second Super Bowl win in four years, solidifying their status as one of the top teams in the NFL. The game was a testament to the skill and talent of both teams, and a thrilling end to the NFL season.\n\nThe Super Bowl is not just about the game itself, but also about the halftime show and the commercials. This year's halftime show featured a star-studded lineup, including Usher, Alicia Keys, and Lil Jon. The show was a spectacle of music and dance, with the performers delivering an energetic and entertaining performance.\n"] +``` + +
+Loading the model in half precision + +The published checkpoint is saved in BF16. In order to load it into RAM in BF16/FP16, you need to specify `torch_dtype`: + +```python +from transformers import AutoModelForCausalLM +import torch +model = AutoModelForCausalLM.from_pretrained("ai21labs/Jamba-v0.1", torch_dtype=torch.bfloat16) +# you can also use torch_dtype=torch.float16 +``` + +When using half precision, you can enable the [FlashAttention2](https://github.com/Dao-AILab/flash-attention) implementation of the Attention blocks. In order to use it, you also need the model on a CUDA device. Since in this precision the model is to big to fit on a single 80GB GPU, you'll also need to parallelize it using [accelerate](https://huggingface.co/docs/accelerate/index): +```python +from transformers import AutoModelForCausalLM +import torch +model = AutoModelForCausalLM.from_pretrained("ai21labs/Jamba-v0.1", + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2", + device_map="auto") +``` + +
+
Load the model in 8-bit + +**Using 8-bit precision, it is possible to fit up to 140K sequence lengths on a single 80GB GPU.** You can easily quantize the model to 8-bit using [bitsandbytes](https://huggingface.co/docs/bitsandbytes/index). In order to not degrade model quality, we recommend to exclude the Mamba blocks from the quantization: + +```python +from transformers import AutoModelForCausalLM, BitsAndBytesConfig +quantization_config = BitsAndBytesConfig(load_in_8bit=True, llm_int8_skip_modules=["mamba"]) +model = AutoModelForCausalLM.from_pretrained( + "ai21labs/Jamba-v0.1", torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2", quantization_config=quantization_config +) +``` +
+ +## JambaConfig + +[[autodoc]] JambaConfig + + +## JambaModel + +[[autodoc]] JambaModel + - forward + + +## JambaForCausalLM + +[[autodoc]] JambaForCausalLM + - forward + + +## JambaForSequenceClassification + +[[autodoc]] transformers.JambaForSequenceClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jetmoe.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jetmoe.md new file mode 100644 index 0000000000000000000000000000000000000000..aba6577f70cd4b889d3c841a39032ae8a1752b96 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jetmoe.md @@ -0,0 +1,55 @@ + + +# JetMoe + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +**JetMoe-8B** is an 8B Mixture-of-Experts (MoE) language model developed by [Yikang Shen](https://scholar.google.com.hk/citations?user=qff5rRYAAAAJ) and [MyShell](https://myshell.ai/). +JetMoe project aims to provide a LLaMA2-level performance and efficient language model with a limited budget. +To achieve this goal, JetMoe uses a sparsely activated architecture inspired by the [ModuleFormer](https://arxiv.org/abs/2306.04640). +Each JetMoe block consists of two MoE layers: Mixture of Attention Heads and Mixture of MLP Experts. +Given the input tokens, it activates a subset of its experts to process them. +This sparse activation schema enables JetMoe to achieve much better training throughput than similar size dense models. +The training throughput of JetMoe-8B is around 100B tokens per day on a cluster of 96 H100 GPUs with a straightforward 3-way pipeline parallelism strategy. + +This model was contributed by [Yikang Shen](https://huggingface.co/YikangS). + + +## JetMoeConfig + +[[autodoc]] JetMoeConfig + +## JetMoeModel + +[[autodoc]] JetMoeModel + - forward + +## JetMoeForCausalLM + +[[autodoc]] JetMoeForCausalLM + - forward + +## JetMoeForSequenceClassification + +[[autodoc]] JetMoeForSequenceClassification + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jukebox.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jukebox.md new file mode 100644 index 0000000000000000000000000000000000000000..144134d9b0709b4a7ff8ca2392ac4a15569c7dcd --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/jukebox.md @@ -0,0 +1,97 @@ + +# Jukebox + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The Jukebox model was proposed in [Jukebox: A generative model for music](https://arxiv.org/pdf/2005.00341.pdf) +by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, +Ilya Sutskever. It introduces a generative music model which can produce minute long samples that can be conditioned on +an artist, genres and lyrics. + +The abstract from the paper is the following: + +*We introduce Jukebox, a model that generates music with singing in the raw audio domain. We tackle the long context of raw audio using a multiscale VQ-VAE to compress it to discrete codes, and modeling those using autoregressive Transformers. We show that the combined model at scale can generate high-fidelity and diverse songs with coherence up to multiple minutes. We can condition on artist and genre to steer the musical and vocal style, and on unaligned lyrics to make the singing more controllable. We are releasing thousands of non cherry-picked samples, along with model weights and code.* + +As shown on the following figure, Jukebox is made of 3 `priors` which are decoder only models. They follow the architecture described in [Generating Long Sequences with Sparse Transformers](https://arxiv.org/abs/1904.10509), modified to support longer context length. +First, a autoencoder is used to encode the text lyrics. Next, the first (also called `top_prior`) prior attends to the last hidden states extracted from the lyrics encoder. The priors are linked to the previous priors respectively via an `AudioConditioner` module. The`AudioConditioner` upsamples the outputs of the previous prior to raw tokens at a certain audio frame per second resolution. +The metadata such as *artist, genre and timing* are passed to each prior, in the form of a start token and positional embedding for the timing data. The hidden states are mapped to the closest codebook vector from the VQVAE in order to convert them to raw audio. + +![JukeboxModel](https://gist.githubusercontent.com/ArthurZucker/92c1acaae62ebf1b6a951710bdd8b6af/raw/c9c517bf4eff61393f6c7dec9366ef02bdd059a3/jukebox.svg) + +This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ). +The original code can be found [here](https://github.com/openai/jukebox). + +## Usage tips + +- This model only supports inference. This is for a few reasons, mostly because it requires a crazy amount of memory to train. Feel free to open a PR and add what's missing to have a full integration with the hugging face trainer! +- This model is very slow, and takes 8h to generate a minute long audio using the 5b top prior on a V100 GPU. In order automaticallay handle the device on which the model should execute, use `accelerate`. +- Contrary to the paper, the order of the priors goes from `0` to `1` as it felt more intuitive : we sample starting from `0`. +- Primed sampling (conditioning the sampling on raw audio) requires more memory than ancestral sampling and should be used with `fp16` set to `True`. + +This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ). +The original code can be found [here](https://github.com/openai/jukebox). + +## JukeboxConfig + +[[autodoc]] JukeboxConfig + +## JukeboxPriorConfig + +[[autodoc]] JukeboxPriorConfig + +## JukeboxVQVAEConfig + +[[autodoc]] JukeboxVQVAEConfig + +## JukeboxTokenizer + +[[autodoc]] JukeboxTokenizer + - save_vocabulary + +## JukeboxModel + +[[autodoc]] JukeboxModel + - ancestral_sample + - primed_sample + - continue_sample + - upsample + - _sample + +## JukeboxPrior + +[[autodoc]] JukeboxPrior + - sample + - forward + +## JukeboxVQVAE + +[[autodoc]] JukeboxVQVAE + - forward + - encode + - decode diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/kosmos-2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/kosmos-2.md new file mode 100644 index 0000000000000000000000000000000000000000..88a3b6bd99e1493d10b0bd50b9a9f69a92332a74 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/kosmos-2.md @@ -0,0 +1,102 @@ + + +# KOSMOS-2 + +
+PyTorch +
+ +## Overview + +The KOSMOS-2 model was proposed in [Kosmos-2: Grounding Multimodal Large Language Models to the World](https://arxiv.org/abs/2306.14824) by Zhiliang Peng, Wenhui Wang, Li Dong, Yaru Hao, Shaohan Huang, Shuming Ma, Furu Wei. + +KOSMOS-2 is a Transformer-based causal language model and is trained using the next-word prediction task on a web-scale +dataset of grounded image-text pairs [GRIT](https://huggingface.co/datasets/zzliang/GRIT). The spatial coordinates of +the bounding boxes in the dataset are converted to a sequence of location tokens, which are appended to their respective +entity text spans (for example, `a snowman` followed by ``). The data format is +similar to “hyperlinks” that connect the object regions in an image to their text span in the corresponding caption. + +The abstract from the paper is the following: + +*We introduce Kosmos-2, a Multimodal Large Language Model (MLLM), enabling new capabilities of perceiving object descriptions (e.g., bounding boxes) and grounding text to the visual world. Specifically, we represent refer expressions as links in Markdown, i.e., ``[text span](bounding boxes)'', where object descriptions are sequences of location tokens. Together with multimodal corpora, we construct large-scale data of grounded image-text pairs (called GrIT) to train the model. In addition to the existing capabilities of MLLMs (e.g., perceiving general modalities, following instructions, and performing in-context learning), Kosmos-2 integrates the grounding capability into downstream applications. We evaluate Kosmos-2 on a wide range of tasks, including (i) multimodal grounding, such as referring expression comprehension, and phrase grounding, (ii) multimodal referring, such as referring expression generation, (iii) perception-language tasks, and (iv) language understanding and generation. This work lays out the foundation for the development of Embodiment AI and sheds light on the big convergence of language, multimodal perception, action, and world modeling, which is a key step toward artificial general intelligence. Code and pretrained models are available at https://aka.ms/kosmos-2.* + + + + Overview of tasks that KOSMOS-2 can handle. Taken from the original paper. + +## Example + +```python +>>> from PIL import Image +>>> import requests +>>> from transformers import AutoProcessor, Kosmos2ForConditionalGeneration + +>>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224") +>>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224") + +>>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw) + +>>> prompt = " An image of" + +>>> inputs = processor(text=prompt, images=image, return_tensors="pt") + +>>> generated_ids = model.generate( +... pixel_values=inputs["pixel_values"], +... input_ids=inputs["input_ids"], +... attention_mask=inputs["attention_mask"], +... image_embeds=None, +... image_embeds_position_mask=inputs["image_embeds_position_mask"], +... use_cache=True, +... max_new_tokens=64, +... ) +>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +>>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False) +>>> processed_text +' An image of a snowman warming himself by a fire.' + +>>> caption, entities = processor.post_process_generation(generated_text) +>>> caption +'An image of a snowman warming himself by a fire.' + +>>> entities +[('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])] +``` + +This model was contributed by [Yih-Dar SHIEH](https://huggingface.co/ydshieh). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/kosmos-2). + +## Kosmos2Config + +[[autodoc]] Kosmos2Config + +## Kosmos2ImageProcessor + +## Kosmos2Processor + +[[autodoc]] Kosmos2Processor + - __call__ + +## Kosmos2Model + +[[autodoc]] Kosmos2Model + - forward + +## Kosmos2ForConditionalGeneration + +[[autodoc]] Kosmos2ForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlm.md new file mode 100644 index 0000000000000000000000000000000000000000..51cc52b7f4526d2556dd9dd158f36f6af8481759 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlm.md @@ -0,0 +1,180 @@ + + +# LayoutLM + +
+PyTorch +TensorFlow +
+ + + +## Overview + +The LayoutLM model was proposed in the paper [LayoutLM: Pre-training of Text and Layout for Document Image +Understanding](https://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, and +Ming Zhou. It's a simple but effective pretraining method of text and layout for document image understanding and +information extraction tasks, such as form understanding and receipt understanding. It obtains state-of-the-art results +on several downstream tasks: + +- form understanding: the [FUNSD](https://guillaumejaume.github.io/FUNSD/) dataset (a collection of 199 annotated + forms comprising more than 30,000 words). +- receipt understanding: the [SROIE](https://rrc.cvc.uab.es/?ch=13) dataset (a collection of 626 receipts for + training and 347 receipts for testing). +- document image classification: the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset (a collection of + 400,000 images belonging to one of 16 classes). + +The abstract from the paper is the following: + +*Pre-training techniques have been verified successfully in a variety of NLP tasks in recent years. Despite the +widespread use of pretraining models for NLP applications, they almost exclusively focus on text-level manipulation, +while neglecting layout and style information that is vital for document image understanding. In this paper, we propose +the LayoutLM to jointly model interactions between text and layout information across scanned document images, which is +beneficial for a great number of real-world document image understanding tasks such as information extraction from +scanned documents. Furthermore, we also leverage image features to incorporate words' visual information into LayoutLM. +To the best of our knowledge, this is the first time that text and layout are jointly learned in a single framework for +document-level pretraining. It achieves new state-of-the-art results in several downstream tasks, including form +understanding (from 70.72 to 79.27), receipt understanding (from 94.02 to 95.24) and document image classification +(from 93.07 to 94.42).* + +## Usage tips + +- In addition to *input_ids*, [`~transformers.LayoutLMModel.forward`] also expects the input `bbox`, which are + the bounding boxes (i.e. 2D-positions) of the input tokens. These can be obtained using an external OCR engine such + as Google's [Tesseract](https://github.com/tesseract-ocr/tesseract) (there's a [Python wrapper](https://pypi.org/project/pytesseract/) available). Each bounding box should be in (x0, y0, x1, y1) format, where + (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the + position of the lower right corner. Note that one first needs to normalize the bounding boxes to be on a 0-1000 + scale. To normalize, you can use the following function: + +```python +def normalize_bbox(bbox, width, height): + return [ + int(1000 * (bbox[0] / width)), + int(1000 * (bbox[1] / height)), + int(1000 * (bbox[2] / width)), + int(1000 * (bbox[3] / height)), + ] +``` + +Here, `width` and `height` correspond to the width and height of the original document in which the token +occurs. Those can be obtained using the Python Image Library (PIL) library for example, as follows: + +```python +from PIL import Image + +# Document can be a png, jpg, etc. PDFs must be converted to images. +image = Image.open(name_of_your_document).convert("RGB") + +width, height = image.size +``` + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LayoutLM. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + + +- A blog post on [fine-tuning + LayoutLM for document-understanding using Keras & Hugging Face + Transformers](https://www.philschmid.de/fine-tuning-layoutlm-keras). + +- A blog post on how to [fine-tune LayoutLM for document-understanding using only Hugging Face Transformers](https://www.philschmid.de/fine-tuning-layoutlm). + +- A notebook on how to [fine-tune LayoutLM on the FUNSD dataset with image embeddings](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Add_image_embeddings_to_LayoutLM.ipynb). + +- See also: [Document question answering task guide](../tasks/document_question_answering) + + + +- A notebook on how to [fine-tune LayoutLM for sequence classification on the RVL-CDIP dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb). +- [Text classification task guide](../tasks/sequence_classification) + + + +- A notebook on how to [ fine-tune LayoutLM for token classification on the FUNSD dataset](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb). +- [Token classification task guide](../tasks/token_classification) + +**Other resources** +- [Masked language modeling task guide](../tasks/masked_language_modeling) + +🚀 Deploy + +- A blog post on how to [Deploy LayoutLM with Hugging Face Inference Endpoints](https://www.philschmid.de/inference-endpoints-layoutlm). + +## LayoutLMConfig + +[[autodoc]] LayoutLMConfig + +## LayoutLMTokenizer + +[[autodoc]] LayoutLMTokenizer + +## LayoutLMTokenizerFast + +[[autodoc]] LayoutLMTokenizerFast + + + + +## LayoutLMModel + +[[autodoc]] LayoutLMModel + +## LayoutLMForMaskedLM + +[[autodoc]] LayoutLMForMaskedLM + +## LayoutLMForSequenceClassification + +[[autodoc]] LayoutLMForSequenceClassification + +## LayoutLMForTokenClassification + +[[autodoc]] LayoutLMForTokenClassification + +## LayoutLMForQuestionAnswering + +[[autodoc]] LayoutLMForQuestionAnswering + + + + +## TFLayoutLMModel + +[[autodoc]] TFLayoutLMModel + +## TFLayoutLMForMaskedLM + +[[autodoc]] TFLayoutLMForMaskedLM + +## TFLayoutLMForSequenceClassification + +[[autodoc]] TFLayoutLMForSequenceClassification + +## TFLayoutLMForTokenClassification + +[[autodoc]] TFLayoutLMForTokenClassification + +## TFLayoutLMForQuestionAnswering + +[[autodoc]] TFLayoutLMForQuestionAnswering + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv2.md new file mode 100644 index 0000000000000000000000000000000000000000..7fc5ae36197bd76d89b5179905d2f2251e44a349 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv2.md @@ -0,0 +1,344 @@ + + +# LayoutLMV2 + +
+PyTorch +
+ +## Overview + +The LayoutLMV2 model was proposed in [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, +Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou. LayoutLMV2 improves [LayoutLM](layoutlm) to obtain +state-of-the-art results across several document image understanding benchmarks: + +- information extraction from scanned documents: the [FUNSD](https://guillaumejaume.github.io/FUNSD/) dataset (a + collection of 199 annotated forms comprising more than 30,000 words), the [CORD](https://github.com/clovaai/cord) + dataset (a collection of 800 receipts for training, 100 for validation and 100 for testing), the [SROIE](https://rrc.cvc.uab.es/?ch=13) dataset (a collection of 626 receipts for training and 347 receipts for testing) + and the [Kleister-NDA](https://github.com/applicaai/kleister-nda) dataset (a collection of non-disclosure + agreements from the EDGAR database, including 254 documents for training, 83 documents for validation, and 203 + documents for testing). +- document image classification: the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset (a collection of + 400,000 images belonging to one of 16 classes). +- document visual question answering: the [DocVQA](https://arxiv.org/abs/2007.00398) dataset (a collection of 50,000 + questions defined on 12,000+ document images). + +The abstract from the paper is the following: + +*Pre-training of text and layout has proved effective in a variety of visually-rich document understanding tasks due to +its effective model architecture and the advantage of large-scale unlabeled scanned/digital-born documents. In this +paper, we present LayoutLMv2 by pre-training text, layout and image in a multi-modal framework, where new model +architectures and pre-training tasks are leveraged. Specifically, LayoutLMv2 not only uses the existing masked +visual-language modeling task but also the new text-image alignment and text-image matching tasks in the pre-training +stage, where cross-modality interaction is better learned. Meanwhile, it also integrates a spatial-aware self-attention +mechanism into the Transformer architecture, so that the model can fully understand the relative positional +relationship among different text blocks. Experiment results show that LayoutLMv2 outperforms strong baselines and +achieves new state-of-the-art results on a wide variety of downstream visually-rich document understanding tasks, +including FUNSD (0.7895 -> 0.8420), CORD (0.9493 -> 0.9601), SROIE (0.9524 -> 0.9781), Kleister-NDA (0.834 -> 0.852), +RVL-CDIP (0.9443 -> 0.9564), and DocVQA (0.7295 -> 0.8672). The pre-trained LayoutLMv2 model is publicly available at +this https URL.* + +LayoutLMv2 depends on `detectron2`, `torchvision` and `tesseract`. Run the +following to install them: +```bash +python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' +python -m pip install torchvision tesseract +``` +(If you are developing for LayoutLMv2, note that passing the doctests also requires the installation of these packages.) + +## Usage tips + +- The main difference between LayoutLMv1 and LayoutLMv2 is that the latter incorporates visual embeddings during + pre-training (while LayoutLMv1 only adds visual embeddings during fine-tuning). +- LayoutLMv2 adds both a relative 1D attention bias as well as a spatial 2D attention bias to the attention scores in + the self-attention layers. Details can be found on page 5 of the [paper](https://arxiv.org/abs/2012.14740). +- Demo notebooks on how to use the LayoutLMv2 model on RVL-CDIP, FUNSD, DocVQA, CORD can be found [here](https://github.com/NielsRogge/Transformers-Tutorials). +- LayoutLMv2 uses Facebook AI's [Detectron2](https://github.com/facebookresearch/detectron2/) package for its visual + backbone. See [this link](https://detectron2.readthedocs.io/en/latest/tutorials/install.html) for installation + instructions. +- In addition to `input_ids`, [`~LayoutLMv2Model.forward`] expects 2 additional inputs, namely + `image` and `bbox`. The `image` input corresponds to the original document image in which the text + tokens occur. The model expects each document image to be of size 224x224. This means that if you have a batch of + document images, `image` should be a tensor of shape (batch_size, 3, 224, 224). This can be either a + `torch.Tensor` or a `Detectron2.structures.ImageList`. You don't need to normalize the channels, as this is + done by the model. Important to note is that the visual backbone expects BGR channels instead of RGB, as all models + in Detectron2 are pre-trained using the BGR format. The `bbox` input are the bounding boxes (i.e. 2D-positions) + of the input text tokens. This is identical to [`LayoutLMModel`]. These can be obtained using an + external OCR engine such as Google's [Tesseract](https://github.com/tesseract-ocr/tesseract) (there's a [Python + wrapper](https://pypi.org/project/pytesseract/) available). Each bounding box should be in (x0, y0, x1, y1) + format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) + represents the position of the lower right corner. Note that one first needs to normalize the bounding boxes to be on + a 0-1000 scale. To normalize, you can use the following function: + +```python +def normalize_bbox(bbox, width, height): + return [ + int(1000 * (bbox[0] / width)), + int(1000 * (bbox[1] / height)), + int(1000 * (bbox[2] / width)), + int(1000 * (bbox[3] / height)), + ] +``` + +Here, `width` and `height` correspond to the width and height of the original document in which the token +occurs (before resizing the image). Those can be obtained using the Python Image Library (PIL) library for example, as +follows: + +```python +from PIL import Image + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +) + +width, height = image.size +``` + +However, this model includes a brand new [`~transformers.LayoutLMv2Processor`] which can be used to directly +prepare data for the model (including applying OCR under the hood). More information can be found in the "Usage" +section below. + +- Internally, [`~transformers.LayoutLMv2Model`] will send the `image` input through its visual backbone to + obtain a lower-resolution feature map, whose shape is equal to the `image_feature_pool_shape` attribute of + [`~transformers.LayoutLMv2Config`]. This feature map is then flattened to obtain a sequence of image tokens. As + the size of the feature map is 7x7 by default, one obtains 49 image tokens. These are then concatenated with the text + tokens, and send through the Transformer encoder. This means that the last hidden states of the model will have a + length of 512 + 49 = 561, if you pad the text tokens up to the max length. More generally, the last hidden states + will have a shape of `seq_length` + `image_feature_pool_shape[0]` * + `config.image_feature_pool_shape[1]`. +- When calling [`~transformers.LayoutLMv2Model.from_pretrained`], a warning will be printed with a long list of + parameter names that are not initialized. This is not a problem, as these parameters are batch normalization + statistics, which are going to have values when fine-tuning on a custom dataset. +- If you want to train the model in a distributed environment, make sure to call [`synchronize_batch_norm`] on the + model in order to properly synchronize the batch normalization layers of the visual backbone. + +In addition, there's LayoutXLM, which is a multilingual version of LayoutLMv2. More information can be found on +[LayoutXLM's documentation page](layoutxlm). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LayoutLMv2. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A notebook on how to [finetune LayoutLMv2 for text-classification on RVL-CDIP dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/RVL-CDIP/Fine_tuning_LayoutLMv2ForSequenceClassification_on_RVL_CDIP.ipynb). +- See also: [Text classification task guide](../tasks/sequence_classification) + + + +- A notebook on how to [finetune LayoutLMv2 for question-answering on DocVQA dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/DocVQA/Fine_tuning_LayoutLMv2ForQuestionAnswering_on_DocVQA.ipynb). +- See also: [Question answering task guide](../tasks/question_answering) +- See also: [Document question answering task guide](../tasks/document_question_answering) + + + + +- A notebook on how to [finetune LayoutLMv2 for token-classification on CORD dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/CORD/Fine_tuning_LayoutLMv2ForTokenClassification_on_CORD.ipynb). +- A notebook on how to [finetune LayoutLMv2 for token-classification on FUNSD dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/FUNSD/Fine_tuning_LayoutLMv2ForTokenClassification_on_FUNSD_using_HuggingFace_Trainer.ipynb). +- See also: [Token classification task guide](../tasks/token_classification) + +## Usage: LayoutLMv2Processor + +The easiest way to prepare data for the model is to use [`LayoutLMv2Processor`], which internally +combines a image processor ([`LayoutLMv2ImageProcessor`]) and a tokenizer +([`LayoutLMv2Tokenizer`] or [`LayoutLMv2TokenizerFast`]). The image processor +handles the image modality, while the tokenizer handles the text modality. A processor combines both, which is ideal +for a multi-modal model like LayoutLMv2. Note that you can still use both separately, if you only want to handle one +modality. + +```python +from transformers import LayoutLMv2ImageProcessor, LayoutLMv2TokenizerFast, LayoutLMv2Processor + +image_processor = LayoutLMv2ImageProcessor() # apply_ocr is set to True by default +tokenizer = LayoutLMv2TokenizerFast.from_pretrained("microsoft/layoutlmv2-base-uncased") +processor = LayoutLMv2Processor(image_processor, tokenizer) +``` + +In short, one can provide a document image (and possibly additional data) to [`LayoutLMv2Processor`], +and it will create the inputs expected by the model. Internally, the processor first uses +[`LayoutLMv2ImageProcessor`] to apply OCR on the image to get a list of words and normalized +bounding boxes, as well to resize the image to a given size in order to get the `image` input. The words and +normalized bounding boxes are then provided to [`LayoutLMv2Tokenizer`] or +[`LayoutLMv2TokenizerFast`], which converts them to token-level `input_ids`, +`attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide word labels to the processor, +which are turned into token-level `labels`. + +[`LayoutLMv2Processor`] uses [PyTesseract](https://pypi.org/project/pytesseract/), a Python +wrapper around Google's Tesseract OCR engine, under the hood. Note that you can still use your own OCR engine of +choice, and provide the words and normalized boxes yourself. This requires initializing +[`LayoutLMv2ImageProcessor`] with `apply_ocr` set to `False`. + +In total, there are 5 use cases that are supported by the processor. Below, we list them all. Note that each of these +use cases work for both batched and non-batched inputs (we illustrate them for non-batched inputs). + +**Use case 1: document image classification (training, inference) + token classification (inference), apply_ocr = +True** + +This is the simplest case, in which the processor (actually the image processor) will perform OCR on the image to get +the words and normalized bounding boxes. + +```python +from transformers import LayoutLMv2Processor +from PIL import Image + +processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased") + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +).convert("RGB") +encoding = processor( + image, return_tensors="pt" +) # you can also add all tokenizer parameters here such as padding, truncation +print(encoding.keys()) +# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image']) +``` + +**Use case 2: document image classification (training, inference) + token classification (inference), apply_ocr=False** + +In case one wants to do OCR themselves, one can initialize the image processor with `apply_ocr` set to +`False`. In that case, one should provide the words and corresponding (normalized) bounding boxes themselves to +the processor. + +```python +from transformers import LayoutLMv2Processor +from PIL import Image + +processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr") + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +).convert("RGB") +words = ["hello", "world"] +boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes +encoding = processor(image, words, boxes=boxes, return_tensors="pt") +print(encoding.keys()) +# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image']) +``` + +**Use case 3: token classification (training), apply_ocr=False** + +For token classification tasks (such as FUNSD, CORD, SROIE, Kleister-NDA), one can also provide the corresponding word +labels in order to train a model. The processor will then convert these into token-level `labels`. By default, it +will only label the first wordpiece of a word, and label the remaining wordpieces with -100, which is the +`ignore_index` of PyTorch's CrossEntropyLoss. In case you want all wordpieces of a word to be labeled, you can +initialize the tokenizer with `only_label_first_subword` set to `False`. + +```python +from transformers import LayoutLMv2Processor +from PIL import Image + +processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr") + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +).convert("RGB") +words = ["hello", "world"] +boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes +word_labels = [1, 2] +encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="pt") +print(encoding.keys()) +# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'labels', 'image']) +``` + +**Use case 4: visual question answering (inference), apply_ocr=True** + +For visual question answering tasks (such as DocVQA), you can provide a question to the processor. By default, the +processor will apply OCR on the image, and create [CLS] question tokens [SEP] word tokens [SEP]. + +```python +from transformers import LayoutLMv2Processor +from PIL import Image + +processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased") + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +).convert("RGB") +question = "What's his name?" +encoding = processor(image, question, return_tensors="pt") +print(encoding.keys()) +# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image']) +``` + +**Use case 5: visual question answering (inference), apply_ocr=False** + +For visual question answering tasks (such as DocVQA), you can provide a question to the processor. If you want to +perform OCR yourself, you can provide your own words and (normalized) bounding boxes to the processor. + +```python +from transformers import LayoutLMv2Processor +from PIL import Image + +processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr") + +image = Image.open( + "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)." +).convert("RGB") +question = "What's his name?" +words = ["hello", "world"] +boxes = [[1, 2, 3, 4], [5, 6, 7, 8]] # make sure to normalize your bounding boxes +encoding = processor(image, question, words, boxes=boxes, return_tensors="pt") +print(encoding.keys()) +# dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'bbox', 'image']) +``` + +## LayoutLMv2Config + +[[autodoc]] LayoutLMv2Config + +## LayoutLMv2FeatureExtractor + +[[autodoc]] LayoutLMv2FeatureExtractor + - __call__ + +## LayoutLMv2ImageProcessor + +[[autodoc]] LayoutLMv2ImageProcessor + - preprocess + +## LayoutLMv2Tokenizer + +[[autodoc]] LayoutLMv2Tokenizer + - __call__ + - save_vocabulary + +## LayoutLMv2TokenizerFast + +[[autodoc]] LayoutLMv2TokenizerFast + - __call__ + +## LayoutLMv2Processor + +[[autodoc]] LayoutLMv2Processor + - __call__ + +## LayoutLMv2Model + +[[autodoc]] LayoutLMv2Model + - forward + +## LayoutLMv2ForSequenceClassification + +[[autodoc]] LayoutLMv2ForSequenceClassification + +## LayoutLMv2ForTokenClassification + +[[autodoc]] LayoutLMv2ForTokenClassification + +## LayoutLMv2ForQuestionAnswering + +[[autodoc]] LayoutLMv2ForQuestionAnswering diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv3.md new file mode 100644 index 0000000000000000000000000000000000000000..5ab998dc3cd88b35b0292a8820a052db1cdcdd71 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutlmv3.md @@ -0,0 +1,154 @@ + + +# LayoutLMv3 + +## Overview + +The LayoutLMv3 model was proposed in [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei. +LayoutLMv3 simplifies [LayoutLMv2](layoutlmv2) by using patch embeddings (as in [ViT](vit)) instead of leveraging a CNN backbone, and pre-trains the model on 3 objectives: masked language modeling (MLM), masked image modeling (MIM) +and word-patch alignment (WPA). + +The abstract from the paper is the following: + +*Self-supervised pre-training techniques have achieved remarkable progress in Document AI. Most multimodal pre-trained models use a masked language modeling objective to learn bidirectional representations on the text modality, but they differ in pre-training objectives for the image modality. This discrepancy adds difficulty to multimodal representation learning. In this paper, we propose LayoutLMv3 to pre-train multimodal Transformers for Document AI with unified text and image masking. Additionally, LayoutLMv3 is pre-trained with a word-patch alignment objective to learn cross-modal alignment by predicting whether the corresponding image patch of a text word is masked. The simple unified architecture and training objectives make LayoutLMv3 a general-purpose pre-trained model for both text-centric and image-centric Document AI tasks. Experimental results show that LayoutLMv3 achieves state-of-the-art performance not only in text-centric tasks, including form understanding, receipt understanding, and document visual question answering, but also in image-centric tasks such as document image classification and document layout analysis.* + + + + LayoutLMv3 architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The TensorFlow version of this model was added by [chriskoo](https://huggingface.co/chriskoo), [tokec](https://huggingface.co/tokec), and [lre](https://huggingface.co/lre). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/layoutlmv3). + +## Usage tips + +- In terms of data processing, LayoutLMv3 is identical to its predecessor [LayoutLMv2](layoutlmv2), except that: + - images need to be resized and normalized with channels in regular RGB format. LayoutLMv2 on the other hand normalizes the images internally and expects the channels in BGR format. + - text is tokenized using byte-pair encoding (BPE), as opposed to WordPiece. + Due to these differences in data preprocessing, one can use [`LayoutLMv3Processor`] which internally combines a [`LayoutLMv3ImageProcessor`] (for the image modality) and a [`LayoutLMv3Tokenizer`]/[`LayoutLMv3TokenizerFast`] (for the text modality) to prepare all data for the model. +- Regarding usage of [`LayoutLMv3Processor`], we refer to the [usage guide](layoutlmv2#usage-layoutlmv2processor) of its predecessor. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LayoutLMv3. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +LayoutLMv3 is nearly identical to LayoutLMv2, so we've also included LayoutLMv2 resources you can adapt for LayoutLMv3 tasks. For these notebooks, take care to use [`LayoutLMv2Processor`] instead when preparing data for the model! + + + +- Demo notebooks for LayoutLMv3 can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/LayoutLMv3). +- Demo scripts can be found [here](https://github.com/huggingface/transformers-research-projects/tree/main/layoutlmv3). + + + +- [`LayoutLMv2ForSequenceClassification`] is supported by this [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/RVL-CDIP/Fine_tuning_LayoutLMv2ForSequenceClassification_on_RVL_CDIP.ipynb). +- [Text classification task guide](../tasks/sequence_classification) + + + +- [`LayoutLMv3ForTokenClassification`] is supported by this [example script](https://github.com/huggingface/transformers-research-projects/tree/main/layoutlmv3) and [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv3/Fine_tune_LayoutLMv3_on_FUNSD_(HuggingFace_Trainer).ipynb). +- A [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/FUNSD/Inference_with_LayoutLMv2ForTokenClassification.ipynb) for how to perform inference with [`LayoutLMv2ForTokenClassification`] and a [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/FUNSD/True_inference_with_LayoutLMv2ForTokenClassification_%2B_Gradio_demo.ipynb) for how to perform inference when no labels are available with [`LayoutLMv2ForTokenClassification`]. +- A [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/FUNSD/Fine_tuning_LayoutLMv2ForTokenClassification_on_FUNSD_using_HuggingFace_Trainer.ipynb) for how to finetune [`LayoutLMv2ForTokenClassification`] with the 🤗 Trainer. +- [Token classification task guide](../tasks/token_classification) + + + +- [`LayoutLMv2ForQuestionAnswering`] is supported by this [notebook](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/DocVQA/Fine_tuning_LayoutLMv2ForQuestionAnswering_on_DocVQA.ipynb). +- [Question answering task guide](../tasks/question_answering) + +**Document question answering** +- [Document question answering task guide](../tasks/document_question_answering) + +## LayoutLMv3Config + +[[autodoc]] LayoutLMv3Config + +## LayoutLMv3FeatureExtractor + +[[autodoc]] LayoutLMv3FeatureExtractor + - __call__ + +## LayoutLMv3ImageProcessor + +[[autodoc]] LayoutLMv3ImageProcessor + - preprocess + +## LayoutLMv3Tokenizer + +[[autodoc]] LayoutLMv3Tokenizer + - __call__ + - save_vocabulary + +## LayoutLMv3TokenizerFast + +[[autodoc]] LayoutLMv3TokenizerFast + - __call__ + +## LayoutLMv3Processor + +[[autodoc]] LayoutLMv3Processor + - __call__ + + + + +## LayoutLMv3Model + +[[autodoc]] LayoutLMv3Model + - forward + +## LayoutLMv3ForSequenceClassification + +[[autodoc]] LayoutLMv3ForSequenceClassification + - forward + +## LayoutLMv3ForTokenClassification + +[[autodoc]] LayoutLMv3ForTokenClassification + - forward + +## LayoutLMv3ForQuestionAnswering + +[[autodoc]] LayoutLMv3ForQuestionAnswering + - forward + + + + +## TFLayoutLMv3Model + +[[autodoc]] TFLayoutLMv3Model + - call + +## TFLayoutLMv3ForSequenceClassification + +[[autodoc]] TFLayoutLMv3ForSequenceClassification + - call + +## TFLayoutLMv3ForTokenClassification + +[[autodoc]] TFLayoutLMv3ForTokenClassification + - call + +## TFLayoutLMv3ForQuestionAnswering + +[[autodoc]] TFLayoutLMv3ForQuestionAnswering + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutxlm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutxlm.md new file mode 100644 index 0000000000000000000000000000000000000000..96e0a4d4bf5134459a8a43e8980184566fc90155 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/layoutxlm.md @@ -0,0 +1,89 @@ + + +# LayoutXLM + +
+PyTorch +
+ +## Overview + +LayoutXLM was proposed in [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha +Zhang, Furu Wei. It's a multilingual extension of the [LayoutLMv2 model](https://arxiv.org/abs/2012.14740) trained +on 53 languages. + +The abstract from the paper is the following: + +*Multimodal pre-training with text, layout, and image has achieved SOTA performance for visually-rich document +understanding tasks recently, which demonstrates the great potential for joint learning across different modalities. In +this paper, we present LayoutXLM, a multimodal pre-trained model for multilingual document understanding, which aims to +bridge the language barriers for visually-rich document understanding. To accurately evaluate LayoutXLM, we also +introduce a multilingual form understanding benchmark dataset named XFUN, which includes form understanding samples in +7 languages (Chinese, Japanese, Spanish, French, Italian, German, Portuguese), and key-value pairs are manually labeled +for each language. Experiment results show that the LayoutXLM model has significantly outperformed the existing SOTA +cross-lingual pre-trained models on the XFUN dataset.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/microsoft/unilm). + +## Usage tips and examples + +One can directly plug in the weights of LayoutXLM into a LayoutLMv2 model, like so: + +```python +from transformers import LayoutLMv2Model + +model = LayoutLMv2Model.from_pretrained("microsoft/layoutxlm-base") +``` + +Note that LayoutXLM has its own tokenizer, based on +[`LayoutXLMTokenizer`]/[`LayoutXLMTokenizerFast`]. You can initialize it as +follows: + +```python +from transformers import LayoutXLMTokenizer + +tokenizer = LayoutXLMTokenizer.from_pretrained("microsoft/layoutxlm-base") +``` + +Similar to LayoutLMv2, you can use [`LayoutXLMProcessor`] (which internally applies +[`LayoutLMv2ImageProcessor`] and +[`LayoutXLMTokenizer`]/[`LayoutXLMTokenizerFast`] in sequence) to prepare all +data for the model. + + + +As LayoutXLM's architecture is equivalent to that of LayoutLMv2, one can refer to [LayoutLMv2's documentation page](layoutlmv2) for all tips, code examples and notebooks. + + +## LayoutXLMTokenizer + +[[autodoc]] LayoutXLMTokenizer + - __call__ + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## LayoutXLMTokenizerFast + +[[autodoc]] LayoutXLMTokenizerFast + - __call__ + +## LayoutXLMProcessor + +[[autodoc]] LayoutXLMProcessor + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/led.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/led.md new file mode 100644 index 0000000000000000000000000000000000000000..729d5666d8a3d3be4e72c725267de4af22ffcca0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/led.md @@ -0,0 +1,148 @@ + + +# LED + +
+PyTorch +TensorFlow +
+ +## Overview + +The LED model was proposed in [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz +Beltagy, Matthew E. Peters, Arman Cohan. + +The abstract from the paper is the following: + +*Transformer-based models are unable to process long sequences due to their self-attention operation, which scales +quadratically with the sequence length. To address this limitation, we introduce the Longformer with an attention +mechanism that scales linearly with sequence length, making it easy to process documents of thousands of tokens or +longer. Longformer's attention mechanism is a drop-in replacement for the standard self-attention and combines a local +windowed attention with a task motivated global attention. Following prior work on long-sequence transformers, we +evaluate Longformer on character-level language modeling and achieve state-of-the-art results on text8 and enwik8. In +contrast to most prior work, we also pretrain Longformer and finetune it on a variety of downstream tasks. Our +pretrained Longformer consistently outperforms RoBERTa on long document tasks and sets new state-of-the-art results on +WikiHop and TriviaQA. We finally introduce the Longformer-Encoder-Decoder (LED), a Longformer variant for supporting +long document generative sequence-to-sequence tasks, and demonstrate its effectiveness on the arXiv summarization +dataset.* + +## Usage tips + +- [`LEDForConditionalGeneration`] is an extension of + [`BartForConditionalGeneration`] exchanging the traditional *self-attention* layer with + *Longformer*'s *chunked self-attention* layer. [`LEDTokenizer`] is an alias of + [`BartTokenizer`]. +- LED works very well on long-range *sequence-to-sequence* tasks where the `input_ids` largely exceed a length of + 1024 tokens. +- LED pads the `input_ids` to be a multiple of `config.attention_window` if required. Therefore a small speed-up is + gained, when [`LEDTokenizer`] is used with the `pad_to_multiple_of` argument. +- LED makes use of *global attention* by means of the `global_attention_mask` (see + [`LongformerModel`]). For summarization, it is advised to put *global attention* only on the first + `` token. For question answering, it is advised to put *global attention* on all tokens of the question. +- To fine-tune LED on all 16384, *gradient checkpointing* can be enabled in case training leads to out-of-memory (OOM) + errors. This can be done by executing `model.gradient_checkpointing_enable()`. + Moreover, the `use_cache=False` + flag can be used to disable the caching mechanism to save memory. +- LED is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than + the left. + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). + +## Resources + +- [A notebook showing how to evaluate LED](https://colab.research.google.com/drive/12INTTR6n64TzS4RrXZxMSXfrOd9Xzamo?usp=sharing). +- [A notebook showing how to fine-tune LED](https://colab.research.google.com/drive/12LjJazBl7Gam0XBPy_y0CTOJZeZ34c2v?usp=sharing). +- [Text classification task guide](../tasks/sequence_classification) +- [Question answering task guide](../tasks/question_answering) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## LEDConfig + +[[autodoc]] LEDConfig + +## LEDTokenizer + +[[autodoc]] LEDTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## LEDTokenizerFast + +[[autodoc]] LEDTokenizerFast + +## LED specific outputs + +[[autodoc]] models.led.modeling_led.LEDEncoderBaseModelOutput + +[[autodoc]] models.led.modeling_led.LEDSeq2SeqModelOutput + +[[autodoc]] models.led.modeling_led.LEDSeq2SeqLMOutput + +[[autodoc]] models.led.modeling_led.LEDSeq2SeqSequenceClassifierOutput + +[[autodoc]] models.led.modeling_led.LEDSeq2SeqQuestionAnsweringModelOutput + +[[autodoc]] models.led.modeling_tf_led.TFLEDEncoderBaseModelOutput + +[[autodoc]] models.led.modeling_tf_led.TFLEDSeq2SeqModelOutput + +[[autodoc]] models.led.modeling_tf_led.TFLEDSeq2SeqLMOutput + + + + +## LEDModel + +[[autodoc]] LEDModel + - forward + +## LEDForConditionalGeneration + +[[autodoc]] LEDForConditionalGeneration + - forward + +## LEDForSequenceClassification + +[[autodoc]] LEDForSequenceClassification + - forward + +## LEDForQuestionAnswering + +[[autodoc]] LEDForQuestionAnswering + - forward + + + + +## TFLEDModel + +[[autodoc]] TFLEDModel + - call + +## TFLEDForConditionalGeneration + +[[autodoc]] TFLEDForConditionalGeneration + - call + + + + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/levit.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/levit.md new file mode 100644 index 0000000000000000000000000000000000000000..af42c1533e53ebf92e033de7b4550a3a6f5d0327 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/levit.md @@ -0,0 +1,110 @@ + + +# LeViT + +
+PyTorch +
+ +## Overview + +The LeViT model was proposed in [LeViT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze. LeViT improves the [Vision Transformer (ViT)](vit) in performance and efficiency by a few architectural differences such as activation maps with decreasing resolutions in Transformers and the introduction of an attention bias to integrate positional information. + +The abstract from the paper is the following: + +*We design a family of image classification architectures that optimize the trade-off between accuracy +and efficiency in a high-speed regime. Our work exploits recent findings in attention-based architectures, +which are competitive on highly parallel processing hardware. We revisit principles from the extensive +literature on convolutional neural networks to apply them to transformers, in particular activation maps +with decreasing resolutions. We also introduce the attention bias, a new way to integrate positional information +in vision transformers. As a result, we propose LeVIT: a hybrid neural network for fast inference image classification. +We consider different measures of efficiency on different hardware platforms, so as to best reflect a wide range of +application scenarios. Our extensive experiments empirically validate our technical choices and show they are suitable +to most architectures. Overall, LeViT significantly outperforms existing convnets and vision transformers with respect +to the speed/accuracy tradeoff. For example, at 80% ImageNet top-1 accuracy, LeViT is 5 times faster than EfficientNet on CPU. * + + + + LeViT Architecture. Taken from the original paper. + +This model was contributed by [anugunj](https://huggingface.co/anugunj). The original code can be found [here](https://github.com/facebookresearch/LeViT). + +## Usage tips + +- Compared to ViT, LeViT models use an additional distillation head to effectively learn from a teacher (which, in the LeViT paper, is a ResNet like-model). The distillation head is learned through backpropagation under supervision of a ResNet like-model. They also draw inspiration from convolution neural networks to use activation maps with decreasing resolutions to increase the efficiency. +- There are 2 ways to fine-tune distilled models, either (1) in a classic way, by only placing a prediction head on top + of the final hidden state and not using the distillation head, or (2) by placing both a prediction head and distillation + head on top of the final hidden state. In that case, the prediction head is trained using regular cross-entropy between + the prediction of the head and the ground-truth label, while the distillation prediction head is trained using hard distillation + (cross-entropy between the prediction of the distillation head and the label predicted by the teacher). At inference time, + one takes the average prediction between both heads as final prediction. (2) is also called "fine-tuning with distillation", + because one relies on a teacher that has already been fine-tuned on the downstream dataset. In terms of models, (1) corresponds + to [`LevitForImageClassification`] and (2) corresponds to [`LevitForImageClassificationWithTeacher`]. +- All released checkpoints were pre-trained and fine-tuned on [ImageNet-1k](https://huggingface.co/datasets/imagenet-1k) + (also referred to as ILSVRC 2012, a collection of 1.3 million images and 1,000 classes). only. No external data was used. This is in + contrast with the original ViT model, which used external data like the JFT-300M dataset/Imagenet-21k for + pre-training. +- The authors of LeViT released 5 trained LeViT models, which you can directly plug into [`LevitModel`] or [`LevitForImageClassification`]. + Techniques like data augmentation, optimization, and regularization were used in order to simulate training on a much larger dataset + (while only using ImageNet-1k for pre-training). The 5 variants available are (all trained on images of size 224x224): + *facebook/levit-128S*, *facebook/levit-128*, *facebook/levit-192*, *facebook/levit-256* and + *facebook/levit-384*. Note that one should use [`LevitImageProcessor`] in order to + prepare images for the model. +- [`LevitForImageClassificationWithTeacher`] currently supports only inference and not training or fine-tuning. +- You can check out demo notebooks regarding inference as well as fine-tuning on custom data [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer) + (you can just replace [`ViTFeatureExtractor`] by [`LevitImageProcessor`] and [`ViTForImageClassification`] by [`LevitForImageClassification`] or [`LevitForImageClassificationWithTeacher`]). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LeViT. + + + +- [`LevitForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## LevitConfig + +[[autodoc]] LevitConfig + +## LevitFeatureExtractor + +[[autodoc]] LevitFeatureExtractor + - __call__ + +## LevitImageProcessor + + [[autodoc]] LevitImageProcessor + - preprocess + +## LevitModel + +[[autodoc]] LevitModel + - forward + +## LevitForImageClassification + +[[autodoc]] LevitForImageClassification + - forward + +## LevitForImageClassificationWithTeacher + +[[autodoc]] LevitForImageClassificationWithTeacher + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lilt.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lilt.md new file mode 100644 index 0000000000000000000000000000000000000000..2474d854e030538724837e596d87e3e439a76c44 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lilt.md @@ -0,0 +1,92 @@ + + +# LiLT + +
+PyTorch +
+ +## Overview + +The LiLT model was proposed in [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding. +LiLT allows to combine any pre-trained RoBERTa text encoder with a lightweight Layout Transformer, to enable [LayoutLM](layoutlm)-like document understanding for many +languages. + +The abstract from the paper is the following: + +*Structured document understanding has attracted considerable attention and made significant progress recently, owing to its crucial role in intelligent document processing. However, most existing related models can only deal with the document data of specific language(s) (typically English) included in the pre-training collection, which is extremely limited. To address this issue, we propose a simple yet effective Language-independent Layout Transformer (LiLT) for structured document understanding. LiLT can be pre-trained on the structured documents of a single language and then directly fine-tuned on other languages with the corresponding off-the-shelf monolingual/multilingual pre-trained textual models. Experimental results on eight languages have shown that LiLT can achieve competitive or even superior performance on diverse widely-used downstream benchmarks, which enables language-independent benefit from the pre-training of document layout structure.* + + + + LiLT architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/jpwang/lilt). + +## Usage tips + +- To combine the Language-Independent Layout Transformer with a new RoBERTa checkpoint from the [hub](https://huggingface.co/models?search=roberta), refer to [this guide](https://github.com/jpWang/LiLT#or-generate-your-own-checkpoint-optional). +The script will result in `config.json` and `pytorch_model.bin` files being stored locally. After doing this, one can do the following (assuming you're logged in with your HuggingFace account): + +```python +from transformers import LiltModel + +model = LiltModel.from_pretrained("path_to_your_files") +model.push_to_hub("name_of_repo_on_the_hub") +``` + +- When preparing data for the model, make sure to use the token vocabulary that corresponds to the RoBERTa checkpoint you combined with the Layout Transformer. +- As [lilt-roberta-en-base](https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base) uses the same vocabulary as [LayoutLMv3](layoutlmv3), one can use [`LayoutLMv3TokenizerFast`] to prepare data for the model. +The same is true for [lilt-roberta-en-base](https://huggingface.co/SCUT-DLVCLab/lilt-infoxlm-base): one can use [`LayoutXLMTokenizerFast`] for that model. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LiLT. + +- Demo notebooks for LiLT can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/LiLT). + +**Documentation resources** +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## LiltConfig + +[[autodoc]] LiltConfig + +## LiltModel + +[[autodoc]] LiltModel + - forward + +## LiltForSequenceClassification + +[[autodoc]] LiltForSequenceClassification + - forward + +## LiltForTokenClassification + +[[autodoc]] LiltForTokenClassification + - forward + +## LiltForQuestionAnswering + +[[autodoc]] LiltForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama.md new file mode 100644 index 0000000000000000000000000000000000000000..c127e0d73c00a7d6dc93220e3f5b2babe2c7c947 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama.md @@ -0,0 +1,145 @@ + + +# LLaMA + +
+PyTorch +Flax +FlashAttention +SDPA +
+ +## Overview + +The LLaMA model was proposed in [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/abs/2302.13971) by Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, Aurelien Rodriguez, Armand Joulin, Edouard Grave, Guillaume Lample. It is a collection of foundation language models ranging from 7B to 65B parameters. + +The abstract from the paper is the following: + +*We introduce LLaMA, a collection of foundation language models ranging from 7B to 65B parameters. We train our models on trillions of tokens, and show that it is possible to train state-of-the-art models using publicly available datasets exclusively, without resorting to proprietary and inaccessible datasets. In particular, LLaMA-13B outperforms GPT-3 (175B) on most benchmarks, and LLaMA-65B is competitive with the best models, Chinchilla-70B and PaLM-540B. We release all our models to the research community. * + +This model was contributed by [zphang](https://huggingface.co/zphang) with contributions from [BlackSamorez](https://huggingface.co/BlackSamorez). The code of the implementation in Hugging Face is based on GPT-NeoX [here](https://github.com/EleutherAI/gpt-neox). The original code of the authors can be found [here](https://github.com/facebookresearch/llama). + +## Usage tips + +- Weights for the LLaMA models can be obtained from by filling out [this form](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform?usp=send_form) +- After downloading the weights, they will need to be converted to the Hugging Face Transformers format using the [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py). The script can be called with the following (example) command: + +```bash +python src/transformers/models/llama/convert_llama_weights_to_hf.py \ + --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path +``` + +- After conversion, the model and tokenizer can be loaded via: + +```python +from transformers import LlamaForCausalLM, LlamaTokenizer + +tokenizer = LlamaTokenizer.from_pretrained("/output/path") +model = LlamaForCausalLM.from_pretrained("/output/path") +``` + +Note that executing the script requires enough CPU RAM to host the whole model in float16 precision (even if the biggest versions +come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). For the 65B model, it's thus 130GB of RAM needed. + +- The LLaMA tokenizer is a BPE model based on [sentencepiece](https://github.com/google/sentencepiece). One quirk of sentencepiece is that when decoding a sequence, if the first token is the start of the word (e.g. "Banana"), the tokenizer does not prepend the prefix space to the string. + +This model was contributed by [zphang](https://huggingface.co/zphang) with contributions from [BlackSamorez](https://huggingface.co/BlackSamorez). The code of the implementation in Hugging Face is based on GPT-NeoX [here](https://github.com/EleutherAI/gpt-neox). The original code of the authors can be found [here](https://github.com/facebookresearch/llama). The Flax version of the implementation was contributed by [afmck](https://huggingface.co/afmck) with the code in the implementation based on Hugging Face's Flax GPT-Neo. + + +Based on the original LLaMA model, Meta AI has released some follow-up works: + +- **Llama2**: Llama2 is an improved version of Llama with some architectural tweaks (Grouped Query Attention), and is pre-trained on 2Trillion tokens. Refer to the documentation of Llama2 which can be found [here](llama2). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LLaMA. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A [notebook](https://colab.research.google.com/github/bigscience-workshop/petals/blob/main/examples/prompt-tuning-sst2.ipynb#scrollTo=f04ba4d2) on how to use prompt tuning to adapt the LLaMA model for text classification task. 🌎 + + + +- [StackLLaMA: A hands-on guide to train LLaMA with RLHF](https://huggingface.co/blog/stackllama#stackllama-a-hands-on-guide-to-train-llama-with-rlhf), a blog post about how to train LLaMA to answer questions on [Stack Exchange](https://stackexchange.com/) with RLHF. + +⚗️ Optimization +- A [notebook](https://colab.research.google.com/drive/1SQUXq1AMZPSLD4mk3A3swUIc6Y2dclme?usp=sharing) on how to fine-tune LLaMA model using xturing library on GPU which has limited memory. 🌎 + +⚡️ Inference +- A [notebook](https://colab.research.google.com/github/DominguesM/alpaca-lora-ptbr-7b/blob/main/notebooks/02%20-%20Evaluate.ipynb) on how to run the LLaMA Model using PeftModel from the 🤗 PEFT library. 🌎 +- A [notebook](https://colab.research.google.com/drive/1l2GiSSPbajVyp2Nk3CFT4t3uH6-5TiBe?usp=sharing) on how to load a PEFT adapter LLaMA model with LangChain. 🌎 + +🚀 Deploy +- A [notebook](https://colab.research.google.com/github/lxe/simple-llama-finetuner/blob/master/Simple_LLaMA_FineTuner.ipynb#scrollTo=3PM_DilAZD8T) on how to fine-tune LLaMA model using LoRA method via the 🤗 PEFT library with intuitive UI. 🌎 +- A [notebook](https://github.com/aws/amazon-sagemaker-examples/blob/main/introduction_to_amazon_algorithms/jumpstart-foundation-models/text-generation-open-llama.ipynb) on how to deploy Open-LLaMA model for text generation on Amazon SageMaker. 🌎 + +## LlamaConfig + +[[autodoc]] LlamaConfig + +## LlamaTokenizer + +[[autodoc]] LlamaTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## LlamaTokenizerFast + +[[autodoc]] LlamaTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary + +## LlamaModel + +[[autodoc]] LlamaModel + - forward + +## LlamaForCausalLM + +[[autodoc]] LlamaForCausalLM + - forward + +## LlamaForSequenceClassification + +[[autodoc]] LlamaForSequenceClassification + - forward + +## LlamaForQuestionAnswering + +[[autodoc]] LlamaForQuestionAnswering + - forward + +## LlamaForTokenClassification + +[[autodoc]] LlamaForTokenClassification + - forward + +## FlaxLlamaModel + +[[autodoc]] FlaxLlamaModel + - __call__ + +## FlaxLlamaForCausalLM + +[[autodoc]] FlaxLlamaForCausalLM + - __call__ diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama2.md new file mode 100644 index 0000000000000000000000000000000000000000..4e5f572c4b20af48a438401e63eeb95bf555f787 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama2.md @@ -0,0 +1,146 @@ + + +# Llama2 + +
+PyTorch +Flax +
+ +## Overview + +The Llama2 model was proposed in [LLaMA: Open Foundation and Fine-Tuned Chat Models](https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/) by Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton Ferrer, Moya Chen, Guillem Cucurull, David Esiobu, Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller, Cynthia Gao, Vedanuj Goswami, Naman Goyal, Anthony Hartshorn, Saghar Hosseini, Rui Hou, Hakan Inan, Marcin Kardas, Viktor Kerkez Madian Khabsa, Isabel Kloumann, Artem Korenev, Punit Singh Koura, Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Diana Liskovich, Yinghai Lu, Yuning Mao, Xavier Martinet, Todor Mihaylov, Pushka rMishra, Igor Molybog, Yixin Nie, Andrew Poulton, Jeremy Reizenstein, Rashi Rungta, Kalyan Saladi, Alan Schelten, Ruan Silva, Eric Michael Smith, Ranjan Subramanian, Xiaoqing EllenTan, Binh Tang, Ross Taylor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, Melanie Kambadur, Sharan Narang, Aurelien Rodriguez, Robert Stojnic, Sergey Edunov, Thomas Scialom. It is a collection of foundation language models ranging from 7B to 70B parameters, with checkpoints finetuned for chat application! + +The abstract from the paper is the following: + +*In this work, we develop and release Llama 2, a collection of pretrained and fine-tuned large language models (LLMs) ranging in scale from 7 billion to 70 billion parameters. Our fine-tuned LLMs, called Llama 2-Chat, are optimized for dialogue use cases. Our models outperform open-source chat models on most benchmarks we tested, and based on our human evaluations for helpfulness and safety, may be a suitable substitute for closed-source models. We provide a detailed description of our approach to fine-tuning and safety improvements of Llama 2-Chat in order to enable the community to build on our work and contribute to the responsible development of LLMs.* + +Checkout all Llama2 model checkpoints [here](https://huggingface.co/models?search=llama2). +This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ) with contributions from [Lysandre Debut](https://huggingface.co/lysandre). The code of the implementation in Hugging Face is based on GPT-NeoX [here](https://github.com/EleutherAI/gpt-neox). The original code of the authors can be found [here](https://github.com/facebookresearch/llama). + +## Usage tips + + + +The `Llama2` models were trained using `bfloat16`, but the original inference uses `float16`. The checkpoints uploaded on the Hub use `torch_dtype = 'float16'`, which will be +used by the `AutoModel` API to cast the checkpoints from `torch.float32` to `torch.float16`. + +The `dtype` of the online weights is mostly irrelevant unless you are using `torch_dtype="auto"` when initializing a model using `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`. The reason is that the model will first be downloaded ( using the `dtype` of the checkpoints online), then it will be casted to the default `dtype` of `torch` (becomes `torch.float32`), and finally, if there is a `torch_dtype` provided in the config, it will be used. + +Training the model in `float16` is not recommended and is known to produce `nan`; as such, the model should be trained in `bfloat16`. + + + +Tips: + +- Weights for the Llama2 models can be obtained by filling out [this form](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) +- The architecture is very similar to the first Llama, with the addition of Grouped Query Attention (GQA) following this [paper](https://arxiv.org/pdf/2305.13245.pdf) +- Setting `config.pretraining_tp` to a value different than 1 will activate the more accurate but slower computation of the linear layers, which should better match the original logits. +- The original model uses `pad_id = -1` which means that there is no padding token. We can't have the same logic, make sure to add a padding token using `tokenizer.add_special_tokens({"pad_token":""})` and resize the token embedding accordingly. You should also set the `model.config.pad_token_id`. The `embed_tokens` layer of the model is initialized with `self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.config.padding_idx)`, which makes sure that encoding the padding token will output zeros, so passing it when initializing is recommended. +- After filling out the form and gaining access to the model checkpoints, you should be able to use the already converted checkpoints. Otherwise, if you are converting your own model, feel free to use the [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py). The script can be called with the following (example) command: + +```bash +python src/transformers/models/llama/convert_llama_weights_to_hf.py \ + --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path +``` + +- After conversion, the model and tokenizer can be loaded via: + +```python +from transformers import LlamaForCausalLM, LlamaTokenizer + +tokenizer = LlamaTokenizer.from_pretrained("/output/path") +model = LlamaForCausalLM.from_pretrained("/output/path") +``` + +Note that executing the script requires enough CPU RAM to host the whole model in float16 precision (even if the biggest versions +come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). For the 75B model, it's thus 145GB of RAM needed. + +- The LLaMA tokenizer is a BPE model based on [sentencepiece](https://github.com/google/sentencepiece). One quirk of sentencepiece is that when decoding a sequence, if the first token is the start of the word (e.g. "Banana"), the tokenizer does not prepend the prefix space to the string. + +- When using Flash Attention 2 via `attn_implementation="flash_attention_2"`, don't pass `torch_dtype` to the `from_pretrained` class method and use Automatic Mixed-Precision training. When using `Trainer`, it is simply specifying either `fp16` or `bf16` to `True`. Otherwise, make sure you are using `torch.autocast`. This is required because the Flash Attention only support `fp16` and `bf16` data type. + + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LLaMA2. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + +- [Llama 2 is here - get it on Hugging Face](https://huggingface.co/blog/llama2), a blog post about Llama 2 and how to use it with 🤗 Transformers and 🤗 PEFT. +- [LLaMA 2 - Every Resource you need](https://www.philschmid.de/llama-2), a compilation of relevant resources to learn about LLaMA 2 and how to get started quickly. + + + +- A [notebook](https://colab.research.google.com/drive/1PEQyJO1-f6j0S_XJ8DV50NkpzasXkrzd?usp=sharing) on how to fine-tune Llama 2 in Google Colab using QLoRA and 4-bit precision. 🌎 +- A [notebook](https://colab.research.google.com/drive/134o_cXcMe_lsvl15ZE_4Y75Kstepsntu?usp=sharing) on how to fine-tune the "Llama-v2-7b-guanaco" model with 4-bit QLoRA and generate Q&A datasets from PDFs. 🌎 + + + +- A [notebook](https://colab.research.google.com/drive/1ggaa2oRFphdBmqIjSEbnb_HGkcIRC2ZB?usp=sharing) on how to fine-tune the Llama 2 model with QLoRa, TRL, and Korean text classification dataset. 🌎🇰🇷 + +⚗️ Optimization +- [Fine-tune Llama 2 with DPO](https://huggingface.co/blog/dpo-trl), a guide to using the TRL library's DPO method to fine tune Llama 2 on a specific dataset. +- [Extended Guide: Instruction-tune Llama 2](https://www.philschmid.de/instruction-tune-llama-2), a guide to training Llama 2 to generate instructions from inputs, transforming the model from instruction-following to instruction-giving. +- A [notebook](https://colab.research.google.com/drive/1SYpgFpcmtIUzdE7pxqknrM4ArCASfkFQ?usp=sharing) on how to fine-tune the Llama 2 model on a personal computer using QLoRa and TRL. 🌎 + +⚡️ Inference +- A [notebook](https://colab.research.google.com/drive/1TC56ArKerXUpbgRy5vM3woRsbTEVNq7h?usp=sharing) on how to quantize the Llama 2 model using GPTQ from the AutoGPTQ library. 🌎 +- A [notebook](https://colab.research.google.com/drive/1X1z9Q6domMKl2CnEM0QGHNwidLfR4dW2?usp=sharing) on how to run the Llama 2 Chat Model with 4-bit quantization on a local computer or Google Colab. 🌎 + +🚀 Deploy +- [Fine-tune LLaMA 2 (7-70B) on Amazon SageMaker](https://www.philschmid.de/sagemaker-llama2-qlora), a complete guide from setup to QLoRA fine-tuning and deployment on Amazon SageMaker. +- [Deploy Llama 2 7B/13B/70B on Amazon SageMaker](https://www.philschmid.de/sagemaker-llama-llm), a guide on using Hugging Face's LLM DLC container for secure and scalable deployment. + + +## LlamaConfig + +[[autodoc]] LlamaConfig + + +## LlamaTokenizer + +[[autodoc]] LlamaTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## LlamaTokenizerFast + +[[autodoc]] LlamaTokenizerFast + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - update_post_processor + - save_vocabulary + +## LlamaModel + +[[autodoc]] LlamaModel + - forward + + +## LlamaForCausalLM + +[[autodoc]] LlamaForCausalLM + - forward + +## LlamaForSequenceClassification + +[[autodoc]] LlamaForSequenceClassification + - forward + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama3.md new file mode 100644 index 0000000000000000000000000000000000000000..0bb5e8160c909e9b1a5e9c99647a65eda2eacc9e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llama3.md @@ -0,0 +1,88 @@ + + +# Llama3 + +
+PyTorch +Flax +
+ +```py3 +import transformers +import torch + +model_id = "meta-llama/Meta-Llama-3-8B" + +pipeline = transformers.pipeline("text-generation", model=model_id, model_kwargs={"torch_dtype": torch.bfloat16}, device_map="auto") +pipeline("Hey how are you doing today?") +``` + +## Overview + +The Llama3 model was proposed in [Introducing Meta Llama 3: The most capable openly available LLM to date](https://ai.meta.com/blog/meta-llama-3/) by the meta AI team. + +The abstract from the blogpost is the following: + +*Today, we’re excited to share the first two models of the next generation of Llama, Meta Llama 3, available for broad use. This release features pretrained and instruction-fine-tuned language models with 8B and 70B parameters that can support a broad range of use cases. This next generation of Llama demonstrates state-of-the-art performance on a wide range of industry benchmarks and offers new capabilities, including improved reasoning. We believe these are the best open source models of their class, period. In support of our longstanding open approach, we’re putting Llama 3 in the hands of the community. We want to kickstart the next wave of innovation in AI across the stack—from applications to developer tools to evals to inference optimizations and more. We can’t wait to see what you build and look forward to your feedback.* + +Checkout all Llama3 model checkpoints [here](https://huggingface.co/models?search=llama3). +The original code of the authors can be found [here](https://github.com/meta-llama/llama3). + +## Usage tips + + + +The `Llama3` models were trained using `bfloat16`, but the original inference uses `float16`. The checkpoints uploaded on the Hub use `torch_dtype = 'float16'`, which will be +used by the `AutoModel` API to cast the checkpoints from `torch.float32` to `torch.float16`. + +The `dtype` of the online weights is mostly irrelevant unless you are using `torch_dtype="auto"` when initializing a model using `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`. The reason is that the model will first be downloaded ( using the `dtype` of the checkpoints online), then it will be casted to the default `dtype` of `torch` (becomes `torch.float32`), and finally, if there is a `torch_dtype` provided in the config, it will be used. + +Training the model in `float16` is not recommended and is known to produce `nan`; as such, the model should be trained in `bfloat16`. + + + +Tips: + +- Weights for the Llama3 models can be obtained by filling out [this form](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) +- The architecture is exactly the same as Llama2. +- The tokenizer is a BPE model based on [tiktoken](https://github.com/openai/tiktoken) (vs the one based on sentencepiece implementation for Llama2). The main difference that it ignores BPE merge rules when an input token is part of the vocab. This means that if no merge exist to produce `"hugging"`, instead of having the smallest units, like `["hug","ging"] form 2 tokens, if `"hugging"` is part of the vocab, it will be automatically returned as a token. +- The original model uses `pad_id = -1` which means that there is no padding token. We can't have the same logic, make sure to add a padding token using `tokenizer.add_special_tokens({"pad_token":""})` and resize the token embedding accordingly. You should also set the `model.config.pad_token_id`. The `embed_tokens` layer of the model is initialized with `self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.config.padding_idx)`, which makes sure that encoding the padding token will output zeros, so passing it when initializing is recommended. +- The original checkpoint can be converted using the [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py). The script can be called with the following (example) command: + + ```bash + python src/transformers/models/llama/convert_llama_weights_to_hf.py \ + --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path --llama_version 3 + ``` + +- After conversion, the model and tokenizer can be loaded via: + + ```python + from transformers import AutoModelForCausalLM, AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained("/output/path") + model = AutoModelForCausalLM.from_pretrained("/output/path") + ``` + + Note that executing the script requires enough CPU RAM to host the whole model in float16 precision (even if the biggest versions + come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). For the 75B model, it's thus 145GB of RAM needed. + +- When using Flash Attention 2 via `attn_implementation="flash_attention_2"`, don't pass `torch_dtype` to the `from_pretrained` class method and use Automatic Mixed-Precision training. When using `Trainer`, it is simply specifying either `fp16` or `bf16` to `True`. Otherwise, make sure you are using `torch.autocast`. This is required because the Flash Attention only support `fp16` and `bf16` data type. + +## Resources + +A ton of cool resources are already available on the documentation page of [Llama2](./llama2), inviting contributors to add new resources curated for Llama3 here! 🤗 diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava.md new file mode 100644 index 0000000000000000000000000000000000000000..79033ec5a189199796f8ef394829ba1e61d556f5 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava.md @@ -0,0 +1,262 @@ + + +# LLaVa + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +LLaVa is an open-source chatbot trained by fine-tuning LlamA/Vicuna on GPT-generated multimodal instruction-following data. It is an auto-regressive language model, based on the transformer architecture. In other words, it is an multi-modal version of LLMs fine-tuned for chat / instructions. + +The LLaVa model was proposed in [Visual Instruction Tuning](https://arxiv.org/abs/2304.08485) and improved in [Improved Baselines with Visual Instruction Tuning](https://arxiv.org/pdf/2310.03744) by Haotian Liu, Chunyuan Li, Yuheng Li and Yong Jae Lee. + +The abstract from the paper is the following: + +*Large multimodal models (LMM) have recently shown encouraging progress with visual instruction tuning. In this note, we show that the fully-connected vision-language cross-modal connector in LLaVA is surprisingly powerful and data-efficient. With simple modifications to LLaVA, namely, using CLIP-ViT-L-336px with an MLP projection and adding academic-task-oriented VQA data with simple response formatting prompts, we establish stronger baselines that achieve state-of-the-art across 11 benchmarks. Our final 13B checkpoint uses merely 1.2M publicly available data, and finishes full training in ∼1 day on a single 8-A100 node. We hope this can make state-of-the-art LMM research more accessible. Code and model will be publicly available* + + + + LLaVa architecture. Taken from the original paper. + +This model was contributed by [ArthurZ](https://huggingface.co/ArthurZ) and [ybelkada](https://huggingface.co/ybelkada). +The original code can be found [here](https://github.com/haotian-liu/LLaVA/tree/main/llava). + +## Usage tips + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to call `processor.tokenizer.padding_side = "left"` before generating. + +- Note the model has not been explicitly trained to process multiple images in the same prompt, although this is technically possible, you may experience inaccurate results. + + +> [!NOTE] +> LLaVA models after release v4.46 will raise warnings about adding `processor.patch_size = {{patch_size}}`, `processor.num_additional_image_tokens = {{num_additional_image_tokens}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. +Adding these attributes means that LLaVA will try to infer the number of image tokens required per image and expand the text with as many `` placeholders as there will be tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there will be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.vision_config.patch_size` or `model.config.vision_feature_select_strategy`. The `num_additional_image_tokens` should be `1` if the vision backbone adds a CLS token or `0` if nothing extra is added to the vision patches. + + +### Formatting Prompts with Chat Templates + +Each **checkpoint** is trained with a specific prompt format, depending on the underlying large language model backbone. To ensure correct formatting, use the processor’s `apply_chat_template` method. + +**Important:** +- You must construct a conversation history — passing a plain string won't work. +- Each message should be a dictionary with `"role"` and `"content"` keys. +- The `"content"` should be a list of dictionaries for different modalities like `"text"` and `"image"`. + + +Here’s an example of how to structure your input. +We will use [llava-hf/llava-1.5-7b-hf](https://huggingface.co/llava-hf/llava-1.5-7b-hf) and a conversation history of text and image. Each content field has to be a list of dicts, as follows: + + +```python +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf") + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What’s shown in this image?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "This image shows a red stop sign."},] + }, + { + + "role": "user", + "content": [ + {"type": "text", "text": "Describe the image in more details."}, + ], + }, +] + +text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) + +# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your images +print(text_prompt) +>>> "USER: \nUSER: Describe the image in more details. ASSISTANT:" +``` + +- If you want to construct a chat prompt yourself, below is a list of prompt formats accepted by each llava checkpoint: + +[llava-interleave models](https://huggingface.co/collections/llava-hf/llava-interleave-668e19a97da0036aad4a2f19) requires the following format: +```bash +"<|im_start|>user \nWhat is shown in this image?<|im_end|><|im_start|>assistant" +``` + +For multiple turns conversation: + +```bash +"<|im_start|>user \n<|im_end|><|im_start|>assistant <|im_end|><|im_start|>user \n<|im_end|><|im_start|>assistant " +``` + +[llava-1.5 models](https://huggingface.co/collections/llava-hf/llava-15-65f762d5b6941db5c2ba07e0) requires the following format: +```bash +"USER: \n ASSISTANT:" +``` + +For multiple turns conversation: + +```bash +"USER: \n ASSISTANT:
USER: ASSISTANT: USER: ASSISTANT:" +``` + +🚀 **Bonus:** If you're using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the **Usage Examples** below for more details on how to use it. + + +## Usage examples + +### Single input inference + + +```python +import torch +from transformers import AutoProcessor, LlavaForConditionalGeneration + +# Load the model in half-precision +model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16, device_map="auto") +processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf") + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt" +).to(model.device, torch.float16) + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=30) +processor.batch_decode(generate_ids, skip_special_tokens=True) +``` + + +### Batched inference + +LLaVa also supports batched inference. Here is how you can do it: + +```python +import torch +from transformers import AutoProcessor, LlavaForConditionalGeneration + +# Load the model in half-precision +model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf", torch_dtype=torch.float16, device_map="auto") +processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf") + + +# Prepare a batch of two prompts +conversation_1 = [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] + +conversation_2 = [ + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + [conversation_1, conversation_2], + add_generation_prompt=True, + tokenize=True, + return_dict=True, + padding=True, + return_tensors="pt" +).to(model.device, torch.float16) + + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=30) +processor.batch_decode(generate_ids, skip_special_tokens=True) +``` + + +## Note regarding reproducing original implementation + +In order to match the logits of the [original implementation](https://github.com/haotian-liu/LLaVA/tree/main), one needs to additionally specify `do_pad=True` when instantiating `LLavaImageProcessor`: + +```python +from transformers import LLavaImageProcessor + +image_processor = LLavaImageProcessor.from_pretrained("https://huggingface.co/llava-hf/llava-1.5-7b-hf", do_pad=True) +``` + +### Using Flash Attention 2 + +Flash Attention 2 is an even faster, optimized version of the previous optimization, please refer to the [Flash Attention 2 section of performance docs](https://huggingface.co/docs/transformers/perf_infer_gpu_one). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BEiT. + + + +- A [Google Colab demo](https://colab.research.google.com/drive/1qsl6cd2c8gGtEW1xV5io7S8NHh-Cp1TV?usp=sharing) on how to run Llava on a free-tier Google colab instance leveraging 4-bit inference. +- A [similar notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LLaVa/Inference_with_LLaVa_for_multimodal_generation.ipynb) showcasing batched inference. 🌎 + + +## LlavaConfig + +[[autodoc]] LlavaConfig + +## LlavaImageProcessor + +[[autodoc]] LlavaImageProcessor + - preprocess + +## LlavaImageProcessorFast + +[[autodoc]] LlavaImageProcessorFast + - preprocess + +## LlavaProcessor + +[[autodoc]] LlavaProcessor + +## LlavaForConditionalGeneration + +[[autodoc]] LlavaForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next.md new file mode 100644 index 0000000000000000000000000000000000000000..7d85ab8b6967755836dd767a21bc19c9c411648d --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next.md @@ -0,0 +1,321 @@ + + +# LLaVA-NeXT + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The LLaVA-NeXT model was proposed in [LLaVA-NeXT: Improved reasoning, OCR, and world knowledge](https://llava-vl.github.io/blog/2024-01-30-llava-next/) by Haotian Liu, Chunyuan Li, Yuheng Li, Bo Li, Yuanhan Zhang, Sheng Shen, Yong Jae Lee. LLaVa-NeXT (also called LLaVa-1.6) improves upon [LLaVa](llava) by increasing the input image resolution and training on an improved visual instruction tuning dataset to improve OCR and common sense reasoning. + +The introduction from the blog is the following: + +*In October 2023, we released LLaVA-1.5 with a simple and efficient design along with great performance on a benchmark suite of 12 datasets. It has since served as the foundation of many comprehensive studies of data, model, and capabilities of large multimodal models (LMM), and has enabled various new applications. + +Today, we are thrilled to present LLaVA-NeXT, with improved reasoning, OCR, and world knowledge. LLaVA-NeXT even exceeds Gemini Pro on several benchmarks. + +Compared with LLaVA-1.5, LLaVA-NeXT has several improvements: + +Increasing the input image resolution to 4x more pixels. This allows it to grasp more visual details. It supports three aspect ratios, up to 672x672, 336x1344, 1344x336 resolution. +Better visual reasoning and OCR capability with an improved visual instruction tuning data mixture. +Better visual conversation for more scenarios, covering different applications. Better world knowledge and logical reasoning. +Efficient deployment and inference with SGLang. +Along with performance improvements, LLaVA-NeXT maintains the minimalist design and data efficiency of LLaVA-1.5. It re-uses the pretrained connector of LLaVA-1.5, and still uses less than 1M visual instruction tuning samples. The largest 34B variant finishes training in ~1 day with 32 A100s.* + + + + LLaVa-NeXT incorporates a higher input resolution by encoding various patches of the input image. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/haotian-liu/LLaVA/tree/main). + +## Usage tips + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to call `processor.tokenizer.padding_side = "left"` before generating. + + + +- Llava-Next uses different number of patches for images and thus has to pad the inputs inside modeling code, aside from the padding done when processing the inputs. The default setting is "left-padding" if model is in `eval()` mode, otherwise "right-padding". + + + + +> [!NOTE] +> LLaVA models after release v4.46 will raise warnings about adding `processor.patch_size = {{patch_size}}`, `processor.num_additional_image_tokens = {{num_additional_image_tokens}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. +Adding these attributes means that LLaVA will try to infer the number of image tokens required per image and expand the text with as many `` placeholders as there will be tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there will be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.vision_config.patch_size` or `model.config.vision_feature_select_strategy`. The `num_additional_image_tokens` should be `1` if the vision backbone adds a CLS token or `0` if nothing extra is added to the vision patches. + + +### Formatting Prompts with Chat Templates + +Each **checkpoint** is trained with a specific prompt format, depending on the underlying large language model backbone. To ensure correct formatting, use the processor’s `apply_chat_template` method. + +**Important:** +- You must construct a conversation history — passing a plain string won't work. +- Each message should be a dictionary with `"role"` and `"content"` keys. +- The `"content"` should be a list of dictionaries for different modalities like `"text"` and `"image"`. + + +Here’s an example of how to structure your input. We will use [llava-v1.6-mistral-7b-hf](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf) and a conversation history of text and image. + +```python +from transformers import LlavaNextProcessor + +processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What’s shown in this image?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "This image shows a red stop sign."},] + }, + { + + "role": "user", + "content": [ + {"type": "text", "text": "Describe the image in more details."}, + ], + }, +] + +text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) + +# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your images +print(text_prompt) +>>> "[INST] \nWhat's shown in this image? [/INST] This image shows a red stop sign. [INST] Describe the image in more details. [/INST]" +``` + +- If you want to construct a chat prompt yourself, below is a list of possible formats +. +[llava-v1.6-mistral-7b-hf](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf) requires the following format: +```bash +"[INST] \nWhat is shown in this image? [/INST]" +``` + +[llava-v1.6-vicuna-7b-hf](https://huggingface.co/llava-hf/llava-v1.6-vicuna-7b-hf) and [llava-v1.6-vicuna-13b-hf](https://huggingface.co/llava-hf/llava-v1.6-vicuna-13b-hf) require the following format: +```bash +"A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions. USER: \nWhat is shown in this image? ASSISTANT:" +``` + +[llava-v1.6-34b-hf](https://huggingface.co/llava-hf/llava-v1.6-34b-hf) requires the following format: +```bash +"<|im_start|>system\nAnswer the questions.<|im_end|><|im_start|>user\n\nWhat is shown in this image?<|im_end|><|im_start|>assistant\n" +``` + +[llama3-llava-next-8b-hf](https://huggingface.co/llava-hf/llava-next-8b-hf) requires the following format: + +```bash +"<|start_header_id|>system<|end_header_id|>\n\nYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.<|eot_id|><|start_header_id|><|start_header_id|>user<|end_header_id|>\n\n\nWhat is shown in this image?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n" +``` + +[llava-next-72b-hf](https://huggingface.co/llava-hf/llava-next-72b-hf) and [llava-next-110b-hf](https://huggingface.co/llava-hf/llava-next-110b-hf) require the following format: + +```bash +"<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n\nWhat is shown in this image?<|im_end|>\n<|im_start|>assistant\n" +``` + +🚀 **Bonus:** If you're using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the **Usage Examples** below for more details on how to use it. + + + +## Usage example + +### Single image inference + +Here's how to load the model and perform inference in half-precision (`torch.float16`): + +```python +from transformers import LlavaNextProcessor, LlavaNextForConditionalGeneration +import torch +from PIL import Image +import requests + +processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + +model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", torch_dtype=torch.float16, low_cpu_mem_usage=True) +model.to("cuda:0") + +# prepare image and text prompt, using the appropriate prompt template +url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true" +image = Image.open(requests.get(url, stream=True).raw) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] +prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) +inputs = processor(image, prompt, return_tensors="pt").to("cuda:0") + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=100) + +print(processor.decode(output[0], skip_special_tokens=True)) +``` + +### Multi image inference + +LLaVa-Next can perform inference with multiple images as input, where images either belong to the same prompt or different prompts (in batched inference). Here is how you can do it: + +```python +import requests +from PIL import Image +import torch +from transformers import AutoProcessor, AutoModelForImageTextToText + +# Load the model in half-precision +model = AutoModelForImageTextToText.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", torch_dtype=torch.float16, device_map="auto") +processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + +# Get three different images +url = "https://www.ilankelman.org/stopsigns/australia.jpg" +image_stop = Image.open(requests.get(url, stream=True).raw) + +url = "http://images.cocodataset.org/val2017/000000039769.jpg" +image_cats = Image.open(requests.get(url, stream=True).raw) + +url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg" +image_snowman = Image.open(requests.get(url, stream=True).raw) + +# Prepare a batch of two prompts, where the first one is a multi-turn conversation and the second is not +conversation_1 = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": "There is a red stop sign in the image."}, + ], + }, + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What about this image? How many cats do you see?"}, + ], + }, +] + +conversation_2 = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] + +prompt_1 = processor.apply_chat_template(conversation_1, add_generation_prompt=True) +prompt_2 = processor.apply_chat_template(conversation_2, add_generation_prompt=True) +prompts = [prompt_1, prompt_2] + +# We can simply feed images in the order they have to be used in the text prompt +# Each "" token uses one image leaving the next for the subsequent "" tokens +inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, padding=True, return_tensors="pt").to(model.device) + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=30) +processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) +``` + +## Model optimization + +### Quantization using Bitsandbytes + +The model can be loaded in 8 or 4 bits, greatly reducing the memory requirements while maintaining the performance of the original model. First make sure to install bitsandbytes, `pip install bitsandbytes`, and to have access to a GPU/accelerator that is supported by the library. + + + +bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend). + +We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links. + + + +Simply change the snippet above with: + +```python +from transformers import AutoModelForImageTextToText, BitsAndBytesConfig + +# specify how to quantize the model +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, +) + +model = AutoModelForImageTextToText.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=quantization_config, device_map="auto") +``` + +### Use Flash-Attention 2 to further speed-up generation + +First make sure to install flash-attn. Refer to the [original repository of Flash Attention](https://github.com/Dao-AILab/flash-attention) regarding that package installation. Simply change the snippet above with: + +```python +from transformers import AutoModelForImageTextToText + +model = AutoModelForImageTextToText.from_pretrained( + model_id, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + use_flash_attention_2=True +).to(0) +``` + +## LlavaNextConfig + +[[autodoc]] LlavaNextConfig + +## LlavaNextImageProcessor + +[[autodoc]] LlavaNextImageProcessor + - preprocess + +## LlavaNextImageProcessorFast + +[[autodoc]] LlavaNextImageProcessorFast + - preprocess + +## LlavaNextProcessor + +[[autodoc]] LlavaNextProcessor + +## LlavaNextForConditionalGeneration + +[[autodoc]] LlavaNextForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next_video.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next_video.md new file mode 100644 index 0000000000000000000000000000000000000000..e435861cbe26f4c1176f11d2b85d071c5aea1454 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_next_video.md @@ -0,0 +1,268 @@ + + +# LLaVa-NeXT-Video + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The LLaVa-NeXT-Video model was proposed in [LLaVA-NeXT: A Strong Zero-shot Video Understanding Model +](https://llava-vl.github.io/blog/2024-04-30-llava-next-video/) by Yuanhan Zhang, Bo Li, Haotian Liu, Yong Jae Lee, Liangke Gui, Di Fu, Jiashi Feng, Ziwei Liu, Chunyuan Li. LLaVa-NeXT-Video improves upon [LLaVa-NeXT](llava_next) by fine-tuning on a mix if video and image dataset thus increasing the model's performance on videos. + +[LLaVA-NeXT](llava_next) surprisingly has strong performance in understanding video content in zero-shot fashion with the AnyRes technique that it uses. The AnyRes technique naturally represents a high-resolution image into multiple images. This technique is naturally generalizable to represent videos because videos can be considered as a set of frames (similar to a set of images in LLaVa-NeXT). The current version of LLaVA-NeXT makes use of AnyRes and trains with supervised fine-tuning (SFT) on top of LLaVA-Next on video data to achieves better video understanding capabilities.The model is a current SOTA among open-source models on [VideoMME bench](https://arxiv.org/abs/2405.21075). + + +The introduction from the blog is the following: + +On January 30, 2024, we released LLaVA-NeXT, an open-source Large Multimodal Model (LMM) that has been trained exclusively on text-image data. With the proposed AnyRes technique, it boosts capabilities in reasoning, OCR, and world knowledge, demonstrating remarkable performance across a spectrum of image-based multimodal understanding tasks, and even exceeding Gemini-Pro on several image benchmarks, e.g. MMMU and MathVista. + +**In today’s exploration, we delve into the performance of LLaVA-NeXT within the realm of video understanding tasks. We reveal that LLaVA-NeXT surprisingly has strong performance in understanding video content. The current version of LLaVA-NeXT for videos has several improvements: + +- Zero-shot video representation capabilities with AnyRes: The AnyRes technique naturally represents a high-resolution image into multiple images that a pre-trained VIT is able to digest, and forms them into a concatenated sequence. This technique is naturally generalizable to represent videos (consisting of multiple frames), allowing the image-only-trained LLaVA-Next model to perform surprisingly well on video tasks. Notably, this is the first time that LMMs show strong zero-shot modality transfer ability. +- Inference with length generalization improves on longer videos. The linear scaling technique enables length generalization, allowing LLaVA-NeXT to effectively handle long-video beyond the limitation of the "max_token_length" of the LLM. +- Strong video understanding ability. (1) LLaVA-Next-Image, which combines the above two techniques, yields superior zero-shot performance than open-source LMMs tuned on videos. (2) LLaVA-Next-Video, further supervised fine-tuning (SFT) LLaVA-Next-Image on video data, achieves better video understanding capabilities compared to LLaVA-Next-Image. (3) LLaVA-Next-Video-DPO, which aligns the model response with AI feedback using direct preference optimization (DPO), showing significant performance boost. +- Efficient deployment and inference with SGLang. It allows 5x faster inference on video tasks, allowing more scalable serving such as million-level video re-captioning. See instructions in our repo.** + + +This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/LLaVA-VL/LLaVA-NeXT/tree/inference). + +## Usage tips + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to call `processor.tokenizer.padding_side = "left"` before generating. + + + +- Llava-Next uses different number of patches for images and thus has to pad the inputs inside modeling code, aside from the padding done when processing the inputs. The default setting is "left-padding" if model is in `eval()` mode, otherwise "right-padding". + + + + +> [!NOTE] +> LLaVA models after release v4.46 will raise warnings about adding `processor.patch_size = {{patch_size}}`, `processor.num_additional_image_tokens = {{num_additional_image_tokens}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. +Adding these attributes means that LLaVA will try to infer the number of image tokens required per image and expand the text with as many `` placeholders as there will be tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there will be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.vision_config.patch_size` or `model.config.vision_feature_select_strategy`. The `num_additional_image_tokens` should be `1` if the vision backbone adds a CLS token or `0` if nothing extra is added to the vision patches. + + +### Formatting Prompts with Chat Templates + +Each **checkpoint** is trained with a specific prompt format, depending on the underlying large language model backbone. To ensure correct formatting, use the processor’s `apply_chat_template` method. + +**Important:** +- You must construct a conversation history — passing a plain string won't work. +- Each message should be a dictionary with `"role"` and `"content"` keys. +- The `"content"` should be a list of dictionaries for different modalities like `"text"` and `"image"`. + + +Here’s an example of how to structure your input. We will use [LLaVA-NeXT-Video-7B-hf](https://huggingface.co/llava-hf/LLaVA-NeXT-Video-7B-hf) and a conversation history of videos and images. + +```python +from transformers import LlavaNextVideoProcessor + +processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf") + +conversation = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions."}, + ], + }, + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s shown in this image?"}, + {"type": "image"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "This image shows a red stop sign."},] + }, + { + + "role": "user", + "content": [ + {"type": "text", "text": "Why is this video funny?"}, + {"type": "video"}, + ], + }, +] + +text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) + +# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your visuals +print(text_prompt) +``` + +🚀 **Bonus:** If you're using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the **Usage Examples** below for more details on how to use it. + + + +## Usage example + +### Single Media Mode + +The model can accept both images and videos as input. Here's an example code for inference in half-precision (`torch.float16`): + +```python +from huggingface_hub import hf_hub_download +import torch +from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor + +# Load the model in half-precision +model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", torch_dtype=torch.float16, device_map="auto") +processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf") + +# Load the video as an np.array, sampling uniformly 8 frames (can sample more for longer videos) +video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset") + +conversation = [ + { + + "role": "user", + "content": [ + {"type": "text", "text": "Why is this video funny?"}, + {"type": "video", "path": video_path}, + ], + }, +] + +inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") + +out = model.generate(**inputs, max_new_tokens=60) +processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True) +``` + + +### Mixed Media Mode + +The model can also generate from an interleaved image-video inputs. However note, that it was not trained in interleaved image-video setting which might affect the performance. Below is an example usage for mixed media input, add the following lines to the above code snippet: + +```python + +# Generate from image and video mixed inputs +conversation = [ + { + + "role": "user", + "content": [ + {"type": "text", "text": "How many cats are there in the image?"}, + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + ], + }, + { + + "role": "assistant", + "content": [{"type": "text", "text": "There are two cats"}], + }, + { + + "role": "user", + "content": [ + {"type": "text", "text": "Why is this video funny?"}, + {"type": "video", "path": video_path}, + ], + }, +] +inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, padding=True, return_tensors="pt") + +# Generate +generate_ids = model.generate(**inputs, max_length=50) +processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) + +``` + +## Model optimization + +### Quantization using Bitsandbytes for memory efficiency + +The model can be loaded in lower bits, significantly reducing memory burden while maintaining the performance of the original model. This allows for efficient deployment on resource-constrained cases. + +First, make sure to install bitsandbytes by running `pip install bitsandbytes` and to have access to a GPU/accelerator that is supported by the library. + + + +bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend). + +We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links. + + + +Then simply load the quantized model by adding [`BitsAndBytesConfig`](../main_classes/quantization#transformers.BitsAndBytesConfig) as shown below: + + +```python +from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor + +# specify how to quantize the model +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, +) + +model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", quantization_config=quantization_config, device_map="auto") +``` + + +### Flash-Attention 2 to speed-up generation + +Additionally, we can greatly speed-up model inference by using [Flash Attention](../perf_train_gpu_one#flash-attention-2), which is a faster implementation of the attention mechanism used inside the model. + +First, make sure to install the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Also, you should have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of the [flash attention repository](https://github.com/Dao-AILab/flash-attention). FlashAttention-2 can only be used when a model is loaded in `torch.float16` or `torch.bfloat16`. + +To load and run a model using Flash Attention-2, simply add `attn_implementation="flash_attention_2"` when loading the model as follows: + +```python +from transformers import LlavaNextVideoForConditionalGeneration + +model = LlavaNextVideoForConditionalGeneration.from_pretrained( + "llava-hf/LLaVA-NeXT-Video-7B-hf", + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", +).to(0) +``` + + + +## LlavaNextVideoConfig + +[[autodoc]] LlavaNextVideoConfig + +## LlavaNextVideoProcessor + +[[autodoc]] LlavaNextVideoProcessor + +## LlavaNextVideoImageProcessor + +[[autodoc]] LlavaNextVideoImageProcessor + +## LlavaNextVideoForConditionalGeneration + +[[autodoc]] LlavaNextVideoForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_onevision.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_onevision.md new file mode 100644 index 0000000000000000000000000000000000000000..77fe807d46d0083e0b1895d8b305d5f5073f87ee --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/llava_onevision.md @@ -0,0 +1,319 @@ + + +# LLaVA-OneVision + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The LLaVA-OneVision model was proposed in [LLaVA-OneVision: Easy Visual Task Transfer](https://arxiv.org/abs/2408.03326) by + + LLaVA-OneVision architecture. Taken from the original paper. + +Tips: + +- We advise users to use `padding_side="left"` when computing batched generation as it leads to more accurate results. Simply make sure to call `processor.tokenizer.padding_side = "left"` before generating. + + + +- Llava-OneVision uses different number of patches for images and thus has to pad the inputs inside modeling code, aside from the padding done when processing the inputs. The default setting is "left-padding" if model is in `eval()` mode, otherwise "right-padding". + + + + +### Formatting Prompts with Chat Templates + +Each **checkpoint** is trained with a specific prompt format, depending on the underlying large language model backbone. To ensure correct formatting, use the processor’s `apply_chat_template` method. + +**Important:** +- You must construct a conversation history — passing a plain string won't work. +- Each message should be a dictionary with `"role"` and `"content"` keys. +- The `"content"` should be a list of dictionaries for different modalities like `"text"` and `"image"`. + + +Here’s an example of how to structure your input. +We will use [llava-onevision-qwen2-7b-si-hf](https://huggingface.co/llava-hf/llava-onevision-qwen2-7b-si-hf) and a conversation history of text and image. Each content field has to be a list of dicts, as follows: + +```python +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-si-hf") + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "What’s shown in this image?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "This image shows a red stop sign."},] + }, + { + + "role": "user", + "content": [ + {"type": "text", "text": "Describe the image in more details."}, + ], + }, +] + +text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) + +# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your images +print(text_prompt) +'<|im_start|>user\nWhat is shown in this image?<|im_end|>\n<|im_start|>assistant\nPage showing the list of options.<|im_end|>' +``` + +🚀 **Bonus:** If you're using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the **Usage Examples** below for more details on how to use it. + + +This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/LLaVA-VL/LLaVA-NeXT/tree/main). + + +## Usage example + +### Single image inference + +Here's how to load the model and perform inference in half-precision (`torch.float16`): + +```python +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration +import torch + +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf") +model = LlavaOnevisionForConditionalGeneration.from_pretrained( + "llava-hf/llava-onevision-qwen2-7b-ov-hf", + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + device_map="cuda:0" +) + +# prepare image and text prompt, using the appropriate prompt template +url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true" +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "url": url}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] +inputs = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt") +inputs = inputs.to("cuda:0", torch.float16) + +# autoregressively complete prompt +output = model.generate(**inputs, max_new_tokens=100) +print(processor.decode(output[0], skip_special_tokens=True)) +'user\n\nWhat is shown in this image?\nassistant\nThe image shows a radar chart, also known as a spider chart or a star chart, which is used to compare multiple quantitative variables. Each axis represents a different variable, and the chart is filled with' +``` + +### Multi image inference + +LLaVa-OneVision can perform inference with multiple images as input, where images either belong to the same prompt or different prompts (in batched inference). For that you have to use checkpoints with an "ov" suffix. Here is how you can do it: + +```python +import requests +from PIL import Image +import torch +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +# Load the model in half-precision +model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype=torch.float16, device_map="auto") +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf") + +# Prepare a batch of two prompts, where the first one is a multi-turn conversation and the second is not +conversation_1 = [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": "There is a red stop sign in the image."}, + ], + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, + {"type": "text", "text": "What about this image? How many cats do you see?"}, + ], + }, +] + +conversation_2 = [ + { + "role": "user", + "content": [ + {"type": "image", "url": "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"}, + {"type": "text", "text": "What is shown in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + [conversation_1, conversation_2], + add_generation_prompt=True, + tokenize=True, + return_dict=True, + padding=True, + return_tensors="pt" +).to(model.device, torch.float16) + +# Generate +generate_ids = model.generate(**inputs, max_new_tokens=30) +processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False) +['user\n\nWhat is shown in this image?\nassistant\nThere is a red stop sign in the image.\nuser\n\nWhat about this image? How many cats do you see?\nassistant\ntwo', 'user\n\nWhat is shown in this image?\nassistant\n'] +``` + +### Video inference + +LLaVa-OneVision also can perform inference with videos as input, where video frames are treated as multiple images. Here is how you can do it: + +```python +from huggingface_hub import hf_hub_download +import torch +from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration + +# Load the model in half-precision +model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype=torch.float16, device_map="auto") +processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf") + +video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset") +conversation = [ + { + + "role": "user", + "content": [ + {"type": "video", "path": video_path}, + {"type": "text", "text": "Why is this video funny?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + num_frames=8 + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt" +).to(model.device, torch.float16) + +out = model.generate(**inputs, max_new_tokens=60) +processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True) +["user\n\nWhy is this video funny?\nassistant\nThe video appears to be humorous because it shows a young child, who is wearing glasses and holding a book, seemingly reading with a serious and focused expression. The child's glasses are a bit oversized for their face, which adds a comical touch, as it's a common trope to see children wearing"] +``` + +## Model optimization + +### Quantization using bitsandbytes + +The model can be loaded in 8 or 4 bits, greatly reducing the memory requirements while maintaining the performance of the original model. First make sure to install bitsandbytes, `pip install bitsandbytes` and make sure to have access to a GPU/accelerator that is supported by the library. + + + +bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend). + +We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links. + + + +Simply change the snippet above with: + +```python +from transformers import LlavaOnevisionForConditionalGeneration, BitsAndBytesConfig + +# specify how to quantize the model +quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, +) + +model = LlavaOnevisionForConditionalGeneration.from_pretrained(model_id, quantization_config=quantization_config, device_map="auto") +``` + +### Use Flash-Attention 2 to further speed-up generation + +First make sure to install flash-attn. Refer to the [original repository of Flash Attention](https://github.com/Dao-AILab/flash-attention) regarding that package installation. Simply change the snippet above with: + +```python +from transformers import LlavaOnevisionForConditionalGeneration + +model = LlavaOnevisionForConditionalGeneration.from_pretrained( + model_id, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + use_flash_attention_2=True +).to(0) +``` + + +## LlavaOnevisionConfig + +[[autodoc]] LlavaOnevisionConfig + +## LlavaOnevisionProcessor + +[[autodoc]] LlavaOnevisionProcessor + +## LlavaOnevisionImageProcessor + +[[autodoc]] LlavaOnevisionImageProcessor + +## LlavaOnevisionImageProcessorFast + +[[autodoc]] LlavaOnevisionImageProcessorFast + - preprocess + +## LlavaOnevisionVideoProcessor + +[[autodoc]] LlavaOnevisionVideoProcessor + +## LlavaOnevisionForConditionalGeneration + +[[autodoc]] LlavaOnevisionForConditionalGeneration + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longformer.md new file mode 100644 index 0000000000000000000000000000000000000000..d173a7eb32ec11abb0f777ee9439458886159980 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longformer.md @@ -0,0 +1,209 @@ + + +# Longformer + +
+PyTorch +TensorFlow +
+ +## Overview + +The Longformer model was presented in [Longformer: The Long-Document Transformer](https://arxiv.org/pdf/2004.05150.pdf) by Iz Beltagy, Matthew E. Peters, Arman Cohan. + +The abstract from the paper is the following: + +*Transformer-based models are unable to process long sequences due to their self-attention operation, which scales +quadratically with the sequence length. To address this limitation, we introduce the Longformer with an attention +mechanism that scales linearly with sequence length, making it easy to process documents of thousands of tokens or +longer. Longformer's attention mechanism is a drop-in replacement for the standard self-attention and combines a local +windowed attention with a task motivated global attention. Following prior work on long-sequence transformers, we +evaluate Longformer on character-level language modeling and achieve state-of-the-art results on text8 and enwik8. In +contrast to most prior work, we also pretrain Longformer and finetune it on a variety of downstream tasks. Our +pretrained Longformer consistently outperforms RoBERTa on long document tasks and sets new state-of-the-art results on +WikiHop and TriviaQA.* + +This model was contributed by [beltagy](https://huggingface.co/beltagy). The Authors' code can be found [here](https://github.com/allenai/longformer). + +## Usage tips + +- Since the Longformer is based on RoBERTa, it doesn't have `token_type_ids`. You don't need to indicate which + token belongs to which segment. Just separate your segments with the separation token `tokenizer.sep_token` (or + ``). +- A transformer model replacing the attention matrices by sparse matrices to go faster. Often, the local context (e.g., what are the two tokens left and right?) is enough to take action for a given token. Some preselected input tokens are still given global attention, but the attention matrix has way less parameters, resulting in a speed-up. See the local attention section for more information. + +## Longformer Self Attention + +Longformer self attention employs self attention on both a "local" context and a "global" context. Most tokens only +attend "locally" to each other meaning that each token attends to its \\(\frac{1}{2} w\\) previous tokens and +\\(\frac{1}{2} w\\) succeeding tokens with \\(w\\) being the window length as defined in +`config.attention_window`. Note that `config.attention_window` can be of type `List` to define a +different \\(w\\) for each layer. A selected few tokens attend "globally" to all other tokens, as it is +conventionally done for all tokens in `BertSelfAttention`. + +Note that "locally" and "globally" attending tokens are projected by different query, key and value matrices. Also note +that every "locally" attending token not only attends to tokens within its window \\(w\\), but also to all "globally" +attending tokens so that global attention is *symmetric*. + +The user can define which tokens attend "locally" and which tokens attend "globally" by setting the tensor +`global_attention_mask` at run-time appropriately. All Longformer models employ the following logic for +`global_attention_mask`: + +- 0: the token attends "locally", +- 1: the token attends "globally". + +For more information please also refer to [`~LongformerModel.forward`] method. + +Using Longformer self attention, the memory and time complexity of the query-key matmul operation, which usually +represents the memory and time bottleneck, can be reduced from \\(\mathcal{O}(n_s \times n_s)\\) to +\\(\mathcal{O}(n_s \times w)\\), with \\(n_s\\) being the sequence length and \\(w\\) being the average window +size. It is assumed that the number of "globally" attending tokens is insignificant as compared to the number of +"locally" attending tokens. + +For more information, please refer to the official [paper](https://arxiv.org/pdf/2004.05150.pdf). + + +## Training + +[`LongformerForMaskedLM`] is trained the exact same way [`RobertaForMaskedLM`] is +trained and should be used as follows: + +```python +input_ids = tokenizer.encode("This is a sentence from [MASK] training data", return_tensors="pt") +mlm_labels = tokenizer.encode("This is a sentence from the training data", return_tensors="pt") + +loss = model(input_ids, labels=input_ids, masked_lm_labels=mlm_labels)[0] +``` + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## LongformerConfig + +[[autodoc]] LongformerConfig + +## LongformerTokenizer + +[[autodoc]] LongformerTokenizer + +## LongformerTokenizerFast + +[[autodoc]] LongformerTokenizerFast + +## Longformer specific outputs + +[[autodoc]] models.longformer.modeling_longformer.LongformerBaseModelOutput + +[[autodoc]] models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling + +[[autodoc]] models.longformer.modeling_longformer.LongformerMaskedLMOutput + +[[autodoc]] models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput + +[[autodoc]] models.longformer.modeling_longformer.LongformerSequenceClassifierOutput + +[[autodoc]] models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput + +[[autodoc]] models.longformer.modeling_longformer.LongformerTokenClassifierOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerBaseModelOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerBaseModelOutputWithPooling + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerMaskedLMOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerQuestionAnsweringModelOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerSequenceClassifierOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerMultipleChoiceModelOutput + +[[autodoc]] models.longformer.modeling_tf_longformer.TFLongformerTokenClassifierOutput + + + + +## LongformerModel + +[[autodoc]] LongformerModel + - forward + +## LongformerForMaskedLM + +[[autodoc]] LongformerForMaskedLM + - forward + +## LongformerForSequenceClassification + +[[autodoc]] LongformerForSequenceClassification + - forward + +## LongformerForMultipleChoice + +[[autodoc]] LongformerForMultipleChoice + - forward + +## LongformerForTokenClassification + +[[autodoc]] LongformerForTokenClassification + - forward + +## LongformerForQuestionAnswering + +[[autodoc]] LongformerForQuestionAnswering + - forward + + + + +## TFLongformerModel + +[[autodoc]] TFLongformerModel + - call + +## TFLongformerForMaskedLM + +[[autodoc]] TFLongformerForMaskedLM + - call + +## TFLongformerForQuestionAnswering + +[[autodoc]] TFLongformerForQuestionAnswering + - call + +## TFLongformerForSequenceClassification + +[[autodoc]] TFLongformerForSequenceClassification + - call + +## TFLongformerForTokenClassification + +[[autodoc]] TFLongformerForTokenClassification + - call + +## TFLongformerForMultipleChoice + +[[autodoc]] TFLongformerForMultipleChoice + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longt5.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longt5.md new file mode 100644 index 0000000000000000000000000000000000000000..85a869f3c5948934ea42ba66339370ae62964b15 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/longt5.md @@ -0,0 +1,145 @@ + + +# LongT5 + +
+PyTorch +Flax +
+ +## Overview + +The LongT5 model was proposed in [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) +by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung and Yinfei Yang. It's an +encoder-decoder transformer pre-trained in a text-to-text denoising generative setting. LongT5 model is an extension of +T5 model, and it enables using one of the two different efficient attention mechanisms - (1) Local attention, or (2) +Transient-Global attention. + + +The abstract from the paper is the following: + +*Recent work has shown that either (1) increasing the input length or (2) increasing model size can improve the +performance of Transformer-based neural models. In this paper, we present a new model, called LongT5, with which we +explore the effects of scaling both the input length and model size at the same time. Specifically, we integrated +attention ideas from long-input transformers (ETC), and adopted pre-training strategies from summarization pre-training +(PEGASUS) into the scalable T5 architecture. The result is a new attention mechanism we call {\em Transient Global} +(TGlobal), which mimics ETC's local/global attention mechanism, but without requiring additional side-inputs. We are +able to achieve state-of-the-art results on several summarization tasks and outperform the original T5 models on +question answering tasks.* + +This model was contributed by [stancld](https://huggingface.co/stancld). +The original code can be found [here](https://github.com/google-research/longt5). + +## Usage tips + +- [`LongT5ForConditionalGeneration`] is an extension of [`T5ForConditionalGeneration`] exchanging the traditional +encoder *self-attention* layer with efficient either *local* attention or *transient-global* (*tglobal*) attention. +- Unlike the T5 model, LongT5 does not use a task prefix. Furthermore, it uses a different pre-training objective +inspired by the pre-training of [`PegasusForConditionalGeneration`]. +- LongT5 model is designed to work efficiently and very well on long-range *sequence-to-sequence* tasks where the +input sequence exceeds commonly used 512 tokens. It is capable of handling input sequences of a length up to 16,384 tokens. +- For *Local Attention*, the sparse sliding-window local attention operation allows a given token to attend only `r` +tokens to the left and right of it (with `r=127` by default). *Local Attention* does not introduce any new parameters +to the model. The complexity of the mechanism is linear in input sequence length `l`: `O(l*r)`. +- *Transient Global Attention* is an extension of the *Local Attention*. It, furthermore, allows each input token to +interact with all other tokens in the layer. This is achieved via splitting an input sequence into blocks of a fixed +length `k` (with a default `k=16`). Then, a global token for such a block is obtained via summing and normalizing the embeddings of every token +in the block. Thanks to this, the attention allows each token to attend to both nearby tokens like in Local attention, and +also every global token like in the case of standard global attention (*transient* represents the fact the global tokens +are constructed dynamically within each attention operation). As a consequence, *TGlobal* attention introduces +a few new parameters -- global relative position biases and a layer normalization for global token's embedding. +The complexity of this mechanism is `O(l(r + l/k))`. +- An example showing how to evaluate a fine-tuned LongT5 model on the [pubmed dataset](https://huggingface.co/datasets/scientific_papers) is below. + +```python +>>> import evaluate +>>> from datasets import load_dataset +>>> from transformers import AutoTokenizer, LongT5ForConditionalGeneration + +>>> dataset = load_dataset("scientific_papers", "pubmed", split="validation") +>>> model = ( +... LongT5ForConditionalGeneration.from_pretrained("Stancld/longt5-tglobal-large-16384-pubmed-3k_steps") +... .to("cuda") +... .half() +... ) +>>> tokenizer = AutoTokenizer.from_pretrained("Stancld/longt5-tglobal-large-16384-pubmed-3k_steps") + + +>>> def generate_answers(batch): +... inputs_dict = tokenizer( +... batch["article"], max_length=16384, padding="max_length", truncation=True, return_tensors="pt" +... ) +... input_ids = inputs_dict.input_ids.to("cuda") +... attention_mask = inputs_dict.attention_mask.to("cuda") +... output_ids = model.generate(input_ids, attention_mask=attention_mask, max_length=512, num_beams=2) +... batch["predicted_abstract"] = tokenizer.batch_decode(output_ids, skip_special_tokens=True) +... return batch + + +>>> result = dataset.map(generate_answer, batched=True, batch_size=2) +>>> rouge = evaluate.load("rouge") +>>> rouge.compute(predictions=result["predicted_abstract"], references=result["abstract"]) +``` + + +## Resources + +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## LongT5Config + +[[autodoc]] LongT5Config + + + + +## LongT5Model + +[[autodoc]] LongT5Model + - forward + +## LongT5ForConditionalGeneration + +[[autodoc]] LongT5ForConditionalGeneration + - forward + +## LongT5EncoderModel + +[[autodoc]] LongT5EncoderModel + - forward + + + + +## FlaxLongT5Model + +[[autodoc]] FlaxLongT5Model + - __call__ + - encode + - decode + +## FlaxLongT5ForConditionalGeneration + +[[autodoc]] FlaxLongT5ForConditionalGeneration + - __call__ + - encode + - decode + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/luke.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/luke.md new file mode 100644 index 0000000000000000000000000000000000000000..be4d5946dfcf2950afbfdb1e88a506c9383c9a5f --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/luke.md @@ -0,0 +1,185 @@ + + +# LUKE + +
+PyTorch +
+ +## Overview + +The LUKE model was proposed in [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda and Yuji Matsumoto. +It is based on RoBERTa and adds entity embeddings as well as an entity-aware self-attention mechanism, which helps +improve performance on various downstream tasks involving reasoning about entities such as named entity recognition, +extractive and cloze-style question answering, entity typing, and relation classification. + +The abstract from the paper is the following: + +*Entity representations are useful in natural language tasks involving entities. In this paper, we propose new +pretrained contextualized representations of words and entities based on the bidirectional transformer. The proposed +model treats words and entities in a given text as independent tokens, and outputs contextualized representations of +them. Our model is trained using a new pretraining task based on the masked language model of BERT. The task involves +predicting randomly masked words and entities in a large entity-annotated corpus retrieved from Wikipedia. We also +propose an entity-aware self-attention mechanism that is an extension of the self-attention mechanism of the +transformer, and considers the types of tokens (words or entities) when computing attention scores. The proposed model +achieves impressive empirical performance on a wide range of entity-related tasks. In particular, it obtains +state-of-the-art results on five well-known datasets: Open Entity (entity typing), TACRED (relation classification), +CoNLL-2003 (named entity recognition), ReCoRD (cloze-style question answering), and SQuAD 1.1 (extractive question +answering).* + +This model was contributed by [ikuyamada](https://huggingface.co/ikuyamada) and [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/studio-ousia/luke). + +## Usage tips + +- This implementation is the same as [`RobertaModel`] with the addition of entity embeddings as well + as an entity-aware self-attention mechanism, which improves performance on tasks involving reasoning about entities. +- LUKE treats entities as input tokens; therefore, it takes `entity_ids`, `entity_attention_mask`, + `entity_token_type_ids` and `entity_position_ids` as extra input. You can obtain those using + [`LukeTokenizer`]. +- [`LukeTokenizer`] takes `entities` and `entity_spans` (character-based start and end + positions of the entities in the input text) as extra input. `entities` typically consist of [MASK] entities or + Wikipedia entities. The brief description when inputting these entities are as follows: + + - *Inputting [MASK] entities to compute entity representations*: The [MASK] entity is used to mask entities to be + predicted during pretraining. When LUKE receives the [MASK] entity, it tries to predict the original entity by + gathering the information about the entity from the input text. Therefore, the [MASK] entity can be used to address + downstream tasks requiring the information of entities in text such as entity typing, relation classification, and + named entity recognition. + - *Inputting Wikipedia entities to compute knowledge-enhanced token representations*: LUKE learns rich information + (or knowledge) about Wikipedia entities during pretraining and stores the information in its entity embedding. By + using Wikipedia entities as input tokens, LUKE outputs token representations enriched by the information stored in + the embeddings of these entities. This is particularly effective for tasks requiring real-world knowledge, such as + question answering. + +- There are three head models for the former use case: + + - [`LukeForEntityClassification`], for tasks to classify a single entity in an input text such as + entity typing, e.g. the [Open Entity dataset](https://www.cs.utexas.edu/~eunsol/html_pages/open_entity.html). + This model places a linear head on top of the output entity representation. + - [`LukeForEntityPairClassification`], for tasks to classify the relationship between two entities + such as relation classification, e.g. the [TACRED dataset](https://nlp.stanford.edu/projects/tacred/). This + model places a linear head on top of the concatenated output representation of the pair of given entities. + - [`LukeForEntitySpanClassification`], for tasks to classify the sequence of entity spans, such as + named entity recognition (NER). This model places a linear head on top of the output entity representations. You + can address NER using this model by inputting all possible entity spans in the text to the model. + + [`LukeTokenizer`] has a `task` argument, which enables you to easily create an input to these + head models by specifying `task="entity_classification"`, `task="entity_pair_classification"`, or + `task="entity_span_classification"`. Please refer to the example code of each head models. + +Usage example: + +```python +>>> from transformers import LukeTokenizer, LukeModel, LukeForEntityPairClassification + +>>> model = LukeModel.from_pretrained("studio-ousia/luke-base") +>>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base") +# Example 1: Computing the contextualized entity representation corresponding to the entity mention "Beyoncé" + +>>> text = "Beyoncé lives in Los Angeles." +>>> entity_spans = [(0, 7)] # character-based entity span corresponding to "Beyoncé" +>>> inputs = tokenizer(text, entity_spans=entity_spans, add_prefix_space=True, return_tensors="pt") +>>> outputs = model(**inputs) +>>> word_last_hidden_state = outputs.last_hidden_state +>>> entity_last_hidden_state = outputs.entity_last_hidden_state +# Example 2: Inputting Wikipedia entities to obtain enriched contextualized representations + +>>> entities = [ +... "Beyoncé", +... "Los Angeles", +... ] # Wikipedia entity titles corresponding to the entity mentions "Beyoncé" and "Los Angeles" +>>> entity_spans = [(0, 7), (17, 28)] # character-based entity spans corresponding to "Beyoncé" and "Los Angeles" +>>> inputs = tokenizer(text, entities=entities, entity_spans=entity_spans, add_prefix_space=True, return_tensors="pt") +>>> outputs = model(**inputs) +>>> word_last_hidden_state = outputs.last_hidden_state +>>> entity_last_hidden_state = outputs.entity_last_hidden_state +# Example 3: Classifying the relationship between two entities using LukeForEntityPairClassification head model + +>>> model = LukeForEntityPairClassification.from_pretrained("studio-ousia/luke-large-finetuned-tacred") +>>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-large-finetuned-tacred") +>>> entity_spans = [(0, 7), (17, 28)] # character-based entity spans corresponding to "Beyoncé" and "Los Angeles" +>>> inputs = tokenizer(text, entity_spans=entity_spans, return_tensors="pt") +>>> outputs = model(**inputs) +>>> logits = outputs.logits +>>> predicted_class_idx = int(logits[0].argmax()) +>>> print("Predicted class:", model.config.id2label[predicted_class_idx]) +``` + +## Resources + +- [A demo notebook on how to fine-tune [`LukeForEntityPairClassification`] for relation classification](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/LUKE) +- [Notebooks showcasing how you to reproduce the results as reported in the paper with the HuggingFace implementation of LUKE](https://github.com/studio-ousia/luke/tree/master/notebooks) +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## LukeConfig + +[[autodoc]] LukeConfig + +## LukeTokenizer + +[[autodoc]] LukeTokenizer + - __call__ + - save_vocabulary + +## LukeModel + +[[autodoc]] LukeModel + - forward + +## LukeForMaskedLM + +[[autodoc]] LukeForMaskedLM + - forward + +## LukeForEntityClassification + +[[autodoc]] LukeForEntityClassification + - forward + +## LukeForEntityPairClassification + +[[autodoc]] LukeForEntityPairClassification + - forward + +## LukeForEntitySpanClassification + +[[autodoc]] LukeForEntitySpanClassification + - forward + +## LukeForSequenceClassification + +[[autodoc]] LukeForSequenceClassification + - forward + +## LukeForMultipleChoice + +[[autodoc]] LukeForMultipleChoice + - forward + +## LukeForTokenClassification + +[[autodoc]] LukeForTokenClassification + - forward + +## LukeForQuestionAnswering + +[[autodoc]] LukeForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lxmert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lxmert.md new file mode 100644 index 0000000000000000000000000000000000000000..a0f686efc35d0437c943d11bfb9f98e0aef680c9 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/lxmert.md @@ -0,0 +1,123 @@ + + +# LXMERT + +
+PyTorch +TensorFlow +
+ +## Overview + +The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from Transformers](https://arxiv.org/abs/1908.07490) by Hao Tan & Mohit Bansal. It is a series of bidirectional transformer encoders +(one for the vision modality, one for the language modality, and then one to fuse both modalities) pretrained using a +combination of masked language modeling, visual-language text alignment, ROI-feature regression, masked +visual-attribute modeling, masked visual-object modeling, and visual-question answering objectives. The pretraining +consists of multiple multi-modal datasets: MSCOCO, Visual-Genome + Visual-Genome Question Answering, VQA 2.0, and GQA. + +The abstract from the paper is the following: + +*Vision-and-language reasoning requires an understanding of visual concepts, language semantics, and, most importantly, +the alignment and relationships between these two modalities. We thus propose the LXMERT (Learning Cross-Modality +Encoder Representations from Transformers) framework to learn these vision-and-language connections. In LXMERT, we +build a large-scale Transformer model that consists of three encoders: an object relationship encoder, a language +encoder, and a cross-modality encoder. Next, to endow our model with the capability of connecting vision and language +semantics, we pre-train the model with large amounts of image-and-sentence pairs, via five diverse representative +pretraining tasks: masked language modeling, masked object prediction (feature regression and label classification), +cross-modality matching, and image question answering. These tasks help in learning both intra-modality and +cross-modality relationships. After fine-tuning from our pretrained parameters, our model achieves the state-of-the-art +results on two visual question answering datasets (i.e., VQA and GQA). We also show the generalizability of our +pretrained cross-modality model by adapting it to a challenging visual-reasoning task, NLVR, and improve the previous +best result by 22% absolute (54% to 76%). Lastly, we demonstrate detailed ablation studies to prove that both our novel +model components and pretraining strategies significantly contribute to our strong results; and also present several +attention visualizations for the different encoders* + +This model was contributed by [eltoto1219](https://huggingface.co/eltoto1219). The original code can be found [here](https://github.com/airsplay/lxmert). + +## Usage tips + +- Bounding boxes are not necessary to be used in the visual feature embeddings, any kind of visual-spacial features + will work. +- Both the language hidden states and the visual hidden states that LXMERT outputs are passed through the + cross-modality layer, so they contain information from both modalities. To access a modality that only attends to + itself, select the vision/language hidden states from the first input in the tuple. +- The bidirectional cross-modality encoder attention only returns attention values when the language modality is used + as the input and the vision modality is used as the context vector. Further, while the cross-modality encoder + contains self-attention for each respective modality and cross-attention, only the cross attention is returned and + both self attention outputs are disregarded. + +## Resources + +- [Question answering task guide](../tasks/question_answering) + +## LxmertConfig + +[[autodoc]] LxmertConfig + +## LxmertTokenizer + +[[autodoc]] LxmertTokenizer + +## LxmertTokenizerFast + +[[autodoc]] LxmertTokenizerFast + +## Lxmert specific outputs + +[[autodoc]] models.lxmert.modeling_lxmert.LxmertModelOutput + +[[autodoc]] models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput + +[[autodoc]] models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput + +[[autodoc]] models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput + +[[autodoc]] models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput + + + + +## LxmertModel + +[[autodoc]] LxmertModel + - forward + +## LxmertForPreTraining + +[[autodoc]] LxmertForPreTraining + - forward + +## LxmertForQuestionAnswering + +[[autodoc]] LxmertForQuestionAnswering + - forward + + + + +## TFLxmertModel + +[[autodoc]] TFLxmertModel + - call + +## TFLxmertForPreTraining + +[[autodoc]] TFLxmertForPreTraining + - call + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/m2m_100.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/m2m_100.md new file mode 100644 index 0000000000000000000000000000000000000000..f4f2955bb046f310195a2b50c81058dad8a99651 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/m2m_100.md @@ -0,0 +1,189 @@ + + +# M2M100 + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The M2M100 model was proposed in [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, +Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy +Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin. + +The abstract from the paper is the following: + +*Existing work in translation demonstrated the potential of massively multilingual machine translation by training a +single model able to translate between any pair of languages. However, much of this work is English-Centric by training +only on data which was translated from or to English. While this is supported by large sources of training data, it +does not reflect translation needs worldwide. In this work, we create a true Many-to-Many multilingual translation +model that can translate directly between any pair of 100 languages. We build and open source a training dataset that +covers thousands of language directions with supervised data, created through large-scale mining. Then, we explore how +to effectively increase model capacity through a combination of dense scaling and language-specific sparse parameters +to create high quality models. Our focus on non-English-Centric models brings gains of more than 10 BLEU when directly +translating between non-English directions while performing competitively to the best single systems of WMT. We +open-source our scripts so that others may reproduce the data, evaluation, and final M2M-100 model.* + +This model was contributed by [valhalla](https://huggingface.co/valhalla). + + +## Usage tips and examples + +M2M100 is a multilingual encoder-decoder (seq-to-seq) model primarily intended for translation tasks. As the model is +multilingual it expects the sequences in a certain format: A special language id token is used as prefix in both the +source and target text. The source text format is `[lang_code] X [eos]`, where `lang_code` is source language +id for source text and target language id for target text, with `X` being the source or target text. + +The [`M2M100Tokenizer`] depends on `sentencepiece` so be sure to install it before running the +examples. To install `sentencepiece` run `pip install sentencepiece`. + +**Supervised Training** + +```python +from transformers import M2M100Config, M2M100ForConditionalGeneration, M2M100Tokenizer + +model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M") +tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="en", tgt_lang="fr") + +src_text = "Life is like a box of chocolates." +tgt_text = "La vie est comme une boîte de chocolat." + +model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt") + +loss = model(**model_inputs).loss # forward pass +``` + +**Generation** + +M2M100 uses the `eos_token_id` as the `decoder_start_token_id` for generation with the target language id +being forced as the first generated token. To force the target language id as the first generated token, pass the +*forced_bos_token_id* parameter to the *generate* method. The following example shows how to translate between +Hindi to French and Chinese to English using the *facebook/m2m100_418M* checkpoint. + +```python +>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer + +>>> hi_text = "जीवन एक चॉकलेट बॉक्स की तरह है।" +>>> chinese_text = "生活就像一盒巧克力。" + +>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M") +>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M") + +>>> # translate Hindi to French +>>> tokenizer.src_lang = "hi" +>>> encoded_hi = tokenizer(hi_text, return_tensors="pt") +>>> generated_tokens = model.generate(**encoded_hi, forced_bos_token_id=tokenizer.get_lang_id("fr")) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +"La vie est comme une boîte de chocolat." + +>>> # translate Chinese to English +>>> tokenizer.src_lang = "zh" +>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt") +>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en")) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +"Life is like a box of chocolate." +``` + +## Resources + +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## M2M100Config + +[[autodoc]] M2M100Config + +## M2M100Tokenizer + +[[autodoc]] M2M100Tokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## M2M100Model + +[[autodoc]] M2M100Model + - forward + +## M2M100ForConditionalGeneration + +[[autodoc]] M2M100ForConditionalGeneration + - forward + +## Using Flash Attention 2 + +Flash Attention 2 is a faster, optimized version of the attention scores computation which relies on `cuda` kernels. + +### Installation + +First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). + +Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: + +```bash +pip install -U flash-attn --no-build-isolation +``` + +### Usage + +To load a model using Flash Attention 2, we can pass the argument `attn_implementation="flash_attention_2"` to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). You can use either `torch.float16` or `torch.bfloat16` precision. + +```python +>>> import torch +>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer + +>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to("cuda").eval() +>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M") + +>>> # translate Hindi to French +>>> hi_text = "जीवन एक चॉकलेट बॉक्स की तरह है।" +>>> tokenizer.src_lang = "hi" +>>> encoded_hi = tokenizer(hi_text, return_tensors="pt").to("cuda") +>>> generated_tokens = model.generate(**encoded_hi, forced_bos_token_id=tokenizer.get_lang_id("fr")) +>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +"La vie est comme une boîte de chocolat." +``` + +### Expected speedups + +Below is an expected speedup diagram that compares pure inference time between the native implementation and the Flash Attention 2. + +
+ +
+ +## Using Scaled Dot Product Attention (SDPA) +PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function +encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the +[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) +or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) +page for more information. + +SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set +`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. + +```python +from transformers import M2M100ForConditionalGeneration +model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M", torch_dtype=torch.float16, attn_implementation="sdpa") +... +``` + +For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/madlad-400.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/madlad-400.md new file mode 100644 index 0000000000000000000000000000000000000000..db6abc38eaf1fba33945f85815a0c8dd692350da --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/madlad-400.md @@ -0,0 +1,75 @@ + + +# MADLAD-400 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +MADLAD-400 models were released in the paper [MADLAD-400: A Multilingual And Document-Level Large Audited Dataset](MADLAD-400: A Multilingual And Document-Level Large Audited Dataset). + +The abstract from the paper is the following: + +*We introduce MADLAD-400, a manually audited, general domain 3T token monolingual dataset based on CommonCrawl, spanning 419 languages. We discuss +the limitations revealed by self-auditing MADLAD-400, and the role data auditing +had in the dataset creation process. We then train and release a 10.7B-parameter +multilingual machine translation model on 250 billion tokens covering over 450 +languages using publicly available data, and find that it is competitive with models +that are significantly larger, and report the results on different domains. In addition, we train a 8B-parameter language model, and assess the results on few-shot +translation. We make the baseline models 1 +available to the research community.* + +This model was added by [Juarez Bochi](https://huggingface.co/jbochi). The original checkpoints can be found [here](https://github.com/google-research/google-research/tree/master/madlad_400). + +This is a machine translation model that supports many low-resource languages, and that is competitive with models that are significantly larger. + +One can directly use MADLAD-400 weights without finetuning the model: + +```python +>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/madlad400-3b-mt") +>>> tokenizer = AutoTokenizer.from_pretrained("google/madlad400-3b-mt") + +>>> inputs = tokenizer("<2pt> I love pizza!", return_tensors="pt") +>>> outputs = model.generate(**inputs) +>>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) +['Eu amo pizza!'] +``` + +Google has released the following variants: + +- [google/madlad400-3b-mt](https://huggingface.co/google/madlad400-3b-mt) + +- [google/madlad400-7b-mt](https://huggingface.co/google/madlad400-7b-mt) + +- [google/madlad400-7b-mt-bt](https://huggingface.co/google/madlad400-7b-mt-bt) + +- [google/madlad400-10b-mt](https://huggingface.co/google/madlad400-10b-mt) + +The original checkpoints can be found [here](https://github.com/google-research/google-research/tree/master/madlad_400). + + + +Refer to [T5's documentation page](t5) for all API references, code examples, and notebooks. For more details regarding training and evaluation of the MADLAD-400, refer to the model card. + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba.md new file mode 100644 index 0000000000000000000000000000000000000000..d5c0612b1ebe15de3001091f3d6459a08eebf03b --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba.md @@ -0,0 +1,108 @@ + + +# Mamba + +
+PyTorch +
+ +## Overview + +The Mamba model was proposed in [Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://arxiv.org/abs/2312.00752) by Albert Gu and Tri Dao. + +This model is a new paradigm architecture based on `state-space-models`. You can read more about the intuition behind these [here](https://srush.github.io/annotated-s4/). + +The abstract from the paper is the following: + +*Foundation models, now powering most of the exciting applications in deep learning, are almost universally based on the Transformer architecture and its core attention module. Many subquadratic-time architectures such as linear attention, gated convolution and recurrent models, and structured state space models (SSMs) have been developed to address Transformers' computational inefficiency on long sequences, but they have not performed as well as attention on important modalities such as language. We identify that a key weakness of such models is their inability to perform content-based reasoning, and make several improvements. First, simply letting the SSM parameters be functions of the input addresses their weakness with discrete modalities, allowing the model to selectively propagate or forget information along the sequence length dimension depending on the current token. Second, even though this change prevents the use of efficient convolutions, we design a hardware-aware parallel algorithm in recurrent mode. We integrate these selective SSMs into a simplified end-to-end neural network architecture without attention or even MLP blocks (Mamba). Mamba enjoys fast inference (5× higher throughput than Transformers) and linear scaling in sequence length, and its performance improves on real data up to million-length sequences. As a general sequence model backbone, Mamba achieves state-of-the-art performance across several modalities such as language, audio, and genomics. On language modeling, our Mamba-3B model outperforms Transformers of the same size and matches Transformers twice its size, both in pretraining and downstream evaluation.* + +Tips: + +- Mamba is a new `state space model` architecture that rivals the classic Transformers. It is based on the line of progress on structured state space models, with an efficient hardware-aware design and implementation in the spirit of [FlashAttention](https://github.com/Dao-AILab/flash-attention). +- Mamba stacks `mixer` layers, which are the equivalent of `Attention` layers. The core logic of `mamba` is held in the `MambaMixer` class. +- Two implementations cohabit: one is optimized and uses fast cuda kernels, while the other one is naive but can run on any device! +- The current implementation leverages the original cuda kernels: the equivalent of flash attention for Mamba are hosted in the [`mamba-ssm`](https://github.com/state-spaces/mamba) and the [`causal_conv1d`](https://github.com/Dao-AILab/causal-conv1d) repositories. Make sure to install them if your hardware supports them! +- Contributions to make the naive path faster are welcome 🤗 + +This model was contributed by [ArthurZ](https://huggingface.co/ArthurZ). +The original code can be found [here](https://github.com/state-spaces/mamba). + +# Usage + +### A simple generation example: +```python +from transformers import MambaConfig, MambaForCausalLM, AutoTokenizer +import torch + +tokenizer = AutoTokenizer.from_pretrained("state-spaces/mamba-130m-hf") +model = MambaForCausalLM.from_pretrained("state-spaces/mamba-130m-hf") +input_ids = tokenizer("Hey how are you doing?", return_tensors= "pt")["input_ids"] + +out = model.generate(input_ids, max_new_tokens=10) +print(tokenizer.batch_decode(out)) +``` + +### Peft finetuning +The slow version is not very stable for training, and the fast one needs `float32`! + +```python +from datasets import load_dataset +from trl import SFTTrainer +from peft import LoraConfig +from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments +model_id = "state-spaces/mamba-130m-hf" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id) +dataset = load_dataset("Abirate/english_quotes", split="train") +training_args = TrainingArguments( + output_dir="./results", + num_train_epochs=3, + per_device_train_batch_size=4, + logging_dir='./logs', + logging_steps=10, + learning_rate=2e-3 +) +lora_config = LoraConfig( + r=8, + target_modules=["x_proj", "embeddings", "in_proj", "out_proj"], + task_type="CAUSAL_LM", + bias="none" +) +trainer = SFTTrainer( + model=model, + processing_class=tokenizer, + args=training_args, + peft_config=lora_config, + train_dataset=dataset, + dataset_text_field="quote", +) +trainer.train() +``` + +## MambaConfig + +[[autodoc]] MambaConfig + +## MambaModel + +[[autodoc]] MambaModel + - forward + +## MambaLMHeadModel + +[[autodoc]] MambaForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba2.md new file mode 100644 index 0000000000000000000000000000000000000000..8d88d6c02652e50c3efacc1bdc7277dcabda1376 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mamba2.md @@ -0,0 +1,110 @@ + + +# Mamba 2 + +
+PyTorch +
+ +## Overview + +The Mamba2 model was proposed in [Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality](https://arxiv.org/abs/2405.21060) by Tri Dao and Albert Gu. It is a State Space Model similar to Mamba 1, with better performances in a simplified architecture. + + +The abstract from the paper is the following: + +*While Transformers have been the main architecture behind deep learning's success in language modeling, state-space models (SSMs) such as Mamba have recently been shown to match or outperform Transformers at small to medium scale. We show that these families of models are actually quite closely related, and develop a rich framework of theoretical connections between SSMs and variants of attention, connected through various decompositions of a well-studied class of structured semiseparable matrices. Our state space duality (SSD) framework allows us to design a new architecture (Mamba-2) whose core layer is an a refinement of Mamba's selective SSM that is 2-8X faster, while continuing to be competitive with Transformers on language modeling.* + +Tips: + +This version should support all implementations of Mamba 2, and in particular [Mamba-2 codestral](https://huggingface.co/mistralai/Mamba-Codestral-7B-v0.1) from Mistral AI. In particular, mamba 2 codestral was released with a number of `groups` equal to 8, which can be thought intuitively as similar to the number of kv heads in an attention-based model. +This model has two different forward passes, `torch_forward` or `cuda_kernels_forward`. The latter uses the original cuda kernels if they are found in your environment, and is slower on the prefill i.e. requires a "warmup run" due to high cpu overhead, see [here](https://github.com/state-spaces/mamba/issues/389#issuecomment-2171755306) and [also here](https://github.com/state-spaces/mamba/issues/355#issuecomment-2147597457). Without compilation, the `torch_forward` implementation is faster by a factor 3 to 4. Further, there are no positional embeddings in this model, but there is an `attention_mask` and a specific logic to mask out hidden states in two places in the case of batched generation, see [here](https://github.com/state-spaces/mamba/issues/66#issuecomment-1863563829) as well. Due to this, in addition to the reimplementation of mamba2 kernels, batched generation and cached generation are expected to have slight discrepancies. Further, the results given by the cuda kernels or the torch forward are expected to be slightly different. The SSM algorithm heavily relies on tensor contractions, which have matmul equivalents but the order of operations is slightly different, making the difference greater at smaller precisions. +Another note, shutdown of hidden states corresponding to padding tokens is done in 2 places and mostly has been tested with left-padding. Right-padding will propagate noise down the line and is not guaranteed to yield satisfactory results. `tokenizer.padding_side = "left"` ensures you are using the correct padding side. + +This model was contributed by [Molbap](https://huggingface.co/Molbap), with tremendous help from [Anton Vlasjuk](https://github.com/vasqu). +The original code can be found [here](https://github.com/state-spaces/mamba). + + +# Usage + +### A simple generation example: +```python +from transformers import Mamba2Config, Mamba2ForCausalLM, AutoTokenizer +import torch +model_id = 'mistralai/Mamba-Codestral-7B-v0.1' +tokenizer = AutoTokenizer.from_pretrained(model_id, revision='refs/pr/9', from_slow=True, legacy=False) +model = Mamba2ForCausalLM.from_pretrained(model_id, revision='refs/pr/9') +input_ids = tokenizer("Hey how are you doing?", return_tensors= "pt")["input_ids"] + +out = model.generate(input_ids, max_new_tokens=10) +print(tokenizer.batch_decode(out)) +``` + +Here's a draft script for finetuning: +```python +from trl import SFTTrainer +from peft import LoraConfig +from transformers import AutoTokenizer, Mamba2ForCausalLM, TrainingArguments +model_id = 'mistralai/Mamba-Codestral-7B-v0.1' +tokenizer = AutoTokenizer.from_pretrained(model_id, revision='refs/pr/9', from_slow=True, legacy=False) +tokenizer.pad_token = tokenizer.eos_token +tokenizer.padding_side = "left" #enforce padding side left + +model = Mamba2ForCausalLM.from_pretrained(model_id, revision='refs/pr/9') +dataset = load_dataset("Abirate/english_quotes", split="train") +# Without CUDA kernels, batch size of 2 occupies one 80GB device +# but precision can be reduced. +# Experiments and trials welcome! +training_args = TrainingArguments( + output_dir="./results", + num_train_epochs=3, + per_device_train_batch_size=2, + logging_dir='./logs', + logging_steps=10, + learning_rate=2e-3 +) +lora_config = LoraConfig( + r=8, + target_modules=["embeddings", "in_proj", "out_proj"], + task_type="CAUSAL_LM", + bias="none" +) +trainer = SFTTrainer( + model=model, + tokenizer=tokenizer, + args=training_args, + peft_config=lora_config, + train_dataset=dataset, + dataset_text_field="quote", +) +trainer.train() +``` + + +## Mamba2Config + +[[autodoc]] Mamba2Config + +## Mamba2Model + +[[autodoc]] Mamba2Model + - forward + +## Mamba2LMHeadModel + +[[autodoc]] Mamba2ForCausalLM + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/marian.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/marian.md new file mode 100644 index 0000000000000000000000000000000000000000..80bb73d26df121000a8d6a2343142489532cbf08 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/marian.md @@ -0,0 +1,223 @@ + + +# MarianMT + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +A framework for translation models, using the same models as BART. Translations should be similar, but not identical to output in the test set linked to in each model card. +This model was contributed by [sshleifer](https://huggingface.co/sshleifer). + + +## Implementation Notes + +- Each model is about 298 MB on disk, there are more than 1,000 models. +- The list of supported language pairs can be found [here](https://huggingface.co/Helsinki-NLP). +- Models were originally trained by [Jörg Tiedemann](https://researchportal.helsinki.fi/en/persons/j%C3%B6rg-tiedemann) using the [Marian](https://marian-nmt.github.io/) C++ library, which supports fast training and translation. +- All models are transformer encoder-decoders with 6 layers in each component. Each model's performance is documented + in a model card. +- The 80 opus models that require BPE preprocessing are not supported. +- The modeling code is the same as [`BartForConditionalGeneration`] with a few minor modifications: + + - static (sinusoid) positional embeddings (`MarianConfig.static_position_embeddings=True`) + - no layernorm_embedding (`MarianConfig.normalize_embedding=False`) + - the model starts generating with `pad_token_id` (which has 0 as a token_embedding) as the prefix (Bart uses + ``), +- Code to bulk convert models can be found in `convert_marian_to_pytorch.py`. + + +## Naming + +- All model names use the following format: `Helsinki-NLP/opus-mt-{src}-{tgt}` +- The language codes used to name models are inconsistent. Two digit codes can usually be found [here](https://developers.google.com/admin-sdk/directory/v1/languages), three digit codes require googling "language + code {code}". +- Codes formatted like `es_AR` are usually `code_{region}`. That one is Spanish from Argentina. +- The models were converted in two stages. The first 1000 models use ISO-639-2 codes to identify languages, the second + group use a combination of ISO-639-5 codes and ISO-639-2 codes. + + +## Examples + +- Since Marian models are smaller than many other translation models available in the library, they can be useful for + fine-tuning experiments and integration tests. +- [Fine-tune on GPU](https://github.com/huggingface/transformers/blob/master/examples/legacy/seq2seq/train_distil_marian_enro.sh) + +## Multilingual Models + +- All model names use the following format: `Helsinki-NLP/opus-mt-{src}-{tgt}`: +- If a model can output multiple languages, and you should specify a language code by prepending the desired output + language to the `src_text`. +- You can see a models's supported language codes in its model card, under target constituents, like in [opus-mt-en-roa](https://huggingface.co/Helsinki-NLP/opus-mt-en-roa). +- Note that if a model is only multilingual on the source side, like `Helsinki-NLP/opus-mt-roa-en`, no language + codes are required. + +New multi-lingual models from the [Tatoeba-Challenge repo](https://github.com/Helsinki-NLP/Tatoeba-Challenge) +require 3 character language codes: + +```python +>>> from transformers import MarianMTModel, MarianTokenizer + +>>> src_text = [ +... ">>fra<< this is a sentence in english that we want to translate to french", +... ">>por<< This should go to portuguese", +... ">>esp<< And this to Spanish", +... ] + +>>> model_name = "Helsinki-NLP/opus-mt-en-roa" +>>> tokenizer = MarianTokenizer.from_pretrained(model_name) +>>> print(tokenizer.supported_language_codes) +['>>zlm_Latn<<', '>>mfe<<', '>>hat<<', '>>pap<<', '>>ast<<', '>>cat<<', '>>ind<<', '>>glg<<', '>>wln<<', '>>spa<<', '>>fra<<', '>>ron<<', '>>por<<', '>>ita<<', '>>oci<<', '>>arg<<', '>>min<<'] + +>>> model = MarianMTModel.from_pretrained(model_name) +>>> translated = model.generate(**tokenizer(src_text, return_tensors="pt", padding=True)) +>>> [tokenizer.decode(t, skip_special_tokens=True) for t in translated] +["c'est une phrase en anglais que nous voulons traduire en français", + 'Isto deve ir para o português.', + 'Y esto al español'] +``` + +Here is the code to see all available pretrained models on the hub: + +```python +from huggingface_hub import list_models + +model_list = list_models() +org = "Helsinki-NLP" +model_ids = [x.id for x in model_list if x.id.startswith(org)] +suffix = [x.split("/")[1] for x in model_ids] +old_style_multi_models = [f"{org}/{s}" for s in suffix if s != s.lower()] +``` + +## Old Style Multi-Lingual Models + +These are the old style multi-lingual models ported from the OPUS-MT-Train repo: and the members of each language +group: + +```python no-style +['Helsinki-NLP/opus-mt-NORTH_EU-NORTH_EU', + 'Helsinki-NLP/opus-mt-ROMANCE-en', + 'Helsinki-NLP/opus-mt-SCANDINAVIA-SCANDINAVIA', + 'Helsinki-NLP/opus-mt-de-ZH', + 'Helsinki-NLP/opus-mt-en-CELTIC', + 'Helsinki-NLP/opus-mt-en-ROMANCE', + 'Helsinki-NLP/opus-mt-es-NORWAY', + 'Helsinki-NLP/opus-mt-fi-NORWAY', + 'Helsinki-NLP/opus-mt-fi-ZH', + 'Helsinki-NLP/opus-mt-fi_nb_no_nn_ru_sv_en-SAMI', + 'Helsinki-NLP/opus-mt-sv-NORWAY', + 'Helsinki-NLP/opus-mt-sv-ZH'] +GROUP_MEMBERS = { + 'ZH': ['cmn', 'cn', 'yue', 'ze_zh', 'zh_cn', 'zh_CN', 'zh_HK', 'zh_tw', 'zh_TW', 'zh_yue', 'zhs', 'zht', 'zh'], + 'ROMANCE': ['fr', 'fr_BE', 'fr_CA', 'fr_FR', 'wa', 'frp', 'oc', 'ca', 'rm', 'lld', 'fur', 'lij', 'lmo', 'es', 'es_AR', 'es_CL', 'es_CO', 'es_CR', 'es_DO', 'es_EC', 'es_ES', 'es_GT', 'es_HN', 'es_MX', 'es_NI', 'es_PA', 'es_PE', 'es_PR', 'es_SV', 'es_UY', 'es_VE', 'pt', 'pt_br', 'pt_BR', 'pt_PT', 'gl', 'lad', 'an', 'mwl', 'it', 'it_IT', 'co', 'nap', 'scn', 'vec', 'sc', 'ro', 'la'], + 'NORTH_EU': ['de', 'nl', 'fy', 'af', 'da', 'fo', 'is', 'no', 'nb', 'nn', 'sv'], + 'SCANDINAVIA': ['da', 'fo', 'is', 'no', 'nb', 'nn', 'sv'], + 'SAMI': ['se', 'sma', 'smj', 'smn', 'sms'], + 'NORWAY': ['nb_NO', 'nb', 'nn_NO', 'nn', 'nog', 'no_nb', 'no'], + 'CELTIC': ['ga', 'cy', 'br', 'gd', 'kw', 'gv'] +} +``` + +Example of translating english to many romance languages, using old-style 2 character language codes + + +```python +>>> from transformers import MarianMTModel, MarianTokenizer + +>>> src_text = [ +... ">>fr<< this is a sentence in english that we want to translate to french", +... ">>pt<< This should go to portuguese", +... ">>es<< And this to Spanish", +... ] + +>>> model_name = "Helsinki-NLP/opus-mt-en-ROMANCE" +>>> tokenizer = MarianTokenizer.from_pretrained(model_name) + +>>> model = MarianMTModel.from_pretrained(model_name) +>>> translated = model.generate(**tokenizer(src_text, return_tensors="pt", padding=True)) +>>> tgt_text = [tokenizer.decode(t, skip_special_tokens=True) for t in translated] +["c'est une phrase en anglais que nous voulons traduire en français", + 'Isto deve ir para o português.', + 'Y esto al español'] +``` + +## Resources + +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) +- [Causal language modeling task guide](../tasks/language_modeling) + +## MarianConfig + +[[autodoc]] MarianConfig + +## MarianTokenizer + +[[autodoc]] MarianTokenizer + - build_inputs_with_special_tokens + + + + +## MarianModel + +[[autodoc]] MarianModel + - forward + +## MarianMTModel + +[[autodoc]] MarianMTModel + - forward + +## MarianForCausalLM + +[[autodoc]] MarianForCausalLM + - forward + + + + +## TFMarianModel + +[[autodoc]] TFMarianModel + - call + +## TFMarianMTModel + +[[autodoc]] TFMarianMTModel + - call + + + + +## FlaxMarianModel + +[[autodoc]] FlaxMarianModel + - __call__ + +## FlaxMarianMTModel + +[[autodoc]] FlaxMarianMTModel + - __call__ + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/markuplm.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/markuplm.md new file mode 100644 index 0000000000000000000000000000000000000000..72948da2c5af42913dae55768f3d044fe84ca375 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/markuplm.md @@ -0,0 +1,257 @@ + + +# MarkupLM + +
+PyTorch +
+ +## Overview + +The MarkupLM model was proposed in [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document +Understanding](https://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei. MarkupLM is BERT, but +applied to HTML pages instead of raw text documents. The model incorporates additional embedding layers to improve +performance, similar to [LayoutLM](layoutlm). + +The model can be used for tasks like question answering on web pages or information extraction from web pages. It obtains +state-of-the-art results on 2 important benchmarks: +- [WebSRC](https://x-lance.github.io/WebSRC/), a dataset for Web-Based Structural Reading Comprehension (a bit like SQuAD but for web pages) +- [SWDE](https://www.researchgate.net/publication/221299838_From_one_tree_to_a_forest_a_unified_solution_for_structured_web_data_extraction), a dataset +for information extraction from web pages (basically named-entity recognition on web pages) + +The abstract from the paper is the following: + +*Multimodal pre-training with text, layout, and image has made significant progress for Visually-rich Document +Understanding (VrDU), especially the fixed-layout documents such as scanned document images. While, there are still a +large number of digital documents where the layout information is not fixed and needs to be interactively and +dynamically rendered for visualization, making existing layout-based pre-training approaches not easy to apply. In this +paper, we propose MarkupLM for document understanding tasks with markup languages as the backbone such as +HTML/XML-based documents, where text and markup information is jointly pre-trained. Experiment results show that the +pre-trained MarkupLM significantly outperforms the existing strong baseline models on several document understanding +tasks. The pre-trained model and code will be publicly available.* + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/markuplm). + +## Usage tips + +- In addition to `input_ids`, [`~MarkupLMModel.forward`] expects 2 additional inputs, namely `xpath_tags_seq` and `xpath_subs_seq`. +These are the XPATH tags and subscripts respectively for each token in the input sequence. +- One can use [`MarkupLMProcessor`] to prepare all data for the model. Refer to the [usage guide](#usage-markuplmprocessor) for more info. + + + + MarkupLM architecture. Taken from the original paper. + +## Usage: MarkupLMProcessor + +The easiest way to prepare data for the model is to use [`MarkupLMProcessor`], which internally combines a feature extractor +([`MarkupLMFeatureExtractor`]) and a tokenizer ([`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`]). The feature extractor is +used to extract all nodes and xpaths from the HTML strings, which are then provided to the tokenizer, which turns them into the +token-level inputs of the model (`input_ids` etc.). Note that you can still use the feature extractor and tokenizer separately, +if you only want to handle one of the two tasks. + +```python +from transformers import MarkupLMFeatureExtractor, MarkupLMTokenizerFast, MarkupLMProcessor + +feature_extractor = MarkupLMFeatureExtractor() +tokenizer = MarkupLMTokenizerFast.from_pretrained("microsoft/markuplm-base") +processor = MarkupLMProcessor(feature_extractor, tokenizer) +``` + +In short, one can provide HTML strings (and possibly additional data) to [`MarkupLMProcessor`], +and it will create the inputs expected by the model. Internally, the processor first uses +[`MarkupLMFeatureExtractor`] to get a list of nodes and corresponding xpaths. The nodes and +xpaths are then provided to [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`], which converts them +to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_subs_seq`, `xpath_tags_seq`. +Optionally, one can provide node labels to the processor, which are turned into token-level `labels`. + +[`MarkupLMFeatureExtractor`] uses [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/), a Python library for +pulling data out of HTML and XML files, under the hood. Note that you can still use your own parsing solution of +choice, and provide the nodes and xpaths yourself to [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`]. + +In total, there are 5 use cases that are supported by the processor. Below, we list them all. Note that each of these +use cases work for both batched and non-batched inputs (we illustrate them for non-batched inputs). + +**Use case 1: web page classification (training, inference) + token classification (inference), parse_html = True** + +This is the simplest case, in which the processor will use the feature extractor to get all nodes and xpaths from the HTML. + +```python +>>> from transformers import MarkupLMProcessor + +>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base") + +>>> html_string = """ +... +... +... +... Hello world +... +... +...

Welcome

+...

Here is my website.

+... +... """ + +>>> # note that you can also add provide all tokenizer parameters here such as padding, truncation +>>> encoding = processor(html_string, return_tensors="pt") +>>> print(encoding.keys()) +dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq']) +``` + +**Use case 2: web page classification (training, inference) + token classification (inference), parse_html=False** + +In case one already has obtained all nodes and xpaths, one doesn't need the feature extractor. In that case, one should +provide the nodes and corresponding xpaths themselves to the processor, and make sure to set `parse_html` to `False`. + +```python +>>> from transformers import MarkupLMProcessor + +>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base") +>>> processor.parse_html = False + +>>> nodes = ["hello", "world", "how", "are"] +>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"] +>>> encoding = processor(nodes=nodes, xpaths=xpaths, return_tensors="pt") +>>> print(encoding.keys()) +dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq']) +``` + +**Use case 3: token classification (training), parse_html=False** + +For token classification tasks (such as [SWDE](https://paperswithcode.com/dataset/swde)), one can also provide the +corresponding node labels in order to train a model. The processor will then convert these into token-level `labels`. +By default, it will only label the first wordpiece of a word, and label the remaining wordpieces with -100, which is the +`ignore_index` of PyTorch's CrossEntropyLoss. In case you want all wordpieces of a word to be labeled, you can +initialize the tokenizer with `only_label_first_subword` set to `False`. + +```python +>>> from transformers import MarkupLMProcessor + +>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base") +>>> processor.parse_html = False + +>>> nodes = ["hello", "world", "how", "are"] +>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"] +>>> node_labels = [1, 2, 2, 1] +>>> encoding = processor(nodes=nodes, xpaths=xpaths, node_labels=node_labels, return_tensors="pt") +>>> print(encoding.keys()) +dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq', 'labels']) +``` + +**Use case 4: web page question answering (inference), parse_html=True** + +For question answering tasks on web pages, you can provide a question to the processor. By default, the +processor will use the feature extractor to get all nodes and xpaths, and create [CLS] question tokens [SEP] word tokens [SEP]. + +```python +>>> from transformers import MarkupLMProcessor + +>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base") + +>>> html_string = """ +... +... +... +... Hello world +... +... +...

Welcome

+...

My name is Niels.

+... +... """ + +>>> question = "What's his name?" +>>> encoding = processor(html_string, questions=question, return_tensors="pt") +>>> print(encoding.keys()) +dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq']) +``` + +**Use case 5: web page question answering (inference), parse_html=False** + +For question answering tasks (such as WebSRC), you can provide a question to the processor. If you have extracted +all nodes and xpaths yourself, you can provide them directly to the processor. Make sure to set `parse_html` to `False`. + +```python +>>> from transformers import MarkupLMProcessor + +>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base") +>>> processor.parse_html = False + +>>> nodes = ["hello", "world", "how", "are"] +>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"] +>>> question = "What's his name?" +>>> encoding = processor(nodes=nodes, xpaths=xpaths, questions=question, return_tensors="pt") +>>> print(encoding.keys()) +dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq']) +``` + +## Resources + +- [Demo notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/MarkupLM) +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) + +## MarkupLMConfig + +[[autodoc]] MarkupLMConfig + - all + +## MarkupLMFeatureExtractor + +[[autodoc]] MarkupLMFeatureExtractor + - __call__ + +## MarkupLMTokenizer + +[[autodoc]] MarkupLMTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## MarkupLMTokenizerFast + +[[autodoc]] MarkupLMTokenizerFast + - all + +## MarkupLMProcessor + +[[autodoc]] MarkupLMProcessor + - __call__ + +## MarkupLMModel + +[[autodoc]] MarkupLMModel + - forward + +## MarkupLMForSequenceClassification + +[[autodoc]] MarkupLMForSequenceClassification + - forward + +## MarkupLMForTokenClassification + +[[autodoc]] MarkupLMForTokenClassification + - forward + +## MarkupLMForQuestionAnswering + +[[autodoc]] MarkupLMForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mask2former.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mask2former.md new file mode 100644 index 0000000000000000000000000000000000000000..37a2603c68800905cabbb5b49cd1ead121c1372e --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mask2former.md @@ -0,0 +1,80 @@ + + +# Mask2Former + +
+PyTorch +
+ +## Overview + +The Mask2Former model was proposed in [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. Mask2Former is a unified framework for panoptic, instance and semantic segmentation and features significant performance and efficiency improvements over [MaskFormer](maskformer). + +The abstract from the paper is the following: + +*Image segmentation groups pixels with different semantics, e.g., category or instance membership. Each choice +of semantics defines a task. While only the semantics of each task differ, current research focuses on designing specialized architectures for each task. We present Masked-attention Mask Transformer (Mask2Former), a new architecture capable of addressing any image segmentation task (panoptic, instance or semantic). Its key components include masked attention, which extracts localized features by constraining cross-attention within predicted mask regions. In addition to reducing the research effort by at least three times, it outperforms the best specialized architectures by a significant margin on four popular datasets. Most notably, Mask2Former sets a new state-of-the-art for panoptic segmentation (57.8 PQ on COCO), instance segmentation (50.1 AP on COCO) and semantic segmentation (57.7 mIoU on ADE20K).* + +drawing + + Mask2Former architecture. Taken from the original paper. + +This model was contributed by [Shivalika Singh](https://huggingface.co/shivi) and [Alara Dirik](https://huggingface.co/adirik). The original code can be found [here](https://github.com/facebookresearch/Mask2Former). + +## Usage tips + +- Mask2Former uses the same preprocessing and postprocessing steps as [MaskFormer](maskformer). Use [`Mask2FormerImageProcessor`] or [`AutoImageProcessor`] to prepare images and optional targets for the model. +- To get the final segmentation, depending on the task, you can call [`~Mask2FormerImageProcessor.post_process_semantic_segmentation`] or [`~Mask2FormerImageProcessor.post_process_instance_segmentation`] or [`~Mask2FormerImageProcessor.post_process_panoptic_segmentation`]. All three tasks can be solved using [`Mask2FormerForUniversalSegmentation`] output, panoptic segmentation accepts an optional `label_ids_to_fuse` argument to fuse instances of the target object/s (e.g. sky) together. + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Mask2Former. + +- Demo notebooks regarding inference + fine-tuning Mask2Former on custom data can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Mask2Former). +- Scripts for finetuning [`Mask2Former`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/instance-segmentation). + +If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. +The resource should ideally demonstrate something new instead of duplicating an existing resource. + +## Mask2FormerConfig + +[[autodoc]] Mask2FormerConfig + +## MaskFormer specific outputs + +[[autodoc]] models.mask2former.modeling_mask2former.Mask2FormerModelOutput + +[[autodoc]] models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput + +## Mask2FormerModel + +[[autodoc]] Mask2FormerModel + - forward + +## Mask2FormerForUniversalSegmentation + +[[autodoc]] Mask2FormerForUniversalSegmentation + - forward + +## Mask2FormerImageProcessor + +[[autodoc]] Mask2FormerImageProcessor + - preprocess + - encode_inputs + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/maskformer.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/maskformer.md new file mode 100644 index 0000000000000000000000000000000000000000..0adbbf2285f9dc1ad625161a9d2bda7f819b05f0 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/maskformer.md @@ -0,0 +1,96 @@ + + +# MaskFormer + +
+PyTorch +
+ + + +This is a recently introduced model so the API hasn't been tested extensively. There may be some bugs or slight +breaking changes to fix it in the future. If you see something strange, file a [Github Issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=&template=bug-report.md&title). + + + +## Overview + +The MaskFormer model was proposed in [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov. MaskFormer addresses semantic segmentation with a mask classification paradigm instead of performing classic pixel-level classification. + +The abstract from the paper is the following: + +*Modern approaches typically formulate semantic segmentation as a per-pixel classification task, while instance-level segmentation is handled with an alternative mask classification. Our key insight: mask classification is sufficiently general to solve both semantic- and instance-level segmentation tasks in a unified manner using the exact same model, loss, and training procedure. Following this observation, we propose MaskFormer, a simple mask classification model which predicts a set of binary masks, each associated with a single global class label prediction. Overall, the proposed mask classification-based method simplifies the landscape of effective approaches to semantic and panoptic segmentation tasks and shows excellent empirical results. In particular, we observe that MaskFormer outperforms per-pixel classification baselines when the number of classes is large. Our mask classification-based method outperforms both current state-of-the-art semantic (55.6 mIoU on ADE20K) and panoptic segmentation (52.7 PQ on COCO) models.* + +The figure below illustrates the architecture of MaskFormer. Taken from the [original paper](https://arxiv.org/abs/2107.06278). + + + +This model was contributed by [francesco](https://huggingface.co/francesco). The original code can be found [here](https://github.com/facebookresearch/MaskFormer). + +## Usage tips + +- MaskFormer's Transformer decoder is identical to the decoder of [DETR](detr). During training, the authors of DETR did find it helpful to use auxiliary losses in the decoder, especially to help the model output the correct number of objects of each class. If you set the parameter `use_auxiliary_loss` of [`MaskFormerConfig`] to `True`, then prediction feedforward neural networks and Hungarian losses are added after each decoder layer (with the FFNs sharing parameters). +- If you want to train the model in a distributed environment across multiple nodes, then one should update the + `get_num_masks` function inside in the `MaskFormerLoss` class of `modeling_maskformer.py`. When training on multiple nodes, this should be + set to the average number of target masks across all nodes, as can be seen in the original implementation [here](https://github.com/facebookresearch/MaskFormer/blob/da3e60d85fdeedcb31476b5edd7d328826ce56cc/mask_former/modeling/criterion.py#L169). +- One can use [`MaskFormerImageProcessor`] to prepare images for the model and optional targets for the model. +- To get the final segmentation, depending on the task, you can call [`~MaskFormerImageProcessor.post_process_semantic_segmentation`] or [`~MaskFormerImageProcessor.post_process_panoptic_segmentation`]. Both tasks can be solved using [`MaskFormerForInstanceSegmentation`] output, panoptic segmentation accepts an optional `label_ids_to_fuse` argument to fuse instances of the target object/s (e.g. sky) together. + +## Resources + + + +- All notebooks that illustrate inference as well as fine-tuning on custom data with MaskFormer can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/MaskFormer). +- Scripts for finetuning [`MaskFormer`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/instance-segmentation). + +## MaskFormer specific outputs + +[[autodoc]] models.maskformer.modeling_maskformer.MaskFormerModelOutput + +[[autodoc]] models.maskformer.modeling_maskformer.MaskFormerForInstanceSegmentationOutput + +## MaskFormerConfig + +[[autodoc]] MaskFormerConfig + +## MaskFormerImageProcessor + +[[autodoc]] MaskFormerImageProcessor + - preprocess + - encode_inputs + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation + +## MaskFormerFeatureExtractor + +[[autodoc]] MaskFormerFeatureExtractor + - __call__ + - encode_inputs + - post_process_semantic_segmentation + - post_process_instance_segmentation + - post_process_panoptic_segmentation + +## MaskFormerModel + +[[autodoc]] MaskFormerModel + - forward + +## MaskFormerForInstanceSegmentation + +[[autodoc]] MaskFormerForInstanceSegmentation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/matcha.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/matcha.md new file mode 100644 index 0000000000000000000000000000000000000000..f3c618953b9b4e2aa39fd22d772de865495b6212 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/matcha.md @@ -0,0 +1,80 @@ + + +# MatCha + +
+PyTorch +
+ +## Overview + +MatCha has been proposed in the paper [MatCha: Enhancing Visual Language Pretraining with Math Reasoning and Chart Derendering](https://arxiv.org/abs/2212.09662), from Fangyu Liu, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Yasemin Altun, Nigel Collier, Julian Martin Eisenschlos. + +The abstract of the paper states the following: + +*Visual language data such as plots, charts, and infographics are ubiquitous in the human world. However, state-of-the-art vision-language models do not perform well on these data. We propose MatCha (Math reasoning and Chart derendering pretraining) to enhance visual language models' capabilities in jointly modeling charts/plots and language data. Specifically, we propose several pretraining tasks that cover plot deconstruction and numerical reasoning which are the key capabilities in visual language modeling. We perform the MatCha pretraining starting from Pix2Struct, a recently proposed image-to-text visual language model. On standard benchmarks such as PlotQA and ChartQA, the MatCha model outperforms state-of-the-art methods by as much as nearly 20%. We also examine how well MatCha pretraining transfers to domains such as screenshots, textbook diagrams, and document figures and observe overall improvement, verifying the usefulness of MatCha pretraining on broader visual language tasks.* + +## Model description + +MatCha is a model that is trained using `Pix2Struct` architecture. You can find more information about `Pix2Struct` in the [Pix2Struct documentation](https://huggingface.co/docs/transformers/main/en/model_doc/pix2struct). +MatCha is a Visual Question Answering subset of `Pix2Struct` architecture. It renders the input question on the image and predicts the answer. + +## Usage + +Currently 6 checkpoints are available for MatCha: + +- `google/matcha`: the base MatCha model, used to fine-tune MatCha on downstream tasks +- `google/matcha-chartqa`: MatCha model fine-tuned on ChartQA dataset. It can be used to answer questions about charts. +- `google/matcha-plotqa-v1`: MatCha model fine-tuned on PlotQA dataset. It can be used to answer questions about plots. +- `google/matcha-plotqa-v2`: MatCha model fine-tuned on PlotQA dataset. It can be used to answer questions about plots. +- `google/matcha-chart2text-statista`: MatCha model fine-tuned on Statista dataset. +- `google/matcha-chart2text-pew`: MatCha model fine-tuned on Pew dataset. + +The models finetuned on `chart2text-pew` and `chart2text-statista` are more suited for summarization, whereas the models finetuned on `plotqa` and `chartqa` are more suited for question answering. + +You can use these models as follows (example on a ChatQA dataset): + +```python +from transformers import AutoProcessor, Pix2StructForConditionalGeneration +import requests +from PIL import Image + +model = Pix2StructForConditionalGeneration.from_pretrained("google/matcha-chartqa").to(0) +processor = AutoProcessor.from_pretrained("google/matcha-chartqa") +url = "https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/20294671002019.png" +image = Image.open(requests.get(url, stream=True).raw) + +inputs = processor(images=image, text="Is the sum of all 4 places greater than Laos?", return_tensors="pt").to(0) +predictions = model.generate(**inputs, max_new_tokens=512) +print(processor.decode(predictions[0], skip_special_tokens=True)) +``` + +## Fine-tuning + +To fine-tune MatCha, refer to the pix2struct [fine-tuning notebook](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_pix2struct.ipynb). For `Pix2Struct` models, we have found out that fine-tuning the model with Adafactor and cosine learning rate scheduler leads to faster convergence: +```python +from transformers.optimization import Adafactor, get_cosine_schedule_with_warmup + +optimizer = Adafactor(self.parameters(), scale_parameter=False, relative_step=False, lr=0.01, weight_decay=1e-05) +scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=1000, num_training_steps=40000) +``` + + + +MatCha is a model that is trained using `Pix2Struct` architecture. You can find more information about `Pix2Struct` in the [Pix2Struct documentation](https://huggingface.co/docs/transformers/main/en/model_doc/pix2struct). + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mbart.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mbart.md new file mode 100644 index 0000000000000000000000000000000000000000..62356ad26402e64b6287ba12886716fa0ed6e10c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mbart.md @@ -0,0 +1,256 @@ + + +# MBart and MBart-50 + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ + +## Overview of MBart + +The MBart model was presented in [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov Marjan +Ghazvininejad, Mike Lewis, Luke Zettlemoyer. + +According to the abstract, MBART is a sequence-to-sequence denoising auto-encoder pretrained on large-scale monolingual +corpora in many languages using the BART objective. mBART is one of the first methods for pretraining a complete +sequence-to-sequence model by denoising full texts in multiple languages, while previous approaches have focused only +on the encoder, decoder, or reconstructing parts of the text. + +This model was contributed by [valhalla](https://huggingface.co/valhalla). The Authors' code can be found [here](https://github.com/pytorch/fairseq/tree/master/examples/mbart) + +### Training of MBart + +MBart is a multilingual encoder-decoder (sequence-to-sequence) model primarily intended for translation task. As the +model is multilingual it expects the sequences in a different format. A special language id token is added in both the +source and target text. The source text format is `X [eos, src_lang_code]` where `X` is the source text. The +target text format is `[tgt_lang_code] X [eos]`. `bos` is never used. + +The regular [`~MBartTokenizer.__call__`] will encode source text format passed as first argument or with the `text` +keyword, and target text format passed with the `text_label` keyword argument. + +- Supervised training + +```python +>>> from transformers import MBartForConditionalGeneration, MBartTokenizer + +>>> tokenizer = MBartTokenizer.from_pretrained("facebook/mbart-large-en-ro", src_lang="en_XX", tgt_lang="ro_RO") +>>> example_english_phrase = "UN Chief Says There Is No Military Solution in Syria" +>>> expected_translation_romanian = "Şeful ONU declară că nu există o soluţie militară în Siria" + +>>> inputs = tokenizer(example_english_phrase, text_target=expected_translation_romanian, return_tensors="pt") + +>>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro") +>>> # forward pass +>>> model(**inputs) +``` + +- Generation + + While generating the target text set the `decoder_start_token_id` to the target language id. The following + example shows how to translate English to Romanian using the *facebook/mbart-large-en-ro* model. + +```python +>>> from transformers import MBartForConditionalGeneration, MBartTokenizer + +>>> tokenizer = MBartTokenizer.from_pretrained("facebook/mbart-large-en-ro", src_lang="en_XX") +>>> article = "UN Chief Says There Is No Military Solution in Syria" +>>> inputs = tokenizer(article, return_tensors="pt") +>>> translated_tokens = model.generate(**inputs, decoder_start_token_id=tokenizer.lang_code_to_id["ro_RO"]) +>>> tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0] +"Şeful ONU declară că nu există o soluţie militară în Siria" +``` + +## Overview of MBart-50 + +MBart-50 was introduced in the [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) paper by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav +Chaudhary, Jiatao Gu, Angela Fan. MBart-50 is created using the original *mbart-large-cc25* checkpoint by extending +its embedding layers with randomly initialized vectors for an extra set of 25 language tokens and then pretrained on 50 +languages. + +According to the abstract + +*Multilingual translation models can be created through multilingual finetuning. Instead of finetuning on one +direction, a pretrained model is finetuned on many directions at the same time. It demonstrates that pretrained models +can be extended to incorporate additional languages without loss of performance. Multilingual finetuning improves on +average 1 BLEU over the strongest baselines (being either multilingual from scratch or bilingual finetuning) while +improving 9.3 BLEU on average over bilingual baselines from scratch.* + + +### Training of MBart-50 + +The text format for MBart-50 is slightly different from mBART. For MBart-50 the language id token is used as a prefix +for both source and target text i.e the text format is `[lang_code] X [eos]`, where `lang_code` is source +language id for source text and target language id for target text, with `X` being the source or target text +respectively. + + +MBart-50 has its own tokenizer [`MBart50Tokenizer`]. + +- Supervised training + +```python +from transformers import MBartForConditionalGeneration, MBart50TokenizerFast + +model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50") +tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50", src_lang="en_XX", tgt_lang="ro_RO") + +src_text = " UN Chief Says There Is No Military Solution in Syria" +tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria" + +model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt") + +model(**model_inputs) # forward pass +``` + +- Generation + + To generate using the mBART-50 multilingual translation models, `eos_token_id` is used as the + `decoder_start_token_id` and the target language id is forced as the first generated token. To force the + target language id as the first generated token, pass the *forced_bos_token_id* parameter to the *generate* method. + The following example shows how to translate between Hindi to French and Arabic to English using the + *facebook/mbart-50-large-many-to-many* checkpoint. + +```python +from transformers import MBartForConditionalGeneration, MBart50TokenizerFast + +article_hi = "संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है" +article_ar = "الأمين العام للأمم المتحدة يقول إنه لا يوجد حل عسكري في سوريا." + +model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") +tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") + +# translate Hindi to French +tokenizer.src_lang = "hi_IN" +encoded_hi = tokenizer(article_hi, return_tensors="pt") +generated_tokens = model.generate(**encoded_hi, forced_bos_token_id=tokenizer.lang_code_to_id["fr_XX"]) +tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +# => "Le chef de l 'ONU affirme qu 'il n 'y a pas de solution militaire en Syria." + +# translate Arabic to English +tokenizer.src_lang = "ar_AR" +encoded_ar = tokenizer(article_ar, return_tensors="pt") +generated_tokens = model.generate(**encoded_ar, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"]) +tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) +# => "The Secretary-General of the United Nations says there is no military solution in Syria." +``` + +## Documentation resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## MBartConfig + +[[autodoc]] MBartConfig + +## MBartTokenizer + +[[autodoc]] MBartTokenizer + - build_inputs_with_special_tokens + +## MBartTokenizerFast + +[[autodoc]] MBartTokenizerFast + +## MBart50Tokenizer + +[[autodoc]] MBart50Tokenizer + +## MBart50TokenizerFast + +[[autodoc]] MBart50TokenizerFast + + + + +## MBartModel + +[[autodoc]] MBartModel + +## MBartForConditionalGeneration + +[[autodoc]] MBartForConditionalGeneration + +## MBartForQuestionAnswering + +[[autodoc]] MBartForQuestionAnswering + +## MBartForSequenceClassification + +[[autodoc]] MBartForSequenceClassification + +## MBartForCausalLM + +[[autodoc]] MBartForCausalLM + - forward + + + + +## TFMBartModel + +[[autodoc]] TFMBartModel + - call + +## TFMBartForConditionalGeneration + +[[autodoc]] TFMBartForConditionalGeneration + - call + + + + +## FlaxMBartModel + +[[autodoc]] FlaxMBartModel + - __call__ + - encode + - decode + +## FlaxMBartForConditionalGeneration + +[[autodoc]] FlaxMBartForConditionalGeneration + - __call__ + - encode + - decode + +## FlaxMBartForSequenceClassification + +[[autodoc]] FlaxMBartForSequenceClassification + - __call__ + - encode + - decode + +## FlaxMBartForQuestionAnswering + +[[autodoc]] FlaxMBartForQuestionAnswering + - __call__ + - encode + - decode + + + diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mctct.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mctct.md new file mode 100644 index 0000000000000000000000000000000000000000..a755f5a027d2051d18fa770449d80756f6455d98 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mctct.md @@ -0,0 +1,83 @@ + + +# M-CTC-T + +
+PyTorch +
+ + + +This model is in maintenance mode only, so we won't accept any new PRs changing its code. + +If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0. +You can do so by running the following command: `pip install -U transformers==4.30.0`. + + + +## Overview + +The M-CTC-T model was proposed in [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert. The model is a 1B-param transformer encoder, with a CTC head over 8065 character labels and a language identification head over 60 language ID labels. It is trained on Common Voice (version 6.1, December 2020 release) and VoxPopuli. After training on Common Voice and VoxPopuli, the model is trained on Common Voice only. The labels are unnormalized character-level transcripts (punctuation and capitalization are not removed). The model takes as input Mel filterbank features from a 16Khz audio signal. + +The abstract from the paper is the following: + +*Semi-supervised learning through pseudo-labeling has become a staple of state-of-the-art monolingual +speech recognition systems. In this work, we extend pseudo-labeling to massively multilingual speech +recognition with 60 languages. We propose a simple pseudo-labeling recipe that works well even +with low-resource languages: train a supervised multilingual model, fine-tune it with semi-supervised +learning on a target language, generate pseudo-labels for that language, and train a final model using +pseudo-labels for all languages, either from scratch or by fine-tuning. Experiments on the labeled +Common Voice and unlabeled VoxPopuli datasets show that our recipe can yield a model with better +performance for many languages that also transfers well to LibriSpeech.* + +This model was contributed by [cwkeam](https://huggingface.co/cwkeam). The original code can be found [here](https://github.com/flashlight/wav2letter/tree/main/recipes/mling_pl). + +## Usage tips + +The PyTorch version of this model is only available in torch 1.9 and higher. + +## Resources + +- [Automatic speech recognition task guide](../tasks/asr) + +## MCTCTConfig + +[[autodoc]] MCTCTConfig + +## MCTCTFeatureExtractor + +[[autodoc]] MCTCTFeatureExtractor + - __call__ + +## MCTCTProcessor + +[[autodoc]] MCTCTProcessor + - __call__ + - from_pretrained + - save_pretrained + - batch_decode + - decode + +## MCTCTModel + +[[autodoc]] MCTCTModel + - forward + +## MCTCTForCTC + +[[autodoc]] MCTCTForCTC + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mega.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mega.md new file mode 100644 index 0000000000000000000000000000000000000000..4e8ccd4b29f3b6a204c595f39ce4e2cdfb7bf256 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mega.md @@ -0,0 +1,96 @@ + + +# MEGA + +
+PyTorch +
+ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The MEGA model was proposed in [Mega: Moving Average Equipped Gated Attention](https://arxiv.org/abs/2209.10655) by Xuezhe Ma, Chunting Zhou, Xiang Kong, Junxian He, Liangke Gui, Graham Neubig, Jonathan May, and Luke Zettlemoyer. +MEGA proposes a new approach to self-attention with each encoder layer having a multi-headed exponential moving average in addition to a single head of standard dot-product attention, giving the attention mechanism +stronger positional biases. This allows MEGA to perform competitively to Transformers on standard benchmarks including LRA +while also having significantly fewer parameters. MEGA's compute efficiency allows it to scale to very long sequences, making it an +attractive option for long-document NLP tasks. + +The abstract from the paper is the following: + + *The design choices in the Transformer attention mechanism, including weak inductive bias and quadratic computational complexity, have limited its application for modeling long sequences. In this paper, we introduce Mega, a simple, theoretically grounded, single-head gated attention mechanism equipped with (exponential) moving average to incorporate inductive bias of position-aware local dependencies into the position-agnostic attention mechanism. We further propose a variant of Mega that offers linear time and space complexity yet yields only minimal quality loss, by efficiently splitting the whole sequence into multiple chunks with fixed length. Extensive experiments on a wide range of sequence modeling benchmarks, including the Long Range Arena, neural machine translation, auto-regressive language modeling, and image and speech classification, show that Mega achieves significant improvements over other sequence models, including variants of Transformers and recent state space models. * + +This model was contributed by [mnaylor](https://huggingface.co/mnaylor). +The original code can be found [here](https://github.com/facebookresearch/mega). + + +## Usage tips + +- MEGA can perform quite well with relatively few parameters. See Appendix D in the MEGA paper for examples of architectural specs which perform well in various settings. If using MEGA as a decoder, be sure to set `bidirectional=False` to avoid errors with default bidirectional. +- Mega-chunk is a variant of mega that reduces time and spaces complexity from quadratic to linear. Utilize chunking with MegaConfig.use_chunking and control chunk size with MegaConfig.chunk_size + + +## Implementation Notes + +- The original implementation of MEGA had an inconsistent expectation of attention masks for padding and causal self-attention between the softmax attention and Laplace/squared ReLU method. This implementation addresses that inconsistency. +- The original implementation did not include token type embeddings; this implementation adds support for these, with the option controlled by MegaConfig.add_token_type_embeddings + + +## MegaConfig + +[[autodoc]] MegaConfig + +## MegaModel + +[[autodoc]] MegaModel + - forward + +## MegaForCausalLM + +[[autodoc]] MegaForCausalLM + - forward + +## MegaForMaskedLM + +[[autodoc]] MegaForMaskedLM + - forward + +## MegaForSequenceClassification + +[[autodoc]] MegaForSequenceClassification + - forward + +## MegaForMultipleChoice + +[[autodoc]] MegaForMultipleChoice + - forward + +## MegaForTokenClassification + +[[autodoc]] MegaForTokenClassification + - forward + +## MegaForQuestionAnswering + +[[autodoc]] MegaForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron-bert.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron-bert.md new file mode 100644 index 0000000000000000000000000000000000000000..b032655f75472466a81368488a60c49865d195a2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron-bert.md @@ -0,0 +1,145 @@ + + +# MegatronBERT + +
+PyTorch +
+ +## Overview + +The MegatronBERT model was proposed in [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model +Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, +Jared Casper and Bryan Catanzaro. + +The abstract from the paper is the following: + +*Recent work in language modeling demonstrates that training large transformer models advances the state of the art in +Natural Language Processing applications. However, very large models can be quite difficult to train due to memory +constraints. In this work, we present our techniques for training very large transformer models and implement a simple, +efficient intra-layer model parallel approach that enables training transformer models with billions of parameters. Our +approach does not require a new compiler or library changes, is orthogonal and complimentary to pipeline model +parallelism, and can be fully implemented with the insertion of a few communication operations in native PyTorch. We +illustrate this approach by converging transformer based models up to 8.3 billion parameters using 512 GPUs. We sustain +15.1 PetaFLOPs across the entire application with 76% scaling efficiency when compared to a strong single GPU baseline +that sustains 39 TeraFLOPs, which is 30% of peak FLOPs. To demonstrate that large language models can further advance +the state of the art (SOTA), we train an 8.3 billion parameter transformer language model similar to GPT-2 and a 3.9 +billion parameter model similar to BERT. We show that careful attention to the placement of layer normalization in +BERT-like models is critical to achieving increased performance as the model size grows. Using the GPT-2 model we +achieve SOTA results on the WikiText103 (10.8 compared to SOTA perplexity of 15.8) and LAMBADA (66.5% compared to SOTA +accuracy of 63.2%) datasets. Our BERT model achieves SOTA results on the RACE dataset (90.9% compared to SOTA accuracy +of 89.4%).* + +This model was contributed by [jdemouth](https://huggingface.co/jdemouth). The original code can be found [here](https://github.com/NVIDIA/Megatron-LM). +That repository contains a multi-GPU and multi-node implementation of the Megatron Language models. In particular, +it contains a hybrid model parallel approach using "tensor parallel" and "pipeline parallel" techniques. + +## Usage tips + +We have provided pretrained [BERT-345M](https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m) checkpoints +for use to evaluate or finetuning downstream tasks. + +To access these checkpoints, first [sign up](https://ngc.nvidia.com/signup) for and setup the NVIDIA GPU Cloud (NGC) +Registry CLI. Further documentation for downloading models can be found in the [NGC documentation](https://docs.nvidia.com/dgx/ngc-registry-cli-user-guide/index.html#topic_6_4_1). + +Alternatively, you can directly download the checkpoints using: + +BERT-345M-uncased: + +```bash +wget --content-disposition https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.1_uncased/zip +-O megatron_bert_345m_v0_1_uncased.zip +``` + +BERT-345M-cased: + +```bash +wget --content-disposition https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.1_cased/zip -O +megatron_bert_345m_v0_1_cased.zip +``` + +Once you have obtained the checkpoints from NVIDIA GPU Cloud (NGC), you have to convert them to a format that will +easily be loaded by Hugging Face Transformers and our port of the BERT code. + +The following commands allow you to do the conversion. We assume that the folder `models/megatron_bert` contains +`megatron_bert_345m_v0_1_{cased, uncased}.zip` and that the commands are run from inside that folder: + +```bash +python3 $PATH_TO_TRANSFORMERS/models/megatron_bert/convert_megatron_bert_checkpoint.py megatron_bert_345m_v0_1_uncased.zip +``` + +```bash +python3 $PATH_TO_TRANSFORMERS/models/megatron_bert/convert_megatron_bert_checkpoint.py megatron_bert_345m_v0_1_cased.zip +``` + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Token classification task guide](../tasks/token_classification) +- [Question answering task guide](../tasks/question_answering) +- [Causal language modeling task guide](../tasks/language_modeling) +- [Masked language modeling task guide](../tasks/masked_language_modeling) +- [Multiple choice task guide](../tasks/multiple_choice) + +## MegatronBertConfig + +[[autodoc]] MegatronBertConfig + +## MegatronBertModel + +[[autodoc]] MegatronBertModel + - forward + +## MegatronBertForMaskedLM + +[[autodoc]] MegatronBertForMaskedLM + - forward + +## MegatronBertForCausalLM + +[[autodoc]] MegatronBertForCausalLM + - forward + +## MegatronBertForNextSentencePrediction + +[[autodoc]] MegatronBertForNextSentencePrediction + - forward + +## MegatronBertForPreTraining + +[[autodoc]] MegatronBertForPreTraining + - forward + +## MegatronBertForSequenceClassification + +[[autodoc]] MegatronBertForSequenceClassification + - forward + +## MegatronBertForMultipleChoice + +[[autodoc]] MegatronBertForMultipleChoice + - forward + +## MegatronBertForTokenClassification + +[[autodoc]] MegatronBertForTokenClassification + - forward + +## MegatronBertForQuestionAnswering + +[[autodoc]] MegatronBertForQuestionAnswering + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron_gpt2.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron_gpt2.md new file mode 100644 index 0000000000000000000000000000000000000000..7e0ee3cb9e7c98a4dce2ed321a49572db934b689 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/megatron_gpt2.md @@ -0,0 +1,84 @@ + + +# MegatronGPT2 + +
+PyTorch +TensorFlow +Flax +
+ +## Overview + +The MegatronGPT2 model was proposed in [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model +Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, +Jared Casper and Bryan Catanzaro. + +The abstract from the paper is the following: + +*Recent work in language modeling demonstrates that training large transformer models advances the state of the art in +Natural Language Processing applications. However, very large models can be quite difficult to train due to memory +constraints. In this work, we present our techniques for training very large transformer models and implement a simple, +efficient intra-layer model parallel approach that enables training transformer models with billions of parameters. Our +approach does not require a new compiler or library changes, is orthogonal and complimentary to pipeline model +parallelism, and can be fully implemented with the insertion of a few communication operations in native PyTorch. We +illustrate this approach by converging transformer based models up to 8.3 billion parameters using 512 GPUs. We sustain +15.1 PetaFLOPs across the entire application with 76% scaling efficiency when compared to a strong single GPU baseline +that sustains 39 TeraFLOPs, which is 30% of peak FLOPs. To demonstrate that large language models can further advance +the state of the art (SOTA), we train an 8.3 billion parameter transformer language model similar to GPT-2 and a 3.9 +billion parameter model similar to BERT. We show that careful attention to the placement of layer normalization in +BERT-like models is critical to achieving increased performance as the model size grows. Using the GPT-2 model we +achieve SOTA results on the WikiText103 (10.8 compared to SOTA perplexity of 15.8) and LAMBADA (66.5% compared to SOTA +accuracy of 63.2%) datasets. Our BERT model achieves SOTA results on the RACE dataset (90.9% compared to SOTA accuracy +of 89.4%).* + +This model was contributed by [jdemouth](https://huggingface.co/jdemouth). The original code can be found [here](https://github.com/NVIDIA/Megatron-LM). +That repository contains a multi-GPU and multi-node implementation of the Megatron Language models. In particular, it +contains a hybrid model parallel approach using "tensor parallel" and "pipeline parallel" techniques. + +## Usage tips + +We have provided pretrained [GPT2-345M](https://ngc.nvidia.com/catalog/models/nvidia:megatron_lm_345m) checkpoints +for use to evaluate or finetuning downstream tasks. + +To access these checkpoints, first [sign up](https://ngc.nvidia.com/signup) for and setup the NVIDIA GPU Cloud (NGC) +Registry CLI. Further documentation for downloading models can be found in the [NGC documentation](https://docs.nvidia.com/dgx/ngc-registry-cli-user-guide/index.html#topic_6_4_1). + +Alternatively, you can directly download the checkpoints using: + +```bash +wget --content-disposition https://api.ngc.nvidia.com/v2/models/nvidia/megatron_lm_345m/versions/v0.0/zip -O +megatron_gpt2_345m_v0_0.zip +``` + +Once you have obtained the checkpoint from NVIDIA GPU Cloud (NGC), you have to convert it to a format that will easily +be loaded by Hugging Face Transformers GPT2 implementation. + +The following command allows you to do the conversion. We assume that the folder `models/megatron_gpt2` contains +`megatron_gpt2_345m_v0_0.zip` and that the command is run from that folder: + +```bash +python3 $PATH_TO_TRANSFORMERS/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py megatron_gpt2_345m_v0_0.zip +``` + + + + MegatronGPT2 architecture is the same as OpenAI GPT-2 . Refer to [GPT-2 documentation](gpt2) for information on + configuration classes and their parameters. + + \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mgp-str.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mgp-str.md new file mode 100644 index 0000000000000000000000000000000000000000..168e5bd1043d5069b1f4a6997ee6a074abbd7602 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mgp-str.md @@ -0,0 +1,92 @@ + + +# MGP-STR + +
+PyTorch +
+ +## Overview + +The MGP-STR model was proposed in [Multi-Granularity Prediction for Scene Text Recognition](https://arxiv.org/abs/2209.03592) by Peng Wang, Cheng Da, and Cong Yao. MGP-STR is a conceptually **simple** yet **powerful** vision Scene Text Recognition (STR) model, which is built upon the [Vision Transformer (ViT)](vit). To integrate linguistic knowledge, Multi-Granularity Prediction (MGP) strategy is proposed to inject information from the language modality into the model in an implicit way. + +The abstract from the paper is the following: + +*Scene text recognition (STR) has been an active research topic in computer vision for years. To tackle this challenging problem, numerous innovative methods have been successively proposed and incorporating linguistic knowledge into STR models has recently become a prominent trend. In this work, we first draw inspiration from the recent progress in Vision Transformer (ViT) to construct a conceptually simple yet powerful vision STR model, which is built upon ViT and outperforms previous state-of-the-art models for scene text recognition, including both pure vision models and language-augmented methods. To integrate linguistic knowledge, we further propose a Multi-Granularity Prediction strategy to inject information from the language modality into the model in an implicit way, i.e. , subword representations (BPE and WordPiece) widely-used in NLP are introduced into the output space, in addition to the conventional character level representation, while no independent language model (LM) is adopted. The resultant algorithm (termed MGP-STR) is able to push the performance envelop of STR to an even higher level. Specifically, it achieves an average recognition accuracy of 93.35% on standard benchmarks.* + + + + MGP-STR architecture. Taken from the original paper. + +MGP-STR is trained on two synthetic datasets [MJSynth]((http://www.robots.ox.ac.uk/~vgg/data/text/)) (MJ) and [SynthText](http://www.robots.ox.ac.uk/~vgg/data/scenetext/) (ST) without fine-tuning on other datasets. It achieves state-of-the-art results on six standard Latin scene text benchmarks, including 3 regular text datasets (IC13, SVT, IIIT) and 3 irregular ones (IC15, SVTP, CUTE). +This model was contributed by [yuekun](https://huggingface.co/yuekun). The original code can be found [here](https://github.com/AlibabaResearch/AdvancedLiterateMachinery/tree/main/OCR/MGP-STR). + +## Inference example + +[`MgpstrModel`] accepts images as input and generates three types of predictions, which represent textual information at different granularities. +The three types of predictions are fused to give the final prediction result. + +The [`ViTImageProcessor`] class is responsible for preprocessing the input image and +[`MgpstrTokenizer`] decodes the generated character tokens to the target string. The +[`MgpstrProcessor`] wraps [`ViTImageProcessor`] and [`MgpstrTokenizer`] +into a single instance to both extract the input features and decode the predicted token ids. + +- Step-by-step Optical Character Recognition (OCR) + +```py +>>> from transformers import MgpstrProcessor, MgpstrForSceneTextRecognition +>>> import requests +>>> from PIL import Image + +>>> processor = MgpstrProcessor.from_pretrained('alibaba-damo/mgp-str-base') +>>> model = MgpstrForSceneTextRecognition.from_pretrained('alibaba-damo/mgp-str-base') + +>>> # load image from the IIIT-5k dataset +>>> url = "https://i.postimg.cc/ZKwLg2Gw/367-14.png" +>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + +>>> pixel_values = processor(images=image, return_tensors="pt").pixel_values +>>> outputs = model(pixel_values) + +>>> generated_text = processor.batch_decode(outputs.logits)['generated_text'] +``` + +## MgpstrConfig + +[[autodoc]] MgpstrConfig + +## MgpstrTokenizer + +[[autodoc]] MgpstrTokenizer + - save_vocabulary + +## MgpstrProcessor + +[[autodoc]] MgpstrProcessor + - __call__ + - batch_decode + +## MgpstrModel + +[[autodoc]] MgpstrModel + - forward + +## MgpstrForSceneTextRecognition + +[[autodoc]] MgpstrForSceneTextRecognition + - forward diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mimi.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mimi.md new file mode 100644 index 0000000000000000000000000000000000000000..6e68394fcaeabca35c453347065b5f80cb989bf2 --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mimi.md @@ -0,0 +1,75 @@ + + +# Mimi + +
+PyTorch +FlashAttention +SDPA +
+ +## Overview + +The Mimi model was proposed in [Moshi: a speech-text foundation model for real-time dialogue](https://kyutai.org/Moshi.pdf) by Alexandre Défossez, Laurent Mazaré, Manu Orsini, Amélie Royer, Patrick Pérez, Hervé Jégou, Edouard Grave and Neil Zeghidour. Mimi is a high-fidelity audio codec model developed by the Kyutai team, that combines semantic and acoustic information into audio tokens running at 12Hz and a bitrate of 1.1kbps. In other words, it can be used to map audio waveforms into “audio tokens”, known as “codebooks”. + +The abstract from the paper is the following: + +*We introduce Moshi, a speech-text foundation model and full-duplex spoken dialogue framework. Current systems for spoken dialogue rely on pipelines of independent components, namely voice activity detection, speech recognition, textual dialogue and text-to-speech. Such frameworks cannot emulate the experience of real conversations. First, their complexity induces a latency of several seconds between interactions. Second, text being the intermediate modality for dialogue, non-linguistic information that modifies meaning— such as emotion or non-speech sounds— is lost in the interaction. Finally, they rely on a segmentation into speaker turns, which does not take into account overlapping speech, interruptions and interjections. Moshi solves these independent issues altogether by casting spoken dialogue as speech-to-speech generation. Starting from a text language model backbone, Moshi generates speech as tokens from the residual quantizer of a neural audio codec, while modeling separately its own speech and that of the user into parallel streams. This allows for the removal of explicit speaker turns, and the modeling of arbitrary conversational dynamics. We moreover extend the hierarchical semantic-to-acoustic token generation of previous work to first predict time-aligned text tokens as a prefix to audio tokens. Not only this “Inner Monologue” method significantly improves the linguistic quality of generated speech, but we also illustrate how it can provide streaming speech recognition and text-to-speech. Our resulting model is the first real-time full-duplex spoken large language model, with a theoretical latency of 160ms, 200ms in practice, and is available at github.com/kyutai-labs/moshi.* + +Its architecture is based on [Encodec](model_doc/encodec) with several major differences: +* it uses a much lower frame-rate. +* it uses additional transformers for encoding and decoding for better latent contextualization +* it uses a different quantization scheme: one codebook is dedicated to semantic projection. + +## Usage example + +Here is a quick example of how to encode and decode an audio using this model: + +```python +>>> from datasets import load_dataset, Audio +>>> from transformers import MimiModel, AutoFeatureExtractor +>>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + +>>> # load model and feature extractor +>>> model = MimiModel.from_pretrained("kyutai/mimi") +>>> feature_extractor = AutoFeatureExtractor.from_pretrained("kyutai/mimi") + +>>> # load audio sample +>>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) +>>> audio_sample = librispeech_dummy[-1]["audio"]["array"] +>>> inputs = feature_extractor(raw_audio=audio_sample, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt") + +>>> encoder_outputs = model.encode(inputs["input_values"], inputs["padding_mask"]) +>>> audio_values = model.decode(encoder_outputs.audio_codes, inputs["padding_mask"])[0] +>>> # or the equivalent with a forward pass +>>> audio_values = model(inputs["input_values"], inputs["padding_mask"]).audio_values +``` + +This model was contributed by [Yoach Lacombe (ylacombe)](https://huggingface.co/ylacombe). +The original code can be found [here](https://github.com/kyutai-labs/moshi). + + +## MimiConfig + +[[autodoc]] MimiConfig + +## MimiModel + +[[autodoc]] MimiModel + - decode + - encode + - forward \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral.md new file mode 100644 index 0000000000000000000000000000000000000000..097d8888f9a579a9a14720db2355f1ac897ce6bf --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral.md @@ -0,0 +1,248 @@ + + +# Mistral + +
+PyTorch +TensorFlow +Flax +FlashAttention +SDPA +
+ +## Overview + +Mistral was introduced in the [this blogpost](https://mistral.ai/news/announcing-mistral-7b/) by Albert Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lélio Renard Lavaud, Lucile Saulnier, Marie-Anne Lachaux, Pierre Stock, Teven Le Scao, Thibaut Lavril, Thomas Wang, Timothée Lacroix, William El Sayed. + +The introduction of the blog post says: + +*Mistral AI team is proud to release Mistral 7B, the most powerful language model for its size to date.* + +Mistral-7B is the first large language model (LLM) released by [mistral.ai](https://mistral.ai/). + +### Architectural details + +Mistral-7B is a decoder-only Transformer with the following architectural choices: + +- Sliding Window Attention - Trained with 8k context length and fixed cache size, with a theoretical attention span of 128K tokens +- GQA (Grouped Query Attention) - allowing faster inference and lower cache size. +- Byte-fallback BPE tokenizer - ensures that characters are never mapped to out of vocabulary tokens. + +For more details refer to the [release blog post](https://mistral.ai/news/announcing-mistral-7b/). + +### License + +`Mistral-7B` is released under the Apache 2.0 license. + +## Usage tips + +The Mistral team has released 3 checkpoints: + +- a base model, [Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1), which has been pre-trained to predict the next token on internet-scale data. +- an instruction tuned model, [Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1), which is the base model optimized for chat purposes using supervised fine-tuning (SFT) and direct preference optimization (DPO). +- an improved instruction tuned model, [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2), which improves upon v1. + +The base model can be used as follows: + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") + +>>> prompt = "My favourite condiment is" + +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +>>> model.to(device) + +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +"My favourite condiment is to ..." +``` + +The instruction tuned model can be used as follows: + +```python +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2", device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2") + +>>> messages = [ +... {"role": "user", "content": "What is your favourite condiment?"}, +... {"role": "assistant", "content": "Well, I'm quite partial to a good squeeze of fresh lemon juice. It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!"}, +... {"role": "user", "content": "Do you have mayonnaise recipes?"} +... ] + +>>> model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda") + +>>> generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +"Mayonnaise can be made as follows: (...)" +``` + +As can be seen, the instruction-tuned model requires a [chat template](../chat_templating) to be applied to make sure the inputs are prepared in the right format. + +## Speeding up Mistral by using Flash Attention + +The code snippets above showcase inference without any optimization tricks. However, one can drastically speed up the model by leveraging [Flash Attention](../perf_train_gpu_one#flash-attention-2), which is a faster implementation of the attention mechanism used inside the model. + +First, make sure to install the latest version of Flash Attention 2 to include the sliding window attention feature. + +```bash +pip install -U flash-attn --no-build-isolation +``` + +Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of the [flash attention repository](https://github.com/Dao-AILab/flash-attention). Make also sure to load your model in half-precision (e.g. `torch.float16`) + +To load and run a model using Flash Attention-2, refer to the snippet below: + +```python +>>> import torch +>>> from transformers import AutoModelForCausalLM, AutoTokenizer + +>>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16, attn_implementation="flash_attention_2", device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") + +>>> prompt = "My favourite condiment is" + +>>> model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda") +>>> model.to(device) + +>>> generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +"My favourite condiment is to (...)" +``` + +### Expected speedups + +Below is a expected speedup diagram that compares pure inference time between the native implementation in transformers using `mistralai/Mistral-7B-v0.1` checkpoint and the Flash Attention 2 version of the model. + +
+ +
+ +### Sliding window Attention + +The current implementation supports the sliding window attention mechanism and memory efficient cache management. +To enable sliding window attention, just make sure to have a `flash-attn` version that is compatible with sliding window attention (`>=2.3.0`). + +The Flash Attention-2 model uses also a more memory efficient cache slicing mechanism - as recommended per the official implementation of Mistral model that use rolling cache mechanism we keep the cache size fixed (`self.config.sliding_window`), support batched generation only for `padding_side="left"` and use the absolute position of the current token to compute the positional embedding. + +## Shrinking down Mistral using quantization + +As the Mistral model has 7 billion parameters, that would require about 14GB of GPU RAM in half precision (float16), since each parameter is stored in 2 bytes. However, one can shrink down the size of the model using [quantization](../quantization.md). If the model is quantized to 4 bits (or half a byte per parameter),that requires only about 3.5GB of RAM. + +Quantizing a model is as simple as passing a `quantization_config` to the model. Below, we'll leverage the BitsAndyBytes quantization (but refer to [this page](../quantization.md) for other quantization methods): + +```python +>>> import torch +>>> from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +>>> # specify how to quantize the model +>>> quantization_config = BitsAndBytesConfig( +... load_in_4bit=True, +... bnb_4bit_quant_type="nf4", +... bnb_4bit_compute_dtype="torch.float16", +... ) + +>>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2", quantization_config=True, device_map="auto") +>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2") + +>>> prompt = "My favourite condiment is" + +>>> messages = [ +... {"role": "user", "content": "What is your favourite condiment?"}, +... {"role": "assistant", "content": "Well, I'm quite partial to a good squeeze of fresh lemon juice. It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!"}, +... {"role": "user", "content": "Do you have mayonnaise recipes?"} +... ] + +>>> model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda") + +>>> generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True) +>>> tokenizer.batch_decode(generated_ids)[0] +"The expected output" +``` + +This model was contributed by [Younes Belkada](https://huggingface.co/ybelkada) and [Arthur Zucker](https://huggingface.co/ArthurZ) . +The original code can be found [here](https://github.com/mistralai/mistral-src). + +## Resources + +A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Mistral. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. + + + +- A demo notebook to perform supervised fine-tuning (SFT) of Mistral-7B can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Mistral/Supervised_fine_tuning_(SFT)_of_an_LLM_using_Hugging_Face_tooling.ipynb). 🌎 +- A [blog post](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl) on how to fine-tune LLMs in 2024 using Hugging Face tooling. 🌎 +- The [Alignment Handbook](https://github.com/huggingface/alignment-handbook) by Hugging Face includes scripts and recipes to perform supervised fine-tuning (SFT) and direct preference optimization with Mistral-7B. This includes scripts for full fine-tuning, QLoRa on a single GPU as well as multi-GPU fine-tuning. +- [Causal language modeling task guide](../tasks/language_modeling) + +## MistralConfig + +[[autodoc]] MistralConfig + +## MistralModel + +[[autodoc]] MistralModel + - forward + +## MistralForCausalLM + +[[autodoc]] MistralForCausalLM + - forward + +## MistralForSequenceClassification + +[[autodoc]] MistralForSequenceClassification + - forward + +## MistralForTokenClassification + +[[autodoc]] MistralForTokenClassification + - forward + +## MistralForQuestionAnswering + +[[autodoc]] MistralForQuestionAnswering +- forward + +## FlaxMistralModel + +[[autodoc]] FlaxMistralModel + - __call__ + +## FlaxMistralForCausalLM + +[[autodoc]] FlaxMistralForCausalLM + - __call__ + +## TFMistralModel + +[[autodoc]] TFMistralModel + - call + +## TFMistralForCausalLM + +[[autodoc]] TFMistralForCausalLM + - call + +## TFMistralForSequenceClassification + +[[autodoc]] TFMistralForSequenceClassification + - call \ No newline at end of file diff --git a/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral3.md b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral3.md new file mode 100644 index 0000000000000000000000000000000000000000..5b607294f659b42ee1ae2209998f26c843c1b33c --- /dev/null +++ b/tasks/tasksmith-441eeab80047/tests/source/docs/source/en/model_doc/mistral3.md @@ -0,0 +1,234 @@ + + +# Mistral3 + +## Overview + +Building upon Mistral Small 3 (2501), Mistral Small 3.1 (2503) adds state-of-the-art vision understanding and enhances long context capabilities up to 128k tokens without compromising text performance. With 24 billion parameters, this model achieves top-tier capabilities in both text and vision tasks. + +It is ideal for: +- Fast-response conversational agents. +- Low-latency function calling. +- Subject matter experts via fine-tuning. +- Local inference for hobbyists and organizations handling sensitive data. +- Programming and math reasoning. +- Long document understanding. +- Visual understanding. + +This model was contributed by [cyrilvallez](https://huggingface.co/cyrilvallez) and [yonigozlan](https://huggingface.co/yonigozlan). + +The original code can be found [here](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/models/pixtral.py) and [here](https://github.com/mistralai/mistral-common). + +## Usage example + +### Inference with Pipeline + +Here is how you can use the `image-text-to-text` pipeline to perform inference with the `Mistral3` models in just a few lines of code: +```python +>>> from transformers import pipeline + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... { +... "type": "image", +... "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", +... }, +... {"type": "text", "text": "Describe this image."}, +... ], +... }, +... ] + +>>> pipe = pipeline("image-text-to-text", model="../mistral3_weights", torch_dtype=torch.bfloat16) +>>> outputs = pipe(text=messages, max_new_tokens=50, return_full_text=False) +>>> outputs[0]["generated_text"] +'The image depicts a vibrant and lush garden scene featuring a variety of wildflowers and plants. The central focus is on a large, pinkish-purple flower, likely a Greater Celandine (Chelidonium majus), with a' +``` +### Inference on a single image + +This example demonstrates how to perform inference on a single image with the Mistral3 models using chat templates. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, +... {"type": "text", "text": "Describe this image"}, +... ], +... } +... ] + +>>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> generate_ids = model.generate(**inputs, max_new_tokens=20) +>>> decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) + +>>> decoded_output +"The image depicts two cats lying on a pink blanket. The larger cat, which appears to be an"... +``` + +### Text-only generation +This example shows how to generate text using the Mistral3 model without providing any image input. + + +````python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = ".mistralai/Mistral-Small-3.1-24B-Instruct-2503" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> SYSTEM_PROMPT = "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat." +>>> user_prompt = "Give me 5 non-formal ways to say 'See you later' in French." + +>>> messages = [ +... {"role": "system", "content": SYSTEM_PROMPT}, +... {"role": "user", "content": user_prompt}, +... ] + +>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) +>>> inputs = processor(text=text, return_tensors="pt").to(0, dtype=torch.float16) +>>> generate_ids = model.generate(**inputs, max_new_tokens=50, do_sample=False) +>>> decoded_output = processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)[0] + +>>> print(decoded_output) +"1. À plus tard! +2. Salut, à plus! +3. À toute! +4. À la prochaine! +5. Je me casse, à plus! + +``` + /\_/\ +( o.o ) + > ^ < +```" +```` + +### Batched image and text inputs +Mistral3 models also support batched image and text inputs. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +... [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, +... {"type": "text", "text": "Write a haiku for this image"}, +... ], +... }, +... ], +... [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}, +... {"type": "text", "text": "Describe this image"}, +... ], +... }, +... ], +... ] + + +>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> output = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True) +>>> decoded_outputs +["Write a haiku for this imageCalm waters reflect\nWhispers of the forest's breath\nPeace on wooden path" +, "Describe this imageThe image depicts a vibrant street scene in what appears to be a Chinatown district. The focal point is a traditional Chinese"] +``` + +### Batched multi-image input and quantization with BitsAndBytes +This implementation of the Mistral3 models supports batched text-images inputs with different number of images for each text. +This example also how to use `BitsAndBytes` to load the model in 4bit quantization. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> quantization_config = BitsAndBytesConfig(load_in_4bit=True) +>>> model = AutoModelForImageTextToText.from_pretrained( +... model_checkpoint, quantization_config=quantization_config +... ) + +>>> messages = [ +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, +...                 {"type": "text", "text": "Write a haiku for this image"}, +...             ], +...         }, +...     ], +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"}, +...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"}, +...                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"}, +...             ], +...         }, +...     ], +>>> ] + +>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> output = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True) +>>> decoded_outputs +["Write a haiku for this imageSure, here is a haiku inspired by the image:\n\nCalm lake's wooden path\nSilent forest stands guard\n", "These images depict two different landmarks. Can you identify them? Certainly! The images depict two iconic landmarks:\n\n1. The first image shows the Statue of Liberty in New York City."] +``` + + +## Mistral3Config + +[[autodoc]] Mistral3Config + + +## Mistral3ForConditionalGeneration + +[[autodoc]] Mistral3ForConditionalGeneration + - forward